【发布时间】:2019-02-13 07:52:01
【问题描述】:
我使用参数化查询将数据保存到 sql server。执行时会抛出以下错误。
参数化查询 '(@CustomerID int,@SerialNo nvarchar(2),@ModelNo nvarchar(2),@Sal' 需要参数 '@CreatedBy',但未提供。
这是我的代码。
public static bool SaveSales(int custid, string model, string serial, DateTime salesdate, decimal price, string mainservice, string comments, DateTime createddate, string createdby, DateTime modifieddate, string modifiedby)
{
bool saved = false;
try
{
using (SqlConnection conn = new SqlConnection(DBManager.DBConnection))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "INSERT INTO tbl_Sales VALUES(@CustomerID, @SerialNo, @ModelNo, @SalesDate, @Price, @MaintanenceService, @Comments, @CreatedDate, @CreatedBy, @ModifiedDate, @ModifiedBy)";
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@CustomerID", custid);
command.Parameters.AddWithValue("@SerialNo", serial);
command.Parameters.AddWithValue("@ModelNo", model);
command.Parameters.AddWithValue("@SalesDate", salesdate);
command.Parameters.AddWithValue("@Price", price);
command.Parameters.AddWithValue("@MaintanenceService", mainservice);
command.Parameters.AddWithValue("@Comments", comments);
command.Parameters.AddWithValue("@CreatedDate", createddate);
command.Parameters.AddWithValue("@CreatedBy", createdby);
command.Parameters.AddWithValue("@ModifiedDate", modifieddate);
command.Parameters.AddWithValue("@ModifiedBy", modifiedby);
command.ExecuteNonQuery();
}
conn.Close();
}
saved = true;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return saved;
}
return saved;
}
我的查询有什么问题?我使用参数化查询是为了正确保存销售日期。任何帮助将不胜感激。
【问题讨论】:
-
听起来您在 INSERT 查询中没有提及列名(例如
INSERT INTO tbl_Sales (Column1, Column2, ...) VALUES (@Param1, @Param2, ...))。 -
请确保 createdBy 不为空。按以下方式更改您的代码 createdby == null ? "" : 创建者
-
你能检查一下这是否能解决你的问题吗? stackoverflow.com/questions/3865982/…
-
请提供您的表结构
-
@TetsuyaYamamoto 该查询没问题,如果要插入所有列,则不需要指定列名,但是 OP 应确保值的顺序与表中的列。
标签: c# sql .net sql-server