c# 事务处理
1 创建一个connection
string connstr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(connstr);
2 创建一个command 连接到 connection上
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlconn;
3 创建一个 transaction 当 connection 打开的时候将事务和connection 绑定 然后将transaction也和command绑定
SqlTransaction sqltran;
sqlconn.Open();
sqltran = sqlconn.BeginTransaction();
cmd.Transaction = sqltran;
4 处理
try
{
StreamReader sr = new StreamReader(postedFile.InputStream);
string headLine = sr.ReadLine();
headLine = headLine.Replace(";", "],[");
headLine = "[" + headLine + "]";
int lineNumber = 1;
while (!sr.EndOfStream)
{
string saleDataLine = sr.ReadLine();
//rdLine = rdLine.Replace("N/A", "null");
saleDataLine = saleDataLine.Replace("'", "''");
saleDataLine = saleDataLine.Replace(";", "','");
string command = "insert into SalesUploadTest (" + headLine + ") values ('" + saleDataLine + "')";
cmd.CommandText = command;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
lineNumber++;
}
sqltran.Commit();
}
catch (Exception)
{
sqltran.Rollback();
}
finally
{
cmd.Dispose();
sqlconn.Close();
}