1、使用new关键字直接创建对象的一个实例,然后设置适当的属性:

string strConn,strSql;

strConn=@"Data Source=.\SQLExpress;"+"Initial Catalog=Northwind;Trusted_Connection=Yes";

strSql="SELECT CustomerID, CompanyName FROM Customers";

SqlConnection cn=new SqlConnection(strConn);

cn.Open();

SqlCommand cmd;

 

cmd=new SqlCommand();

cmd.Connection=cn;

cmd.CommandText=strSql;

2、使用一个构造函数来制定查询字符串和SqlConnection对象

cmd=new SqlCommand(strSql,cn);

 

3、调用SqlConnection类的CreateCommand方法

cmd=cn.CreateCommand();

cmd.CommandText=strSql;

相关文章: