c#通过for循环多次向数据库中插入数据。
2个回答
展开全部
你的问题不甚清晰。需要插入的数据来源是在窗体中吗?SQL需要拼接吗?
给你一段代码参考,这段代码是将窗体中dataGridView中的数据循环插入数据库,循环过程中拼接SQL,并执行插入:
//主方法,拼接SQL并执行插入
private int InsertInTo()
{
StringBuilder sqlinsert = new StringBuilder();
StringBuilder sqlvalue = new StringBuilder();
sqlinsert.Append(" insert into 你的表名 ( ");
sqlvalue.Append(" values(");
int num = 0;//该变量用来获取插入多少条数据
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int c = 0; c < dataGridView1.Columns.Count; c++)
{
sqlinsert.Append(dataGridView1.Columns[c].HeaderText + ",");//赋值列名
sqlvalue.Append("'" + dataGridView1.Rows[i].Cells[c].Value.ToString() + "'");//赋值列对应的值
}
string sql = sqlinsert.ToString().Substring(0, sqlinsert.Length - 1) + ") " + sqlvalue.ToString().Substring(0, sqlvalue.Length - 1) + ")";//拼接完整插入SQL
num += Insert(sql);//调用插入方法,并接收返回的插入行数
}
return num;
}
//连接数据库并执行SQL
private int Insert(string sql)
{
string connstring = "server=127.0.0.1\\SQLEXPRESS;database=你的数据库名;uid=用户名;pwd=密码";
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
int n = cmd.ExecuteNonQuery();//执行
conn.Close();
cmd.Dispose();
return n;
}
赋值列名时可以放在循环外只赋值一次。
展开全部
List<string> sqls=new List<string>(){sql1,sql2,sql3...};
int row=0;
using (SqlConnection Connection = new SqlConnection(ConnectionString))
{
SqlTransaction transaction=null;
SqlCommand Command=null;
try{
Connection.Open();
transaction = Connection.BeginTransaction();
foreach(string SQL in sqls)
{
Command = new SqlCommand(SQL, Connection, transaction);
rows = Command.ExecuteNonQuery();
if (rows<=0)//失败
{
transaction.Rollback();
break;
}
}
}
catch(Exception ex)
{
try
{
transaction.Rollback();
}
catch { }
}
if(rows>0)//成功
transaction.Commit();
}
int row=0;
using (SqlConnection Connection = new SqlConnection(ConnectionString))
{
SqlTransaction transaction=null;
SqlCommand Command=null;
try{
Connection.Open();
transaction = Connection.BeginTransaction();
foreach(string SQL in sqls)
{
Command = new SqlCommand(SQL, Connection, transaction);
rows = Command.ExecuteNonQuery();
if (rows<=0)//失败
{
transaction.Rollback();
break;
}
}
}
catch(Exception ex)
{
try
{
transaction.Rollback();
}
catch { }
}
if(rows>0)//成功
transaction.Commit();
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询