我目前正在开发一个将 MySql 与 C# 结合使用的项目。DataGridView 的数据由数据库中多个表的连接提供。为了显示数据,我使用以下工作代码:
adapter.SelectCommand = new MySqlCommand(
" SELECT" +
" l.lot AS Lot, "+
" m.comment AS Bemerkungen," +
... (multiple columns from different tables) ...
" FROM m " +
" JOIN m2p ON m.m2p_id = m2p.id" +
... (more joins) ...
, this._mySqlConnection);
dataGridView1.DataSource = data;
adapter.Fill(data);
现在允许 GUI 的用户修改某个列(“评论”列)。所以我为事件分配了一个 eventHandler CellEndEdit
,当用户修改了允许的列时,adapter.Update(data)
就会调用它。现在这不会执行正确的操作。
为了定义我的更新命令,我使用了以下代码:
adapter.UpdateCommand = new MySqlCommand(
" UPDATE m" +
" JOIN l ON m.l_id = l.id" +
" SET m.comment = @comment" +
" WHERE l.lot = @lot"
, this._mySqlConnection);
adapter.UpdateCommand.Parameters.Add("@comment", MySqlDbType.Text, 256, "Bemerkungen");
adapter.UpdateCommand.Parameters.Add("@lot", MySqlDbType.Text, 256, "Lot");
你能解释一下我如何修复我的代码以自动更新数据库吗?
编辑:添加了更多源代码:
private MySqlDataAdapter warenlagerMySqlDataAdapter, kundenMySqlDataAdapter;
private DataTable warenlagerData, kundenData;
private DataGridView warenlagerGridView;
private void updateWarenlagerView(object sender, EventArgs e) {
warenlagerMySqlDataAdapter.Update(warenlagerData);
}
private void initialzeFields() {
warenlagerGridView.CellEndEdit += new DataGridViewCellEventHandler(this.updateWarenlagerView);
warenlagerMySqlDataAdapter = new MySqlDataAdapter();
warenlagerData = new DataTable();
}
private void initializeWarenlagerView() {
warenlagerMySqlDataAdapter.SelectCommand = new MySqlCommand(
" SELECT" +
" c.name AS Ursprung, " +
" m2p.art_nr AS ArtNr," +
" m.delivery_date AS Eingangsdatum," +
" CONCAT(FORMAT(m.delivery_amount / 100, 2), 'kg') AS Eingangsmenge, " +
" l.lot AS Lot," +
" m.quality AS Qualität," +
" m.comment AS Bemerkungen," +
" CONCAT(m.units, 'kg') AS Units," +
" CONCAT(FORMAT(s.amount / 100, 2), 'kg') AS Lagermenge, " +
" FORMAT(m.base_price / 100, 2) AS Einkaufspreis," +
" FORMAT(s.amount/10000 * m.base_price, 2) AS Wert" +
" FROM mushrooms AS m " +
" JOIN mushroom2path AS m2p ON m.mushroom2path_id = m2p.id" +
" JOIN countries AS c ON m.origin_id = c.id" +
" JOIN lots AS l ON m.lot_id = l.id" +
" JOIN stock AS s ON s.mushrooms_id = m.id"
, this._mySqlConnection);
warenlagerGridView.DataSource = warenlagerData;
warenlagerMySqlDataAdapter.Fill(warenlagerData);
warenlagerMySqlDataAdapter.UpdateCommand = new MySqlCommand(
" UPDATE mushrooms AS m" +
" JOIN lots AS l ON m.lot_id = l.id" +
" SET m.comment = @comment" +
" WHERE l.lot = @lot"
, this._mySqlConnection);
warenlagerMySqlDataAdapter.UpdateCommand.Parameters.Add("@comment", MySqlDbType.Text, 256, "Bemerkungen");
warenlagerMySqlDataAdapter.UpdateCommand.Parameters.Add("@lot", MySqlDbType.Text, 256, "Lot");
}
这是有关此问题的全部代码。我 100% 确定该adapter.Update(data)
方法被调用(调试)。传递给该adapter.Update()
方法的数据包含新数据。