using System; using System.Data; using System.Data.SqlClient; namespace Chapter12 { class MultipleResults { static void Main(string[] args) { // connection string string connString = @" server = .; integrated security = true; database = northwind "; // query 1 string sql1 = @" select companyname, contactname from customers where companyname like 'A%' "; // query 2 string sql2 = @" select firstname, lastname from employees "; // combine queries string sql = sql1 + sql2; SqlDataReader rdr = null; SqlConnection conn = null; try { // create connection conn = new SqlConnection(connString); // open connection conn.Open(); // create command SqlCommand cmd = new SqlCommand(sql, conn); // 执行两个sql分句后返回两个数据集 rdr = cmd.ExecuteReader(); // loop through result sets do{ while (rdr.Read()) { // Print one row at a time Console.WriteLine("{0} : {1}", rdr[0], rdr[1]); } Console.WriteLine("".PadLeft(60, '=')); } while (rdr.NextResult()); //SqlDataReader.NextResult()函数前进至下一个数据集。 } catch (Exception e) { Console.WriteLine("Error Occurred: " + e); } finally { // close data reader rdr.Close(); // Close connection conn.Close(); } } } } //所有代码来自书籍《Begining C# Databases From Novice to Professional》