use*_*138 8 c# sql stored-procedures
如何传递像SQL命令参数这样的整数值?
我这样想:
cmd.CommandText = ("insert_questions '" +
cmd.Parameters.AddWithValue(store_result,store_result) + "','" +
cmd.Parameters.AddWithValue(store_title, store_title) + "', '" +
cmd.Parameters.AddWithValue(store_des, store_des) + "'");
Run Code Online (Sandbox Code Playgroud)
store_result是int,其他2个参数是字符串类型.
store_result正在给出如下错误消息.
参数1:无法从'int'转换为'string'
在SP中,还有另一个int类型变量,它将获得store_result的值.
传递int参数的正确语法是什么?
谢谢.
aio*_*sov 16
正确的方法是
using(var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using(var command = new SqlCommand("SELECT * FROM Table WHERE ID=@someID",connection))
{
command.Parameters.AddWithValue("someID",1234);
var r = command.ExecuteQuery();
}
}
Run Code Online (Sandbox Code Playgroud)
这意味着它甚至可以用于文本查询.使用存储过程更容易 - 而不是sql查询,您只需提供存储过程名称:
using(var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using(var command = new SqlCommand("insert_sproc",connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("someID",1234);
var r = command.ExecuteQuery();
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
cmd.CommandText = ("insert_questions @store_result, @store_title, @store_des");
cmd.Parameters.AddWithValue("@store_result", store_result);
cmd.Parameters.AddWithValue("@store_title", store_title);
cmd.Parameters.AddWithValue("@store_des", store_des);
Run Code Online (Sandbox Code Playgroud)
它应该是这样的,
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = ("insert_questions") ;
cmd.Parameters.AddWithValue("@value", valueHere);
cmd.Parameters.AddWithValue("@value2", valueHere);
Run Code Online (Sandbox Code Playgroud)
请注意,@value并且@value2是存储过程中声明的参数.