【发布时间】:2014-06-20 08:01:03
【问题描述】:
我遇到了这个异常:
参数化查询 '(@Name nvarchar(8),@type nvarchar(8),@units nvarchar(4000),@rang' 需要参数 '@units',但未提供。
我的插入代码是:
public int insertType(string name, string type, string units = "N\\A", string range = "N\\A", string scale = "N\\A", string description = "N\\A", Guid guid = new Guid())
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO Type(name, type, units, range, scale, description, guid) OUTPUT INSERTED.ID VALUES (@Name, @type, @units, @range, @scale, @description, @guid) ";
command.Connection = connection;
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@type", type);
command.Parameters.AddWithValue("@units", units);
command.Parameters.AddWithValue("@range", range);
command.Parameters.AddWithValue("@scale", scale);
command.Parameters.AddWithValue("@description", description);
command.Parameters.AddWithValue("@guid", guid);
return (int)command.ExecuteScalar();
}
}
这个异常令人惊讶,因为我使用了AddWithValue 函数并确保我为该函数添加了默认参数。
已解决:
问题在于某些参数为空字符串(覆盖默认值)
这是工作代码:
public int insertType(string name, string type, string units = "N\\A", string range = "N\\A", string scale = "N\\A", string description = "N\\A", Guid guid = new Guid())
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO Type(name, type, units, range, scale, description, guid) OUTPUT INSERTED.ID VALUES (@Name, @type, @units, @range, @scale, @description, @guid) ";
command.Connection = connection;
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@type", type);
if (String.IsNullOrEmpty(units))
{
command.Parameters.AddWithValue("@units", DBNull.Value);
}
else
command.Parameters.AddWithValue("@units", units);
if (String.IsNullOrEmpty(range))
{
command.Parameters.AddWithValue("@range", DBNull.Value);
}
else
command.Parameters.AddWithValue("@range", range);
if (String.IsNullOrEmpty(scale))
{
command.Parameters.AddWithValue("@scale", DBNull.Value);
}
else
command.Parameters.AddWithValue("@scale", scale);
if (String.IsNullOrEmpty(description))
{
command.Parameters.AddWithValue("@description", DBNull.Value);
}
else
command.Parameters.AddWithValue("@description", description);
command.Parameters.AddWithValue("@guid", guid);
return (int)command.ExecuteScalar();
}
}
【问题讨论】:
-
您忘记将
@作为每个参数名称的第一个字符。 -
@AndrewMorton:为什么错误信息是抱怨
@units而不是@Name,这是最先出现的? -
@O.R.Mapper 我想它不必按照提供的顺序查找它们。
-
我很震惊,因为仍然没有人回答这个问题。顺便说一句,
2点赞? -
@AndrewMorton 我添加了 @ 并且仍然是相同的异常
标签: c# sql-server exception