c# - 将参数传递到 SqlCommand 时出现问题

标签 c# sql sql-server tsql sqlcommand

我在将参数传递给 SqlCommand 的 SQL 字符串时遇到问题。当我使用选项 1(见下文)时,代码有效。当我使用选项 2 时,它不起作用。我不确定如何让 .AddWithValue 方法与 SqlCommand 一起工作。

如有任何帮助,我们将不胜感激!

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

最佳答案

尝试使用

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

关于c# - 将参数传递到 SqlCommand 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687912/

相关文章:

c# - "Data at the Root Level is invalid"与 LoadXml

mysql大查询优化

mysql - 谁能帮我修复 SQL 查询吗?

java - 我无法连接 SQL Server ClassNotFoundException

sql - 有什么理由不加入 Foreign Key 到 Foreign Key 吗?

php - Codeigniter 请求 sql 但我的代码返回错误

c# - 当 ListBox 被禁用/不活动时覆盖背景颜色

c# - 我如何从最后循环遍历列表?

c# - Lync NotInitializedException 在 Windows 8 上无法捕获

MySQL:按列对 2 个(或更多)表中的行进行排序