如何使用foreach将datagridview记录插入mysql数据库
本文关键字:插入 mysql 数据库 记录 datagridview 何使用 foreach | 更新日期: 2023-09-27 18:25:41
此代码运行良好dataGridview中的值也会成功保存,但在将输入的值保存到数据库中后,表中还会添加一个空行
private void save_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)// picks data from dataGridview
{
try // MySql connection
{
string MyConnectionString = "Server=localhost; Database=markcreations; Uid=root; Pwd=admin";
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd = connection.CreateCommand();
cmd.Parameters.AddWithValue("@invoice", row.Cells["Invoice"].Value);
cmd.Parameters.AddWithValue("@jobOrder", row.Cells["jobOrder"].Value);
cmd.Parameters.AddWithValue("@dateTime", row.Cells["Date"].Value);
cmd.Parameters.AddWithValue("@clientCode", row.Cells["Client Code"].Value);
cmd.Parameters.AddWithValue("@clientName", row.Cells["Client Name"].Value);
cmd.CommandText = "INSERT INTO record(invoice, jobOrder, dateTime, clientCode, clientName)VALUES(@invoice, @jobOrder, @dateTime, @clientCode, @clientName)";
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Records inserted.");
}
看起来DataGridView中有一个空行,可能是最后一个,用于新行。该行的每列都有空值,如果你不检查它,它会插入空值。
您可以使用row.IsNewRow
来检查新行。
谢谢,伙计,它起作用了。
这是正确的代码和行。IsNewRow
private void button5_Click(object sender, EventArgs e)
{
string MyConnectionString = "Server=localhost; Database=markcreations; Uid=root; Pwd=admin";
MySqlConnection connection = new MySqlConnection(MyConnectionString);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
try
{
MySqlCommand cmd = new MySqlCommand();
cmd = connection.CreateCommand();
if (row.IsNewRow) continue;
cmd.Parameters.AddWithValue("@invoice", row.Cells["Invoice"].Value);
cmd.Parameters.AddWithValue("@jobOrder", row.Cells["jobOrder"].Value);
cmd.Parameters.AddWithValue("@dateTime", row.Cells["Date"].Value);
cmd.Parameters.AddWithValue("@clientCode", row.Cells["Client Code"].Value);
cmd.Parameters.AddWithValue("@clientName", row.Cells["Client Name"].Value);
cmd.Parameters.AddWithValue("@jobName", row.Cells["Job Name"].Value);
cmd.Parameters.AddWithValue("@flexQuality", row.Cells["Flex Quality"].Value);
cmd.Parameters.AddWithValue("@sizeLength", row.Cells["Size Length"].Value);
cmd.Parameters.AddWithValue("@sizeWidth", row.Cells["Size Width"].Value);
cmd.Parameters.AddWithValue("@rate", row.Cells["Rate"].Value);
cmd.CommandText = "INSERT INTO record(invoice, jobOrder, dateTime, clientCode, clientName, jobName, flexQuality, sizeLength, sizeWidth, rate)VALUES(@invoice, @jobOrder, @dateTime, @clientCode, @clientName, @jobName, @flexQuality, @sizeLength, @sizeWidth, @rate)";
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Records inserted.");
}