private static string connString = "Server = localhost\\SQLEXPRESS2014;DataBase = StudentManageDB;Uid = sa;Pwd = sa";
/// <summary>
/// 返回一个结果集
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static SqlDataReader GetReader(string sql)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand command = new SqlCommand(sql, conn);
try
{
conn.Open();
return command.ExecuteReader(CommandBehavior.CloseConnection);
//CommandBehavior.CloseConnection 该参数能够保证从外部关闭DataReader时,与之关联的Connection对象将随之关闭
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
//conn.Close();不能用此种方法关闭,关闭之后Read方法将不能使用
}
static void Main(string[] args)
{
string sql = "select * from Students;select * from studentClass";
SqlDataReader reader = SQLHelper.GetReader(sql);
while (reader.Read())
{
Console.WriteLine(reader["StudentId"] + "\t" + reader["StudentName"]);
}
if (reader.NextResult())
{
while (reader.Read())
{
Console.WriteLine(reader["ClassId"] + "\t" + reader["ClassName"]);
}
}
reader.Close();//会同时关闭conn
}