zoukankan      html  css  js  c++  java
  • 用ADO.NET来使用事务

    先把代码段记下来,省得到时候要用的时候再去翻硬盘中的源文件

    代码
    string connString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            SqlConnection conn 
    = new SqlConnection(connString);
            conn.Open();
            SqlTransaction tran 
    = conn.BeginTransaction();    //创建事务Transaction

            
    string strSQL = "INSERT INTO Employees(FirstName, LastName, City, Address) values (@paramFirstName,@paramLastName,@paramCity,@paramAddress)";
            SqlCommand cmd 
    = new SqlCommand(strSQL, conn,tran);        //创建SqlCommand

            
    try
            {
                cmd.Parameters.Add(
    "@paramFirstName", SqlDbType.NVarChar, 20).Value = txtFirstName.Text;
                cmd.Parameters.Add(
    "@paramLastName", SqlDbType.NVarChar, 10).Value = txtLastName.Text;
                cmd.Parameters.Add(
    "@paramCity", SqlDbType.NVarChar, 15).Value = txtCity.Text;
                cmd.Parameters.Add(
    "@paramAddress", SqlDbType.NVarChar, 60).Value = txtAddress.Text;
                cmd.ExecuteNonQuery();
                tran.Commit();        
    //确认事务
                txtMsg.Text = "新增数据成功,事务确认!";
            }
            
    catch
            {
                tran.Rollback();   
    //事务回滚
                txtMsg.Text = "新增数据失败,事务Rollback!";
            }

            
    finally
            {
                conn.Close();
                conn.Dispose();
                tran.Dispose();
                cmd.Dispose();
            }


    撸码:复制、粘贴,拿起键盘就是“干”!!!
  • 相关阅读:
    Will Go eventually replace C++ as Google hoped when Go came out?
    5G到底什么时候来,它究竟能给我们带来什么?
    eog——Eye of GNOME Image Viewer
    Appweb——Embedded Web Server
    【2017】数字重排
    【9203】众数
    【2034】四人投票
    【9204】第k小整数
    【2031】求一元三次方程的解
    iOS 7: 如何为iPhone 5s编译64位应用
  • 原文地址:https://www.cnblogs.com/niunan/p/1696842.html
Copyright © 2011-2022 走看看