c# - sql server 返回 long.parse 显示错误

标签 c# sql .net sql-server ado.net

我目前的问题是 SQL 服务器。我正在编写自己的查询,其中一个查询是针对表中的 INSERT 数据。这很容易做到。不容易的是我在测试期间收到的错误。我只是在每个步骤都设置了断点,并且一切正常,除了最终结果。

是long的问题吗?因为当我使用 bool 时,它工作得很好,但我需要使用 long。

现在让我们看看我的内部代码:

public long Create(TPerson person)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var insert = string.Format(@"INSERT INTO CisOsoba(Jmeno, Prijmeni, Email, TelKlapka, TelKlapka2, TelMob)
                                         VALUES(@jmeno, @prijmeni, @email, @telKlapka, @telKlapka2, @telMob)");

        connection.Open();
        SqlCommand cmd = new SqlCommand(insert, connection);

        cmd.Parameters.AddWithValue("@jmeno", person.FirstName);
        cmd.Parameters.AddWithValue("@prijmeni", person.LastName);
        cmd.Parameters.AddWithValue("@email", person.Email);
        cmd.Parameters.AddWithValue("@telKlapka", person.Phone1);
        cmd.Parameters.AddWithValue("@telKlapka2", person.Phone2);
        cmd.Parameters.AddWithValue("@telMob", person.PhoneMob);

        return long.Parse(cmd.ExecuteScalar().ToString());
    }
}

当我在行处设置断点时:return long.Parse(cmd.ExecuteScalar().ToString()); 然后我跳进去,出现错误:

"An unhandled exception of type 'System.NullReferenceException' occurred in Business.WeighingSystem.dll

Additional information: Object reference not set to an instance of an object."

我真的不知道,什么对象我不需要设置实例。

感谢您的每一个提示! :)

最佳答案

您似乎正在尝试返回受该命令影响的行数。在这种情况下,您需要使用 ExecuteNonQuery相反:

return long.Parse(cmd.ExecuteNonQuery());

基于 MSDN :

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

关于c# - sql server 返回 long.parse 显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303555/

相关文章:

c# - 我们可以排除 ADO.Net 实体数据模型中 ToList() 方法中的特定记录吗?

php - 拉维查询。独一无二的地方

mysql - 使用 JOIN 优化 MySQL 计数查询

c# - 我正在寻找 .NET 的实际功能 Web 浏览器控件,也许是 C++ 库

c# - 如何在 .NET Standard 中为通用枚举类型设置枚举标志?

c# - 从 native C++ 或 C 调用 C# 函数

c# - 使用 Dapper 将参数传递到 SQL 校验和函数

c# - 捕获异常而不做任何事情可以吗?

SQL 将多列拆分为多行

c# - 这段代码在 C# 中做了什么,它的目的是什么?