C#中连接SqlServer数据库并且使用事务和using语句的实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace test2
{
    class Program
    {
        static void Main(string[] args)
        {
            string connString = "Data Source=127.0.0.1;" +
                "Persist Security Info=True;" +
                "Initial Catalog=TestSql;" +
                "Integrated Security=false;" +
                "User ID=sa;" +
                "Password=root123;";

            using (SqlConnection conn = new SqlConnection(connString))  //使用using语句块,可确保关闭数据库连接
            {
                conn.Open();
                Console.WriteLine("open database successfully!!!");

                SqlCommand command = conn.CreateCommand();
                SqlTransaction tx;
                tx = conn.BeginTransaction("SampleTransaction");//启动一个本地事务管理
                //为了将要发生的本地事务,必须将Transaction对象和SqlConnection对象赋值给SqlCommand对象
                command.Connection = conn;//指定要执行数据操作的数据源
                command.Transaction = tx;//指定执行数据命令登记的事务对象
                try
                {
                    command.CommandText = "insert into employee (username,password) values('LiuYe','456')";
                    int rowsReturned = command.ExecuteNonQuery();
                    Console.WriteLine("{0}记录已更新", rowsReturned);
                    //提交事务
                    tx.Commit();
                    Console.WriteLine("record is written to database.");

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.GetType());
                    Console.WriteLine("connection Exception!!!");
                    try
                    {
                        //不成功时回滚
                        tx.Rollback();
                    }
                    catch (Exception ex)
                    {
                        //这个catch块处理任何回滚失败的异常,例如数据库断开的连接。
                        Console.WriteLine("Rollback Exception Type:{0}", ex.GetType());
                        Console.WriteLine("Message:{0}", ex.Message);
                    }
                }
            }
        }
    }
}
             

        

展开阅读全文

没有更多推荐了,返回首页