连接sql2005数据库文件和事务

时间:2022-01-17 20:48:06

Data Source=./SQLEXPRESS;AttachDbFilename="C:/Documents and Settings/Administrator/桌面/MrNetShop_51aspx/App_Data/db_NetShop.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True

 


//使用事务

 

    SqlConnection con = new SqlConnection("连接字符串");
        con.Open();
        SqlTransaction myTrans = con.BeginTransaction(); //事务开始
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "sql语句";
        cmd.Transaction = myTrans;
        try
        {
            cmd.ExecuteNonQuery();
            myTrans.Commit();  //提交事务
        }
        catch
        {
            myTrans.Rollback(); //事务回滚
        }
        finally
        {
            con.Close();
            myTrans.Dispose();
        }