C#连接数据库最基本操作之sql语句 DML

时间:2021-10-31 03:53:00

C#连接数据库最基本操作之sql语句 DML

 

            //1   连接字符串
            string connectionString
                = "server=127.0.0.1;integrated security=true;database=MSPetShop4";
            // = "server=.;uid=sa;pwd=SQL@5;database=AdventureWorks2012";
            // = "server=.;user id=sa;password=SQL@5;database=AdventureWorks2012";
            //2 实例化数据库连接
            System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString);

            //也可以先实例化
            //System.Data.SqlClient.SqlConnection connection = new SqlConnection();
            //然后再设置ConnectionString 属性.
            //connection.ConnectionString = connectionString;

            try
            {
                //3 打开连接
                connection.Open();
                Console.WriteLine("成功连接数据计库MSPetShop4");
                //4 数据访问对象
                //sql字符串
                //string sql = "SELECT [客户],[产品],[数量] FROM A ";
                string sql = "insert into A(客户,产品,数量) values('biangongxin','阿特滋',2);";
                //SqlCommand 表示数据库要执行的sql命令
                System.Data.SqlClient.SqlCommand command = new SqlCommand(sql, connection);
                //ExecuteNonQuery 非查询语句
                //默认工作在自动事务之下,直接提交
                //执行sql DML 之前,手动开启
                System.Data.SqlClient.SqlTransaction trans =  connection.BeginTransaction();
                //设置命令所属的事务管理
                command.Transaction = trans;
                int result =  command.ExecuteNonQuery();
                Console.WriteLine(result);

                Console.Write("SQL命令已经提交,但是事务还未提交,是否继续执行(Y/N)");
                string ans = Console.ReadLine();
                if (ans.Substring(0, 1).ToUpper() == "Y")
                {

                    //提交事务
                    trans.Commit();
                }
                else
                {
                    //回滚事务;
                    trans.Rollback();
                }
            }
            catch(System.Data.SqlClient.SqlException exception)
            {
                Console.WriteLine(exception.Message);
            }

            finally
            {
                //4 注销连接
                connection.Dispose();
                Console.WriteLine("成功断开数据计库MSPetShop4");
            }
            Console.ReadLine();