利用C#事務處理對數據庫進行多重操做

C# codesql

SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCnn;
sqlCmd.Transaction = sqlCnn.BeginTransaction(); //完成事務處理的前期準備工做數據庫

try
{
//將用戶註冊的數據寫入數據庫
string sqlCmd1 = "insert into User_Login (user_id,user_pwd) values('" + User_ID + "','" + User_PWD + "')";
string sqlCmd2 = "insert into User_Data_Basic values('" + User_ID + "','" + User_Name + "','" + User_Sex + "'," + User_Age_Year + "," + User_Age_Month + "," + User_Age_Day + ",'','','','','')";
string sqlCmd3 = "insert into user_data_comunication (user_id) values ('" + User_ID + "')";
string sqlCmd4 = "insert into user_data_like (user_id) values ('" + User_ID + "')";
string sqlCmd5 = "insert into user_data_schooldata (user_id) values ('" + User_ID + "')";
//string sqlCmd6 = "insert into user_data_status (user_id,user_status_date) values ('" + User_ID + "','" + System.DateTime.Now + "')";this

string[] SQLstringList = { sqlCmd1, sqlCmd2, sqlCmd3, sqlCmd4, sqlCmd5 };
for (int i = 0; i < SQLstringList.Length; i++)
{
string SQLstr = SQLstringList[i].ToString();
if (SQLstr.Trim().Length > 1)
{
sqlCmd.CommandText = SQLstr;
sqlCmd.ExecuteNonQuery();
}
}
sqlCmd.Transaction.Commit();
}
catch (Exception exe)
{
sqlCmd.Transaction.Rollback();
flag = false;
//this.FinalCheck.Text = exe.Message.ToString();
}
finally 
{
//關閉數據庫
sqlCnn.Close();
}code

相關文章
相關標籤/搜索