摘要:[C#][SQL 交易處理]
請參考MSDN
http://msdn.microsoft.com/zh-tw/library/system.data.sqlclient.sqltransaction.commit(v=vs.80).aspx
private Boolean Insertdata()
{
Boolean returnBool = true;
string SrvQid = "";
string SrvAns = "";
SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["connectionString"]);
SqlTransaction transaction;
myConnection.Open();
transaction = myConnection.BeginTransaction("SampleTransaction");
try
{
for (int i = 0; i <= Convert.ToInt16(ViewState["Qacout"]); i++)
{
string[] str1 = null; //答案陣列
str1 = ViewState["Ans" + i].ToString().Split('/');
SrvQid = str1[1];
SrvAns = str1[0];
string strSQL = "";
strSQL = strSQL + " INSERT INTO ";
strSQL = strSQL + " SurveyR3 ( ";
strSQL = strSQL + " SrvQID,";
strSQL = strSQL + " UserID,";
strSQL = strSQL + " Ans";
strSQL = strSQL + " ) values (";
strSQL = strSQL + " @SrvQID, ";
strSQL = strSQL + " @UserID, ";
strSQL = strSQL + " @ANS ";
strSQL = strSQL + " ) ";
SqlCommand cmd = new SqlCommand(strSQL, myConnection, transaction);
cmd.Parameters.Add("@SrvQID", SqlDbType.NChar, 36).Value = SrvQid.Trim();
cmd.Parameters.Add("@UserID", SqlDbType.NChar, 36).Value = "";
cmd.Parameters.Add("@ANS", SqlDbType.NChar, 255).Value = SrvAns.Trim();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
returnBool = true;
transaction.Commit();
}
catch (Exception)
{
returnBool = false;
transaction.Rollback();
myConnection.Close();
}
finally {
if (myConnection.State == ConnectionState.Open) {
myConnection.Close();
}
}
return returnBool;
}
※自己的用法資料來源是 跑迴圈去取出來的
然後一筆一筆塞
若以上方法有錯誤的話歡迎留言指正 謝謝
小弟不知道這樣的方法對不對
後來經過 lbwshift2 :大大指正後
再改過的程式如上