简体   繁体   English

如何在ASP.NET中使用MySqlDataAdapter进行插入操作

[英]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 ? 如何使用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. 要插入一条记录,您可以简单地使用MySqlCommand代替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. MySqlDataAdapter具有许多功能,允许您对数据执行插入,更新和删除操作,但是首先需要到达服务器以填充数据表,然后将新记录添加到数据表中,最后调用更新。 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 但是,如果您真的想尝试使用DataAdapter,则需要此代码

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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