使用Datagridview C#更新MySql-Database

时间:2014-10-13 08:03:04

标签: c# mysql datagridview

我遇到了问题:每当用户添加新行或更改内部文本时,我都会尝试更新MySql数据库。是否存在“自动更新”数据库的方法?

我尝试了以下代码,但它不起作用:

代码

private MySqlDataAdapter da;        // Data Adapter
private DataSet ds;                 // Dataset
try
{
  MySqlConnection conn = new MySqlConnection(
           "datasource=localhost;port=3306;username=root;password=123");
  conn.Open();
  MySqlCommandBuilder cmb = new MySqlCommandBuilder(da);
  da.Fill(ds);
  da.Update(ds);                
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
   MessageBox.Show(ex.Message);
}

提前谢谢!

1 个答案:

答案 0 :(得分:2)

我自己找到答案:

<强> CODE

string connStr = "datasource=localhost;port=3306;username=root;password=Achilles44";
MySqlConnection conn = new MySqlConnection(connStr);

try
{
    string sql = "select *from test.edata ;";
    MySqlDataAdapter da = new MySqlDataAdapter(sql,conn);
    MySqlCommandBuilder cb = new MySqlCommandBuilder(da);

    MySqlCommand cmd = new MySqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = sql;

    MySqlCommand insertCmd =cb.GetInsertCommand().Clone();
    insertCmd.CommandText = insertCmd.CommandText +";SELECT last_insert_id() AS id";
    insertCmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
    da.InsertCommand = insertCmd;
    cb.DataAdapter = null;

    DataTable dt = new DataTable();
    da.Fill(dt);

    DataRow row = dt.NewRow();
    row["Familienname"] = " Schischka";
    row["Eid"] = 7;
    row["Vorname"] = "Hannes";
    row["age"] = "20";
    dt.Rows.Add(row);
    da.Update(dt);

    conn.Close();




}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

只有一个问题没有答案:是否有一种更简单的方法可以自动更新&#34;表或这是唯一的工作方式?提前谢谢你!