ADO.NET 之sqlConnection 对象使用摘要

来源:互联网 发布:混血失败知乎 编辑:程序博客网 时间:2024/06/06 04:54

3.1 生成sqlConnection对象

string strConnection ='Data source=.;initial catalog=northwid';

sqlConnection cn = new sqlConnection(strConnection);

 

3.2打开sqlConnection对象

cn.Open();

 

3.3关闭sqlConnection对象

cn.Close();

 

 

3.4自行清除连接

使用using块,确保调用Close方法

 

using (sqlConnection cn = new sqlConnection(strConnection))

{

  cn.Open()

}//执行到这个块时,会隐式调用Close();方法

 

 

3.5.2连接字符串生成器

SqlConnectionStringBuilder sb= new SqlConnectionStringBuilder();

sb['Datab Source']=@'./SQLExpress';

sb['Initital Catalog']='Northwind';

sb['Intergrated Security']=true;

 

//获取字串

string strConnection = sb.ConnectionString;

 

3.7.1创建sqlCommand

 

DBCommand cmd = cn.CreateCommand();

cmd.CommandText ='select 1 + 1';

cmd.ExecuteNonQuery();

cmd.CommandText ='Insert into ...';

cmd.ExecuteNonQuery();

 

3.7.2开始使用sqlTransaction

sqlConnection cn = new sqlConnection(strConnection);

cn.open();

sqlTransaction tn = cn.BeginTransaction();

 

3.7.3获取架构信息

DataTable tb = cn.GetSchema('Tables');

foreach(DataRow row in tb.rows)

 Console.Write(row['TABLE_NAME']);