文档库 最新最全的文档下载
当前位置:文档库 › ex2-1

ex2-1

//数据库查询示例2-1:使用string对象建立简单的查询命令并返回查询结果
static void ex2_1()
{
Console.WriteLine("数据库查询示例2-1:使用string对象建立简单的查询命令并返回查询结果.");

//第1步:设置连接字符串,建立数据库连接
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "(local)";
scsb.InitialCatalog = "northwind";
scsb.IntegratedSecurity = true;
//https://www.wendangku.net/doc/eb3190702.html,erID = "stud";
//scsb.Password = "stud";
SqlConnection sc = new SqlConnection(scsb.ConnectionString);

sc.Open();
if (sc.State == System.Data.ConnectionState.Open)
{
Console.WriteLine("Database Connection is open.");
}


//第2步:定义数据库查询命令
SqlCommand cmd = new SqlCommand();//创建SqlCommand对象
cmd.Connection = sc; //设置SqlCommand所使用的连接对象

//设置SqlCommand的T-SQL语句和类型
string sqlText = "select productID, productName from products where productID = 2";
https://www.wendangku.net/doc/eb3190702.html,mandText = sqlText;
https://www.wendangku.net/doc/eb3190702.html,mandType = CommandType.Text;


//第3步:创建SqlDataReader对象,获取查询结果
SqlDataReader reader = cmd.ExecuteReader();

//若要创建 SqlDataReader,必须调用 SqlCommand 对象的 ExecuteReader 方法,而不要直接使用构造函数。
//SqlDataReader reader = new SqlDataReader();//这样声明SqlDataReader对象是错误的!!!
//reader = cmd.ExecuteReader();

Console.WriteLine("sql command text: " + https://www.wendangku.net/doc/eb3190702.html,mandText);

if (reader.HasRows)
{
Console.WriteLine("data has been retrived from database " + sc.Database + " from data source " + sc.DataSource);

}
else
{
Console.WriteLine("no record is retrived from database " + sc.Database + " from data source " + sc.DataSource);

}
Console.ReadKey();

}

相关文档