简体   繁体   中英

How to make insert operation using MySqlDataAdapter in ASP.NET

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.

string sid, sname;
            sid = Request.QueryString["StudentId"].ToString();
            sname = Request.QueryString["StudentName"].ToString();
            MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
          //  con.Open();
        //    MySqlCommand cmd = con.CreateCommand();
      //      cmd.CommandType = CommandType.Text;
    //        cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
  //          cmd.ExecuteNonQuery();
//            con.Close();

Help with suggestions.

To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record

However if you really want to try to use an DataAdapter then you need this code

string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
     MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
     DataTable dt = new DataTable();
     da.Fill(dt);
     // This is important, because Update will work only on rows
     // present in the DataTable whose RowState is Added, Modified or Deleted
     dt.Rows.Add(sid, sname);
     da.Update(dt);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM