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

时间:2014-09-05 03:53:19

标签: c# sql asp.net sql-server

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

我被要求在UI中构建查询数据库以查找多个IP地址的功能 - 例如用户将进入文本框" 192.168.1.0,18.15.156.4",单击回车并在gridview中显示结果。多个IP地址将使用,分隔。

下面的代码基本上删除空格字符,查找,(确定要查询的ips数量),如果找到则将它们放入数组中。然后for循环将每个数组项放入它自己的会话变量中,然后就可以查询它们了:

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;
            }
        }
    }
}

由于要查询数据库的ips数量是动态的,我得出的结论是我将不得不使用C#代码(我可以使用它),但就我所做的而言。到目前为止,我还不确定如何查询db' 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();
    }
}

4 个答案:

答案 0 :(得分:2)

不要使用多个查询,只需使用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的启发。)

答案 1 :(得分:1)

第一件事 - 为什么在只需要存储值时创建多个会话对象?

我会尝试更改您的代码:

if (ipQueryTextBox.Text != null)
{
    searchErrorLabel.Visible = false;
    string addresses = ipQueryTextBox.Text;
    addresses = addresses.Replace(" ", "");
    addresses = addresses.Replace(",", "','");
    Session["addresses"] = addresses;
}

对于SQL部分,您现在可以轻松利用SQL IN运算符,例如:http://www.w3schools.com/sql/sql_in.asp

SqlCommand command = new SqlCommand("select * from LOCATION WHERE IP_ADDRESS IN (@IP_ADDRESSES)", connection);
command.Parameters.AddWithValue("IP_ADDRESSES", Session["addresses"]);

这应该可行,但我没有测试过,所以可能需要一些调整。希望你明白这一点。

答案 2 :(得分:1)

为什么你需要参数。

//从UI获取IP地址;

string IPAddress = ipQueryTextBox.Text; //e.g. "192.168.0.1,192.168.0.2,192.168.0.3"

string commandFormat = "SELECT * FROM LOCATION WHERE IP_ADDRESS IN ('" + string.Join("','", IPAddress.split(",")) + "')";

现在执行查询

答案 3 :(得分:0)

感谢所有回复的人,以下是我从上面的答案中得出的解决方案:

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(","))
        {
            string[] IParray = addresses.Split(',');

            string[] Parameters= IParray.Select((IP, index)=>"@ip"+ index.ToString()).ToArray();
            string commandformat ="SELECT * FROM LOCATION WHERE IP_ADDRESS IN ({0})";
            string parametertxt= string.Join(",",Parameters);
            string commandtxt= string.Format(commandformat,parametertxt);

            //creates an SQL connection "connection" opens the connection creates the sql command to be executed & binds and refreshes the gridview
            using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=Inventory;Integrated Security=True"))
            {
                SqlDataReader reader = null;

                connection.Open();
                SqlCommand command = new SqlCommand(commandtxt, connection);                

                for(int i =0; i<Parameters.Length; i++)
                {
                    command.Parameters.AddWithValue(Parameters[i],IParray[i]);                        
                }

                reader = command.ExecuteReader();

                browseSiteGridView.DataSource = reader;
                browseSiteGridView.DataBind();
                reader.Close();
                connection.Close();

            }
        }
        else
        {
            //creates an SQL connection "connection" opens the connection creates the sql command to be executed & binds and refreshes the gridview
            string commandtxt="SELECT * FROM LOCATION WHERE IP_ADDRESS ='"+addresses+"'";

            using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=Inventory;Integrated Security=True"))
            {
                SqlDataReader reader = null;

                connection.Open();
                SqlCommand command = new SqlCommand(commandtxt, connection);

                reader = command.ExecuteReader();

                browseSiteGridView.DataSource = reader;
                browseSiteGridView.DataBind();

                reader.Close();
                connection.Close();

            }

        }
    }