[英]How to save DataGridView multiple row data in to MySQL database in c#
我在一列中有多個行數據。 我需要將所有數據保存到MySQL數據庫中。 但這僅將選定的行數據保存在DataGridView中。
以下是我的示例代碼。
private void button1_Click(object sender, EventArgs e)
{
string price = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price +"');";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = MySQLcmd.ExecuteReader();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
感謝任何幫助🙂謝謝!
一種方法是使用Foreach循環在DataGridView中一一獲取所有行的值,然后將其插入。
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = "Connection String";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db1.table1 (price) VALUES (@price", con))
{
cmd.Parameters.AddWithValue("@price", row.Cells["ColumnName"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
如果要保存Gridview中的所有行,請遍歷它並選擇要保存的列值。
另外,如果要保存/更新到數據庫,則應使用ExecuteNonQuery 。 最后,處理要創建的對象以及使用的原因。
using (MySqlConnection myConn = new MySqlConnection(MySQLConn))
{
myConn.Open();
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlParameter priceParameter = new MySqlParameter("@price");
MySQLcmd.Parameters.Add(priceParameter);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var price = row.Cells["PRICE_COLUMN_NAME"].Value;
MySQLcmd.Parameters["@price"].Value = price;
MySQLcmd.ExecuteNonQuery();
}
}
尊敬的mbharanidharan88和user3501749 :感謝您的快速支持。 有了您的支持,我喜歡了一個新代碼。 以下是我的完整工作代碼(對我而言)。
private void button1_Click(object sender, EventArgs e)
{
try
{
string MySQLConn = "datasource=localhost;port=3306;username=root;password=root;";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
myConn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string price = dataGridView1.Rows[i].Cells[3].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price + "');";
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySQLcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
如果有什么問題讓我知道🙂
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.