简体   繁体   中英

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. The method has sql query and it uses parameter, but it seems like the parameter is not passed to the query. (I debugged and saw it does not go into the while loop. My code is below:

    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. However, once I add a parameter, does not go inside while loop; it goes to 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"

if you tried the query in sql server management studio u will not get any result

since 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

You don't need to wrap the string value in quote. You can remove this line, since SqlParameter will handle that for you.

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:

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):

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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