//2015/07/03
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient; namespace Ado.netstart_1
{
class Program
{
static void Main(string[] args)
{
//特殊的字符串,数据库连接串
//第一种
string connectionString = "server=.;database=BookSample;uid=LJK;pwd=123456;";
//第二种
//windows身份验证
//当使用windows身份验证的时候,windows用户就是运行程序的用户
//string connectionString = "server=.;integrated security=true;database=BookSample"; //用来访问数据库的类
SqlConnection connection = new SqlConnection(connectionString); try
{
//与数据库建立连接
connection.Open();
Console.WriteLine("已经建立连接"); //sql就是一个字符串
string sql = "insert into students(ID,StuName,Phone,Address,City,State) values(7,'aaa','1318697125','zz','bb','ccc')";
//SqlCommand 表示发送数据库执行SQL命令
SqlCommand command = new SqlCommand(sql,connection);
//将命令发送到数据库执行
//sql语句可分为:查询语句和非查询语句 //默认工作在自动事务之下
//如果工作在手动事务之下
//begin transaction
//rollback / commit //在执行sql dml之前,启动事务
SqlTransaction trans = connection.BeginTransaction();//事务对象 //设定命令所属的事务管理
command.Transaction = trans; int effectCount = command.ExecuteNonQuery();
Console.WriteLine("{0} 行受影响",effectCount); Console.Write("命令已经执行,事务还没有提交,你确定提交吗?Y/N");
string line = Console.ReadLine();
if (line.Substring(, ).ToUpper() == "Y")
{
trans.Commit();
Console.WriteLine("事务已经提交");
}
else
{
trans.Rollback();
Console.WriteLine("事务已经回滚");
}
}
catch (SqlException exception)
{
Console.WriteLine(exception.Message);
}
finally
{
//或者断开与数据库的连接
connection.Dispose();
//connection.Close();
Console.WriteLine("已经断开连接");
}
Console.ReadKey();
}
}
}