nvarchar'."尝试使用存储过程向表中插入行
本文关键字:插入 存储过程 quot nvarchar | 更新日期: 2023-09-27 18:03:59
我已经被这个错误困了一个小时了,我现在迫切需要别人的帮助。我不知道如何找到错误,所以我只展示我在这里编写的代码。
存储过程:
CREATE PROCEDURE AddProduct @id nvarchar(100), @name nvarchar(100), @price money,
@type int
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
INSERT INTO Product (product_id, product_name, product_price, [type_id])
VALUES(@id, @name, @price, @type);
COMMIT;
END TRY
BEGIN CATCH
ROLLBACK;
END CATCH
END;
GO
这里是c# Function
public void Add()
{
string command = "EXEC AddProduct @id nvarchar(100), @name nvarchar(100), @price money, @type int";
var query = Connection.InitSqlCommand(command);
query.Parameters.AddWithValue("@id", Id);
query.Parameters.AddWithValue("@name", Name);
query.Parameters.AddWithValue("@price", Price);
query.Parameters.AddWithValue("@type", Type);
Connection.ExecuteQuery(query);
}
编辑:这是另一个类
中的内容public void ExecuteQuery(SqlCommand command)
{
con.Open();
try
{
command.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
public SqlCommand InitSqlCommand(string query)
{
var Sqlcommand = new SqlCommand(query, con);
return Sqlcommand;
}
这是我的整个DatabaseConnection现在的样子:
public SqlCommand InitSqlCommand(string query, CommandType commandType)
{
var Sqlcommand = new SqlCommand(query, con);
Sqlcommand.CommandType = commandType;
return Sqlcommand;
}
public DataTable GetData(SqlCommand command)
{
var dataTable = new DataTable();
var dataSet = new DataSet();
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataTable);
return dataTable;
}
public void ExecuteQuery(SqlCommand command)
{
con.Open();
try
{
command.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
public bool ReadSqlCommand(SqlCommand command)
{
con.Open();
var activateCommand = command.ExecuteReader();
if (activateCommand.Read())
{
con.Close();
return true;
}
else
{
con.Close();
return false;
}
}
public bool ReadStringQuery(string command)
{
con.Open();
var activateCommand = InitSqlCommand(command, CommandType.StoredProcedure).ExecuteReader();
if (activateCommand.Read())
{
con.Close();
return true;
}
else
{
con.Close();
return false;
}
}
当你调用存储过程时,你不需要用参数指定数据类型,实际上甚至不需要用exec
命令添加参数,因为你在Parameters
集合中添加参数,这就是你做错的地方,把它改成:
string command = "AddProduct";
并指定SqlCommand
对象的CommandType
,最好将其作为参数并给调用者指定CommandType
的选项:
public SqlCommand InitSqlCommand(string query,CommandType commandType)
{
var Sqlcommand = new SqlCommand(query, con);
Sqlcommand.CommandType = commandType;
return Sqlcommand;
}
并命名为:
string command = "AddProduct";
var query = Connection.InitSqlCommand(command,CommandType.StoredProcedure);