将参数传递给SqlCommand的问题
问题描述:
我在将参数传递给SqlCommand
的SQL字符串时遇到问题。当我使用选项1(见下文)时,代码起作用。当我使用选项2时,它不起作用。我不知道如何让.AddWithValue
方法与SqlCommand
一起使用。将参数传递给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 [email protected];";
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;
答
你可以尝试使用:
using (SqlCommand command = new SqlCommand("select * from OrderProduct where [email protected]", conn))
{
command.Parameters.Add(new SqlParameter("@folder", folder));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
order[1] = Convert.ToString(reader.GetInt32(1));
}
}
+0
你从哪里看到它被弃用?这里没有提及:https://msdn.microsoft.com/en-us/library/0881fz2y(v=vs.110).aspx – Yanga
答
AddWithValue方法使用的值的类型定义正确SqlDbType。因此,如果您的字段OrderProductID是INT的类型,则需要添加int。
样品:
command.Parameters.AddWithValue ("@folder", 26846);
另一个简单的方法是使用简单对象映射像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”你要指定的东西,实际上看起来像一个产品ID:26846.在“选项2”,你分配一个名为'folder'字符串。这似乎没有道理...... –
“它不起作用”的意思是准确的。 – JBrooks
该文件夹和OrderProductID是相同的东西。 OrderProductID是数据库表中的字段名称,也是为订单创建的文件夹的名称。我没有这样设置它,它是由构建该应用程序的公司完成的。 – UltraJ