当前位置: 编程技术>.net/c#/asp.net
c#中使用SqlDataReader查询数据库
来源: 互联网 发布时间:2014-08-30
本文导语: c#中使用SqlDataReader查询数据库,有需要的朋友可参考下。 代码如下: using System; using System.Data; using System.Data.SqlClient; public class StudyReader { public static void Main() { //连接字符串 ...
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());
}
}
}
}
}
}
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来查询数据库中的信息。