0

我有以下代码

MySqlConnection myCon = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["mySQLCon"]);
MySqlDataAdapter dAdap = new MySqlDataAdapter();
dAdap.InsertCommand = new MySqlCommand("insert into PMduedates(eCId,ECClass,ddate,PMType) values(eCId,ECClass,ddate,PMType)", myCon);
dAdap.InsertCommand.Parameters.Add("eCId", MySqlDbType.VarChar, 20, "eqpID");
dAdap.InsertCommand.Parameters.Add("ECClass", MySqlDbType.VarChar, 100, "class");
dAdap.InsertCommand.Parameters.Add("ddate", MySqlDbType.VarChar, 100, "MaintType");
dAdap.InsertCommand.Parameters.Add("PMType", MySqlDbType.Date, 10, "Duedate");
myCon.Open();
dAdap.Update(dtDue);
myCon.Close();

在上面的代码中,dtDue 是一个数据表,eqpID、class、MaintType 和 Duedate 是数据列。当我执行代码时,它没有给出任何错误,但表 PMduedates 中的数据没有更新。

4

2 回答 2

1

为什么要在中DataAdapter插入记录DataTable?没有人告诉它这样做。仅当它们位于时才会插入行RowState.Added,您可以通过以下方式强制它:

foreach (DataRow row in dtDue.Rows)
    row.SetAdded();

但由于无论如何您都是手动提供插入命令和参数,我也会手动执行查询:

using(var myCon = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["mySQLCon"]))
using(var cmd = new MySqlCommand("insert into PMduedates(eCId,ECClass,ddate,PMType) values(eCId,ECClass,ddate,PMType)", myCon))
{
    cmd.InsertCommand.Parameters.Add("eCId", MySqlDbType.VarChar, 20, "eqpID");
    cmd.InsertCommand.Parameters.Add("ECClass", MySqlDbType.VarChar, 100, "class");
    cmd.InsertCommand.Parameters.Add("ddate", MySqlDbType.VarChar, 100, "MaintType");
    cmd.InsertCommand.Parameters.Add("PMType", MySqlDbType.Date, 10, "Duedate");
    myCon.Open();
    int countInserted = cmd.ExecuteNonQuery();
} // using closes the connection implicitely
于 2013-07-24T07:44:09.303 回答
0

我认为问题在于您已将参数和列命名为相同的更改参数名称,例如尝试以下操作:

MySqlConnection myCon = new MySqlConnection(System.Configuration.ConfigurationManager.AppSettings["mySQLCon"]);
MySqlDataAdapter dAdap = new MySqlDataAdapter();
dAdap.InsertCommand = new MySqlCommand("insert into PMduedates(eqpID,class,Duedate,MaintType) values(@eCId,@ECClass,@ddate,@PMType)", myCon);
dAdap.InsertCommand.Parameters.Add("@eCId", MySqlDbType.VarChar, 20, "eqpID");
dAdap.InsertCommand.Parameters.Add("@ECClass", MySqlDbType.VarChar, 100, "class");
dAdap.InsertCommand.Parameters.Add("@ddate", MySqlDbType.VarChar, 100, "MaintType");
dAdap.InsertCommand.Parameters.Add("@PMType", MySqlDbType.Date, 10, "Duedate");
myCon.Open();
dAdap.Update(dtDue);
myCon.Close();
于 2013-07-24T07:44:01.510 回答