【C#.NET】dataGridView1的資料匯入到SQL資料庫中
阿新 • • 發佈:2019-01-28
//將dataGridView1的資料匯入到SQL資料庫中
public void DataGridViewToSql()
{
SqlConnection conn = new SqlConnection("server=yoti,6060; user id = sa; pwd = 2950001; database = hbposev9");
try
{
conn.Open();
for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
{
SqlCommand comm = new SqlCommand();
string gdh = this.dataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
string pn = this.dataGridView1.Rows[i].Cells[1].Value.ToString().Trim();
string SqlStr = "INSERT testbiao(sheet222,名稱) VALUES ('" + gdh + "','" + pn + "')";
comm.CommandText = SqlStr;
comm.Connection = conn;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("更新失敗,失敗原因:" + ex.Message);
}
finally
{
conn.Close();
}
}
//Cells行。Rows列
public void DataGridViewToSql()
{
SqlConnection conn = new SqlConnection("server=yoti,6060; user id = sa; pwd = 2950001; database = hbposev9");
try
{
conn.Open();
for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
{
SqlCommand comm = new SqlCommand();
string gdh = this.dataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
string pn = this.dataGridView1.Rows[i].Cells[1].Value.ToString().Trim();
string SqlStr = "INSERT testbiao(sheet222,名稱) VALUES ('" + gdh + "','" + pn + "')";
comm.CommandText = SqlStr;
comm.Connection = conn;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("更新失敗,失敗原因:" + ex.Message);
}
finally
{
conn.Close();
}
}
//Cells行。Rows列