Problems passing parameters to SqlCommand

I'm having trouble passing parameters to an SQL string for SqlCommand. When I use option 1 (see below), the code works. When I use option 2, it does not work. I am not sure how to get a method .AddWithValueto work with SqlCommand.

Any help would be appreciated!

private string [] GetOrderInfo (string folder)
{
    string [] order = new string [] { "date", "order#", "storeid", "storename", "username" };

    using (SqlConnection conn = new SqlConnection (_connectionString))
    {
        conn.Open ();

        // Option 1: this line works.
        //string sql = "select * from OrderProduct where OrderProductID=26846";

        // Option 2: this line doesn't work.
        string sql = "select * from OrderProduct where OrderProductID=@folder;";

        using (SqlCommand command = new SqlCommand (sql, conn))
        {
            command.Parameters.AddWithValue ("@folder", folder);

            using (SqlDataReader reader = command.ExecuteReader ())
            {
                while (reader.Read ())
                    order [1] = Convert.ToString (reader.GetInt32 (1));
            }
        }

        conn.Close ();
    } // using (SqlConnection conn = new SqlConnection (connectionString))

    return order;
}
+4
source share
3 answers

Try using

 Command.Parameters.Add("@folder",SqlDbType.Varchar).Value = folder; 
+3
source

AddWithValue SqlDbType. , OrderProductID INT, int.

:

command.Parameters.AddWithValue ("@folder", 26846);

- Simple Object Mapper, SqlDatabaseCommand Dapper.

using (var cmd = new SqlDatabaseCommand(_connection))
{
    cmd.CommandText.AppendLine(" SELECT * ")
                   .AppendLine("   FROM EMP ")
                   .AppendLine("  WHERE EMPNO = @EmpNo ")
                   .AppendLine("    AND HIREDATE = @HireDate ");

    cmd.Parameters.AddValues(new
            {
                EmpNo = 7369,
                HireDate = new DateTime(1980, 12, 17)
            });

    var emps = cmd.ExecuteTable<Employee>();
}
+1

You can try:

using (SqlCommand command = new SqlCommand("select * from OrderProduct where OrderProductID=@folder", conn))
{
    command.Parameters.Add(new SqlParameter("@folder", folder));

    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
            order[1] = Convert.ToString(reader.GetInt32(1));
    }
}
0
source

Source: https://habr.com/ru/post/1661255/


All Articles