简体   繁体   English

C#如何将用户输入传递给where子句中的参数

[英]C# how to pass user input to a parameter in where clause

I want to pass an user input to a where clause in a method.我想将用户输入传递给方法中的 where 子句。 The method has sql query and it uses parameter, but it seems like the parameter is not passed to the query.该方法具有 sql 查询并使用参数,但似乎参数未传递给查询。 (I debugged and saw it does not go into the while loop. My code is below: (我调试并看到它没有进入while循环。我的代码如下:

    Console.WriteLine("Enter your name: ");
    string name = Console.ReadLine();
    string prm = "\"" + name + "\"";  // Doublequote a string

      //execute method
      CheckCustomer(prm);



    private static string CheckCustomer(string cusName)
    {
        string cust = "null";

        try
        {
            Console.WriteLine("\nChecking custoemr...\n");
            // Sql Select Query
            string sql = "SELECT * FROM Customer WHERE CustomerName = @CusName";
            SqlCommand cmd = new SqlCommand(sql, sqlConnection);
            cmd.Parameters.AddWithValue("@CusName", cusName);
            SqlDataReader dr;
            dr = cmd.ExecuteReader();

            string strCusname = "Customer Name Found";
            Console.WriteLine("{0}", strCusname.PadRight(25));
            Console.WriteLine("==============================");

            while (dr.Read())
            {
                ////reading from the datareader

               cust = dr["CustomerName"].ToString();

            }
            dr.Close();
            return cust;

        }
        catch (SqlException ex)
        {
            // Display error
            Console.WriteLine("Error: " + ex.ToString());
            return null;
        }
    }

When I execute CheckCustomer() without the where clause, it works perfect.当我在没有 where 子句的情况下执行CheckCustomer() ,它工作得很好。 However, once I add a parameter, does not go inside while loop;但是,一旦我添加了一个参数,就不会进入while循环; it goes to dr.Close();它转到dr.Close(); directly.直接地。

What is wrong with this code?这段代码有什么问题?

To check for nulls in SQL server you use "is null" instead of "where field = null"要检查 SQL 服务器中的空值,请使用“is null”而不是“where field = null”

if you tried the query in sql server management studio u will not get any result如果您在 sql server management studio 中尝试查询,您将不会得到任何结果

since string cust = "null";因为string cust = "null"; that means ur code checks for customerName = null, but as i stated that this is not the right way to check for null and this query will not return any result, and since there is no result that means dr.Read() will evaluate to false and the while loop won't be executed这意味着您的代码会检查 customerName = null,但正如我所说,这不是检查 null 的正确方法,并且此查询不会返回任何结果,并且由于没有结果,这意味着dr.Read()将评估为false 并且不会执行 while 循环

You don't need to wrap the string value in quote.您不需要将字符串值括在引号中。 You can remove this line, since SqlParameter will handle that for you.您可以删除此行,因为 SqlParameter 会为您处理。

string prm = "\\"" + name + "\\""; // Doublequote a string

Also, if you want your query to support optional null values (ie where NULL implies that you DO NOT want to filter on customer name then you can simpy do:此外,如果您希望您的查询支持可选的空值(即,NULL 表示您不想过滤客户名称,那么您可以简单地执行以下操作:

SELECT * FROM Customer WHERE CustomerName = ISNULL(@CusName, CustomerName)

In your parameter section you can do something like:在您的参数部分,您可以执行以下操作:

cmd.Parameters.AddWithValue("@CusName", string.IsNullOrWhiteSpace(cusName) ? DbNull.Value: cusName);

If you don't want to allow nulls then you can leave the SQL query as-is as a throw a new ArgumentNullException at the top of your query method (ie add a guard clause):如果您不想允许空值,那么您可以将 SQL 查询保持原样,在查询方法的顶部抛出一个新的 ArgumentNullException(即添加一个保护子句):

if (string.IsNullOrWhiteSpace(CustomerName)) throw new ArgumentNullException(nameof(CustomerName));

Your query appears to be searching for the first customer with matching name.您的查询似乎正在搜索具有匹配名称的第一个客户。 In that case you should probably add a "TOP 1" to avoid needless overhead:在这种情况下,您可能应该添加“TOP 1”以避免不必要的开销:

SELECT TOP 1 * FROM Customer WHERE CustomerName = ISNULL(@CusName, CustomerName)

Console.WriteLine("Enter your name: ");
    string name = Console.ReadLine();
    string prm = "\"" + name + "\"";  // Doublequote a string

      //execute method
      CheckCustomer(prm);



    private static string CheckCustomer(string cusName)
    {
        string cust = "null";

        try
        {
            Console.WriteLine("\nChecking custoemr...\n");
            // Sql Select Query
            string sql = "SELECT * FROM Customer WHERE CustomerName = @CusName";
            SqlCommand cmd = new SqlCommand(sql, sqlConnection);
            cmd.Parameters.AddWithValue("@CusName", cusName);
            SqlDataReader dr;
            dr = cmd.ExecuteReader();

            string strCusname = "Customer Name Found";
            Console.WriteLine("{0}", strCusname.PadRight(25));
            Console.WriteLine("==============================");

            while (dr.Read())
            {
                ////reading from the datareader

               cust = dr["CustomerName"].ToString();

            }
            dr.Close();
            return cust;

        }
        catch (SqlException ex)
        {
            // Display error
            Console.WriteLine("Error: " + ex.ToString());
            return null;
        }
    }

try this.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM