c#中使用SqlDataReader查询数据库,有需要的朋友可参考下。
复制代码 代码如下:
using System;
using System.Data;
using System.Data.SqlClient;
public class StudyReader
{
public static void Main()
{
//连接字符串
string strcon = "server = .;database = blog;uid = sa;pwd = 1";
SqlConnection con = new SqlConnection (strcon);
SqlCommand cmd = new SqlCommand();
using (con)
{
using (cmd)
{
cmd.Connection = con;
//表employee中有name(varchar(20)),age(int),sex(bit)
cmd.CommandText = "select * from employee where age = @age";
cmd.Parameters.Add("@age",SqlDbType.Int);
cmd.Parameters["@age"].Value = 40;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
using (reader)
{
while (reader.Read())
{
Console.WriteLine(reader["name"].ToString());
}
}
}
}
}
}
注:连接数据库后,可以用SqlDataReader来查询数据库中的信息。