Xeidos
Xeidos

Reputation: 352

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!

Upvotes: 0

Views: 3001

Answers (1)

Xeidos
Xeidos

Reputation: 352

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!

Upvotes: 2

Related Questions