Skip to main content
 首页 » 编程设计

c#之在 ASP.NET C# 中使用未知数量的值查询 SQL 数据库

2024年02月06日12三少

好吧,我已经构建了一个 SQL Server 数据库,它可以通过 ASP.NET UI(我也开发过)访问和操作,以允许工作中的其他人轻松搜索数据库。该数据库保存了我们有网络设备运行的许多位置的数据。

有人要求我在 UI 中构建查询数据库中多个 IP 地址的功能 - 例如用户将输入文本框“192.168.1.0, 18.15.156.4”,单击输入并在 gridview 中显示结果。多个 IP 地址将用 , 分隔。

下面的代码基本上去除了空格字符,寻找 ,(以确定有多少 ips 需要查询),如果找到则将它们放入一个数组中。然后 for 循环将每个数组项放入其自己的 session 变量中,并从那里准备好查询它们:

protected void siteSearchButton_Click(object sender, EventArgs e) 
{ 
    //checks IP search textbox is empty 
    if (ipQueryTextBox.Text != null) 
    { 
        searchErrorLabel.Visible = false; 
        string addresses = ipQueryTextBox.Text; 
 
        //checks for any blank spaces in the addresses variable 
        if (addresses.Contains(" ")) 
        { 
            addresses = addresses.Replace(" ", ""); 
        } 
 
        //sceens for multiple search items by looking for a ',' 
        if (addresses.Contains(",")) 
        { 
            //declaring int variables to be used in each of the respective loops 
            int j = 0; 
 
            string[] IParray = addresses.Split(','); 
 
            //if i is equal to the length of the "addresses" variable, execute the for loop enclosed 
            foreach (string s in IParray) 
            { 
                Session["IP" + j] = IParray[j]; 
                j = j + 1; 
            } 
        } 
    } 
} 

由于要针对数据库查询的 ip 数量是动态的,我得出的结论是我将不得不使用 C# 代码(我可以接受),但就我目前所获得的而言下面,我不确定如何使用代码查询数据库“x”次数,大概我需要使用 while 循环,有人能提供一些见解吗?

//****THE SQL COMMAND BELOW NEEDS ADAPTING TO ALLOW MULTIPLE QUERIES FOR EACH OF THE VALUES STORED IN IParray ---> each session variable 
if() 
{ 
    //opens a new sqlconnection to read and populate edit textboxes from the Inventory database 
    using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=Inventory;Integrated Security=True")) 
    { 
        //declares SQLCommand type named 'command' and assigns it a string value of SQL code 
        SqlCommand command = 
            new SqlCommand("select * from LOCATION WHERE IP_ADDRESS=@IP_ADDRESS", connection); 
 
        //outlines parameters 
        command.Parameters.Add("@IP_ADDRESS", System.Data.SqlDbType.VarChar); 
        command.Parameters["@IP_ADDRESS"].Value = Session["IP"+j];; 
        connection.Open(); 
 
        //opens database connection 
        SqlDataReader read = command.ExecuteReader(); 
 
        //while loop will convert each record to string value and print entry into textbox. Will continue untill it runs out of lines 
        while (read.Read()) 
        { 
 
        } 
        read.Close(); 
    } 
} 

请您参考如下方法:

不使用多个查询,而是使用 SQL 的 IN 子句。不过,设置查询参数确实需要多做一些工作。

string[] ips = new string[] { "192.168.0.1", "192.168.0.2", "192.168.0.3" }; 
string[] parameters = ips.Select( 
    (ip, index) => "@ip" + index.ToString() 
).ToArray(); 
 
string commandFormat = "SELECT * FROM LOCATION WHERE IP_ADDRESS IN ({0})"; 
string parameterText = string.Join(",", parameters); 
string commandText = string.Format(commandFormat, parameterText); 
 
using (SqlCommand command = new SqlCommand(commandText)) { 
    for(int i = 0; i < parameters.Length; i++) { 
       command.Parameters.AddWithValue(parameters[i], ips[i]); 
    } 
} 

在上面的示例中,生成的命令将是 SELECT * FROM LOCATION WHERE IP_ADDRESS IN (@ip1,@ip2,@ip3),参数值将相应设置。

(上述解决方案深受 this answer 的启发。)