我试图使用datagridview
将数据插入数据库,我正在使用以下代码,但是它添加了多条单条记录的记录,任何帮助都可以做到
string connectionString =
"Data Source=S;Initial Catalog=Gits_Retailer;User ID=sa;Password=sa";
SqlConnection SqlConn = new SqlConnection(connectionString);
SqlConn.Open();
DataSet ds = new DataSet();
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
SqlDataAdapter da =
new SqlDataAdapter("INSERT INTO unit_master VALUES('"
+ dataGridView1.Rows[i].Cells[0].Value
+ "')", SqlConn);
da.Fill(ds);
SqlConn.Close()
}
答案 0 :(得分:0)
第一次插入DB会成功,但任何后续操作都会失败,你正在关闭for循环中的SqlConnection。
答案 1 :(得分:0)
试试这个
string connectionString =
"Data Source=S;Initial Catalog=Gits_Retailer;User ID=sa;Password=sa";
SqlConnection SqlConn = new SqlConnection(connectionString);
SqlConn.Open();
DataSet ds = new DataSet();
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
SqlDataAdapter da =
new SqlDataAdapter("INSERT INTO unit_master VALUES('"
+ dataGridView1.Rows[i].Cells[0].Value
+ "')", SqlConn);
da.Fill(ds);
}
SqlConn.Close()
答案 2 :(得分:0)
试试这个
string connectionString =
"Data Source=S;Initial Catalog=Gits_Retailer;User ID=sa;Password=sa";
SqlConnection SqlConn = new SqlConnection(connectionString);
SqlConn.Open();
SqlCommand cmd = SqlConn.CreateCommand();
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
cmd.CommandText ="INSERT INTO unit_master VALUES('"
+ dataGridView1.Rows[i].Cells[0].Value
+ "')";
cmd.ExecuteNonQuery();
}
SqlConn.Close();