string strSQL = "Select * From Employees;Select * from Customers";执行两次查询

SqlCommand对象的字符串SQL命令可以做多个,
以查询为例,用到SqlDataReader的一些方法,如ExecuteReader(),Read()(一条命令内的移动至下一记录),NextResult()(移动到下一个命令并执行)。
  using System;
using System.Collections.Generic;
using System.Text; using System.Data;
using System.Data.SqlClient;
using System.Data.Common; namespace AutoLotDataReader
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Data Readers *****\n"); #region Connection string builder logic
// Create a connection string via the builder object.
// SqlConnectionStringBuilder,这样就不用写连接字符串了
SqlConnectionStringBuilder cnStrBuilder =
new SqlConnectionStringBuilder();
//cnStrBuilder.InitialCatalog = "AutoLot";
//cnStrBuilder.DataSource = @"(local)\SQLEXPRESS";
cnStrBuilder.InitialCatalog="Northwind";
cnStrBuilder.DataSource = @"NLH774";
cnStrBuilder.ConnectTimeout = ;
cnStrBuilder.IntegratedSecurity = true; SqlConnection cn = new SqlConnection();
cn.ConnectionString = cnStrBuilder.ConnectionString;
cn.Open();
ShowConnectionStatus(cn);
#endregion // Create a SQL command object w/ 2 select statements.
//执行两句SQL语句
//string strSQL = "Select * From Inventory;Select * from Customers";
string strSQL = "Select * From Employees;Select * from Customers";
SqlCommand myCommand = new SqlCommand(strSQL, cn); // Obtain a data reader a la ExecuteReader().
SqlDataReader myDataReader;
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection); #region Loop over each table.
do
{
//遍历一个查询中的记录
while (myDataReader.Read())
{
//遍历按行输出一个记录的信息,格式列名=列值
Console.WriteLine("***** Record *****");
for (int i = ; i < myDataReader.FieldCount; i++)
{
Console.WriteLine("{0} = {1}",
myDataReader.GetName(i),
myDataReader.GetValue(i).ToString().Trim());
}
Console.WriteLine();
} Console.WriteLine("**********************************");
} while (myDataReader.NextResult()); //执行下一个结果集查询(Select * from Customers)
#endregion // Because we specified CommandBehavior.CloseConnection, we
// don't need to explicitly call Close() on the connection.
myDataReader.Close();
Console.ReadLine();
} #region Helper method
static void ShowConnectionStatus(DbConnection cn)
{
// Show various stats about current connection object.
Console.WriteLine("***** Info about your connection *****");
Console.WriteLine("Database location: {0}", cn.DataSource);
Console.WriteLine("Database name: {0}", cn.Database);
Console.WriteLine("Timeout: {0}", cn.ConnectionTimeout);
Console.WriteLine("Connection state: {0}\n", cn.State.ToString());
}
#endregion
}
}

虽然可以这样,但我觉得从软件编码规范、清晰可读性上说,最好还是不要这么操作。

最好应该分开执行不同的命令,大不了多声明几个字符串命令而已。

上一篇:ZigBee学习四 无线+UART通信


下一篇:libevent源码深度剖析二