如何在ASP.NET C#中执行多个数据库请求?

时间:2009-03-04 22:46:17

标签: asp.net sql

在我编写的每个ASP.NET应用程序中,在将信息输出到网页之前,我会向数据库发出一些请求。

例如:

var DataTable1 = GetDataTable("Select * From Customers");
var DataTable2 = GetDataTable("Select * From Products");
var DataTable3 = GetDataTable("Select * From Orders");

据我所知,上面的代码将分别进行3次数据库访问,并将逐个进行。

无论如何,我可以将我的参数化SQL语句聚集在一起,并且只有1次访问数据库服务器吗?

4 个答案:

答案 0 :(得分:6)

var SqlString = "SELECT * FROM Customers; SELECT * FROM Products; SELECT * FROM ORDERS;");
var ds = GetDataSet(SqlString);
var DataTable1 = ds.Tables(0);
var DataTable2 = ds.Tables(1);
var DataTable3 = ds.Tables(2);

答案 1 :(得分:1)

我的解决方案:

SqlConnection con = new SqlConnection("Server=CLASS-III-WKS10\\SQLEXPRESS;Initial 
Catalog=wind;Integrated Security=True");
int[] id=new int[9];
int i = 0;
page_load()
{
    con.Open();
    SqlCommand cmd = new SqlCommand("select *from windmill", con);
    SqlDataReader rd = cmd.ExecuteReader();
    while (rd.Read())
    {
        id[i] = rd.GetInt32(9);
        i++;
        //MessageBox.Show(id.ToString());  
    }
    rd.close();
    SqlCommand cmd1 = new SqlCommand("Update windmill set State='Stopped',PmState='Not Available'where Id=0", con);
    cmd1.ExecuteNonQuery(); 
}

答案 2 :(得分:0)

使用分号分隔SQL语句和reader.NextResult来获取每个集合。您的代码最终会看起来像这样。

    Using con As New SqlConnection
        Using cmd As New SqlCommand("Select * From Customers; Select * From Products; Select * From Orders")
            Using reader = cmd.ExecuteReader
                Dim dt1 As DataTable
                dt1.Load(reader)

                reader.NextResult()

                Dim dt2 As DataTable
                dt2.Load(reader)

                reader.NextResult()


                Dim dt3 As DataTable
                dt3.Load(reader)

            End Using
        End Using
    End Using

答案 3 :(得分:-1)

创建一个Thread类并在该类中放置一个接受字符串查询作为输入的方法: 然后创建一个Thread对象并启动该对象。

查看http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx