- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- namespace CommandDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- SqlConnection connection = new SqlConnection();
- SqlTransaction objTrans = null;
- connection.ConnectionString = "Persist Security Info=False;User ID=administrator;Password=zenq;Initial Catalog=StuDB;Data Source=.";
- try
- {
- connection.Open();
- objTrans = connection.BeginTransaction();
- /*SqlCommand sqlCmd = new SqlCommand();
- sqlCmd.Connection = connection;*/
- SqlCommand sqlCmd = connection.CreateCommand();
- sqlCmd.Transaction = objTrans;
- sqlCmd.CommandType = CommandType.Text;
- sqlCmd.CommandText = "insert into Students(Name,Sex,Birthday) values('Jone',1,'2005-5-1')";
- sqlCmd.ExecuteNonQuery();
- sqlCmd.CommandText = "insert into Students(Name,Sex,Birthday) values('Jone',1,'2005-5-1')";
- sqlCmd.ExecuteNonQuery();
- objTrans.Commit();
- Console.WriteLine("添加成功!");
- }
- catch (SqlException ex)
- {
- Console.WriteLine(ex.Message);
- if (objTrans != null)
- {
- objTrans.Rollback();
- }
- }
- finally
- {
- if (connection.State != ConnectionState.Open)
- {
- connection.Close();
- }
- }
- Console.ReadKey();
- }
- }
- }