Stu*_*ens 56 c# sql-server ado.net
我试图通过ADO.net从DB获取输出值.有一个客户端代码:
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("pDoSomethingParamsRes", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@i", 1);
var outParam = new SqlParameter("@out", SqlDbType.VarChar);
outParam.Direction = ParameterDirection.Output;
command.Parameters.Add(outParam);
command.ExecuteNonQuery();
Console.WriteLine(command.Parameters["@out"].Value.ToString());
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到以下异常:
the Size property has an invalid size of 0
Run Code Online (Sandbox Code Playgroud)
根据手册SqlParameter.Size属性我可能会省略大小.为什么我会得到这个例外?如何在不通过尺寸的情况下使其工作?
谢谢您的帮助!
Sac*_*hag 59
VarChar和NVarChar是可变宽度字符字段(因此var + char).您必须设置长度,否则默认值为零.
The*_*ing 47
可变大小的输出参数需要参数大小.通常,ADO.NET根据分配给参数的值来决定参数的大小(因此它是可选的),但是在输出参数中因为没有设置值,所以需要提供参数所需的大小
将参数大小设置为DB中输出变量的大小...说50
outParam.Size = 50;
Run Code Online (Sandbox Code Playgroud)
And*_*ens 15
顺便提一下,即使输出参数不是字符串类型参数,也必须设置输出参数的size属性.例如,如果您使用的是System.Data.SqlDbType.Int,则应将大小设置为4.
检查MSDN:SqlParameter.Size属性
对于双向和输出参数以及返回值,必须设置Size的值.输入参数不需要这样做,如果没有显式设置,则在执行参数化语句时,从指定参数的实际大小推断出该值.
每个人的答案对我来说都像泥巴一样清晰。也许这会帮助某人,因为我找到了有效的方法。
需要给参数加上size
DynamicParameters Params = new DynamicParameters();
Params.Add("@ProfileID", ProfileID);
Params.Add("@CategoryName", CategoryName);
Params.Add("@Added", dbType: DbType.String, direction: ParameterDirection.Output,size:10);
db.Execute(sql, Params, commandType: CommandType.StoredProcedure, commandTimeout: 60);
var Added = Params.Get<string>("@Added");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58460 次 |
| 最近记录: |