简体   繁体   中英

Updating MySql-Database with Datagridview C#

I have a problem: I tried to Update my MySql-Database whenever a user add a new Row, or change some Text inside. Is there a methode to "autoupdate" the Database?

I tried the following code, but it doesn´t work:

Code

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

Thank you in advance!

I found the Answer by myself:

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

There is just one question unanswered: Is there an easier way to "autoupdate" the Table or is this the only way who works? thank you in advance!

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