【问题标题】:C# ExecuteScalar() returns null but the data is inserted in the SQL tableC# ExecuteScalar() 返回 null 但数据插入到 SQL 表中
【发布时间】:2021-03-28 21:05:50
【问题描述】:

我正在使用 SQL Server。

每次数据成功插入数据库但总是返回一个空值。在 SQL Server 中,我只创建了仅在第一列('Id')上自动递增的表。我的桌子是这样的:

Column_Name Type
Id int
DateTime datetime
ClientName nvarchar
ClientNumber nvarchar
TotalPrice float

我的代码如下所示:

try
{ 
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = _conn;
    cmd.CommandText = "INSERT INTO appointmentTable(DateTime,ClientName,ClientNumber,TotalPrice) VALUES( @datee, @clientName ,@clientNumber, @totalPrice);";
    cmd.Parameters.AddWithValue("@datee", newAppointment.GetDateTime().ToString("yyyy-MM-dd HH:mm:ss"));
    cmd.Parameters.AddWithValue("@clientName", newAppointment.GetClientName());
    cmd.Parameters.AddWithValue("@clientNumber", newAppointment.GetClientNumber());
    cmd.Parameters.AddWithValue("@totalPrice", newAppointment.GetTotalPrice());
    _conn.Open();
    int idAdded = Convert.ToInt32(cmd.ExecuteScalar());
    newAppointment.SetId(idAdded);
    AppointmentServiceRepository.getInstance().AddServicesToAppointment(newAppointment);
    _conn.Close();
    return true;
}
catch (SqlException e)
{
    Console.WriteLine(e.Message);
    return false;
}

【问题讨论】:

  • 另外强烈推荐not use AddWithValue。当然不要将您的日期转换为字符串来插入它,将其作为本机日期时间插入。
  • 如果您查看documentation,您会发现需要选择新的 ID 才能返回。
  • 这可能是因为您使用的是 AddWithValue - 使用常规 add 方法并正确设置数据类型。
  • 在上面链接的文档中有一个确切的例子,显示了如何做你想做的事情 - 请阅读它。
  • 单独说明,TotalPrice 是一个糟糕的数据类型选择。通过使用float,您表示您对舍入错误感到满意,这在处理金钱时是一件非常非常糟糕的事情。

标签: c# .net sql-server


【解决方案1】:

需要返回SQL函数SCOPE_IDENTITY(),如下

cmd.CommandText = "INSERT INTO 
appointmentTable(DateTime,ClientName,ClientNumber,TotalPrice) VALUES( @datee, @clientName 
,@clientNumber, @totalPrice); SELECT SCOPE_IDENTITY();";

【讨论】:

    【解决方案2】:

    你可以试试OUTPUT子句返回新插入的id。Read more on OUTPUT clause

    cmd.CommandText = "INSERT INTO 
    appointmentTable(DateTime,ClientName,ClientNumber,TotalPrice) 
    OUTPUT inserted.ID 
    VALUES( @datee, @clientName,@clientNumber, @totalPrice); "
    

    【讨论】:

      猜你喜欢
      • 2012-04-29
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多