gpt4 book ai didi

c# - ExecuteNonQuery 导致参数映射错误

转载 作者:行者123 更新时间:2023-11-30 20:03:24 26 4
gpt4 key购买 nike

您好,我正在尝试使用 ADO.NET 将数据插入数据库。这是我的代码。这是我的 C# 代码:

 public void CreateBook(FormCollection collection)
{
string name = collection["BookName"];
string author = collection["Author"];
string description = collection["Description"];
int category = int.Parse(collection["category"]);
DateTime currentDate = new DateTime();

using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
SqlCommand command = new SqlCommand("AddBook", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(createParameter(name, "@Name"));
command.Parameters.Add(createParameter(author, "@Author"));
command.Parameters.Add(createParameter(description, "@Description"));
command.Parameters.Add(createParameter(currentDate.Date, "@Date"));
command.Parameters.Add(createParameter(category, "@CategoryId"));
command.ExecuteNonQuery();
}
}
//there are 2 other overloads of this method
private SqlParameter createParameter(string parameter , string parameterName) {
SqlParameter param = new SqlParameter();
param.ParameterName = parameterName;
param.Value = param;
return param;
}

这是我的 SQL 代码:

 CREATE PROCEDURE [dbo].[AddBook]
@Name nvarchar(MAX),
@Author nvarchar(MAX),
@Description nvarchar(MAX),
@Date date ,
@CategoryId int
AS
INSERT INTO Books (Name , Author , Description , PublicationDate , CategoryId)
VALUES (@Name , @Author , @Description , @Date , @CategoryId)

当 ExecuteNonQueryuery 被触发时,我得到这个错误:

No mapping exists from object type System.Data.SqlClient.SqlParameter to a known managed provider native type. 

我做错了什么?

最佳答案

我怀疑这条线是最直接的问题:

param.Value = param;

你的意思是:

param.Value = parameter;

否则你试图将参数设置为参数本身,这是没有意义的。

但是,我个人建议也指定类型等。您可以摆脱其他方法,只需使用这样的调用:

command.Parameters.Add("@Name", SqlDbType.NVarChar).Value = name;
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = currentDate.Date;
// etc

关于c# - ExecuteNonQuery 导致参数映射错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com