C#怎样实现批量更新sql数据,贴个例子上来好吗.
简单用控制台实现一个例子:
// 换上你的数据库连接字符串即可,还有一个UserInfo表
class Program
{
private static string connectionString = "Server = localhost;Initial Catalog=test;User ID= sa;Password =sa";
//存放sql语句的可变数组
private static ArrayList msqlArr;
static void Main(string[] args)
{
msqlArr = new ArrayList();
msqlArr.Add("INSERT INTO UserInfo (No,Name) VALUES('1','1')");
msqlArr.Add("INSERT INTO UserInfo (No,Name) VALUES('2','2')");
msqlArr.Add("INSERT INTO UserInfo (No,Name) VALUES('112233','2')");
msqlArr.Add("DELETE FROM UserInfo WHERE No = '112233'");
ExecuteSqlTransaction(msqlArr);
}
/// <summary>
/// 用一个事务来批量执行sql语句
/// </summary>
/// <param name="sqlArr">存放sql语句(s)的字符串数组</param>
public static void ExecuteSqlTransaction(ArrayList sqlArr)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// 开始一个事务
transaction = connection.BeginTransaction("SampleTransaction");
//必须给命令对象(command)的连接和事务相应的值
command.Connection = connection;
command.Transaction = transaction;
try
{
//在一个事务里执行多条sql语句
for (int i = 0; i < sqlArr.Count; i++)
{
command.CommandText = sqlArr[i].ToString();
command.ExecuteNonQuery();
}
// 提交事务
transaction.Commit();
Console.WriteLine("sql执行成功!");
}
catch (Exception ex)
{
//执行sql过程中出错,即事务回滚
transaction.Rollback();
Console.WriteLine("错误信息:" + ex.Message );
}
}
}
}
执行效果:
ps:批量执行(更新)sql,最后用事务处理,好处是,遇到某条语句出错,可以回滚。
SqlTransaction。
var transcation=conn.BetinTranscation();
........
transcation.Commit();