使用ADO.NET执行SQL脚本

时间:2022-06-28 07:27:36
public void ExecuteSql(SqlConnection connection, string sqlFile)
{
string sql = ""; using (FileStream strm = File.OpenRead(sqlFile))
{
StreamReader reader = new StreamReader(strm);
sql = reader.ReadToEnd();
} Regex regex = new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline);
string[] lines = regex.Split(sql); SqlTransaction transaction = connection.BeginTransaction();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.Connection = connection;
cmd.Transaction = transaction; foreach (string line in lines)
{
if (line.Length > 0)
{
cmd.CommandText = line;
cmd.CommandType = CommandType.Text; try
{
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
transaction.Rollback();
throw;
}
}
}
} transaction.Commit();
}

  原文地址:https://matt.berther.io/2005/04/11/executing-a-sql-script-using-adonet/