32

我一直在通过SqlCeConnection在 C# 中使用 SQL 和数据库。我一直在使用ExecuteReader来读取读入 Long 的记录 ID 的结果和BigInt值。

今天我一直在使用基于 COUNT 的语句('SELECT COUNT(*) FROM X')的 SQL 语句,并且一直在使用ExecuteScalar来读取这些单值结果。

但是,我遇到了一个问题。我似乎无法将值存储到我一直在使用的 Long 数据类型中。我可以将它们存储到 Int64 中。

我一直在使用 BigInt 作为记录 ID,以获得最大的潜在记录数。

因此,一个 BigInt 8 字节是一个 Int64。Long 是否不等于 Int64,因为两者都是 64 位有符号整数?

因此,为什么我不能将 Int64 转换为 Long?

long recordCount =0;

recordCount = (long)selectCommand.ExecuteScalar();

错误是:

指定的演员表无效。

我可以将 BigInt 读入 Long。这不成问题。我无法将 SQL COUNT 读入很长的内容。

COUNT 返回一个 Int (Int32),所以问题实际上是将 Int32 转换为 long。

4

2 回答 2

34

longInt64 .NET 中;它只是 C# 中的别名。您的问题是将返回值转换为long,除非我们确定从您的查询返回的类型,否则我们不会知道您为什么会收到错误。SQL BigInt 必须可转换为long.

如果返回的是 COUNT(*),那么它是 Int32。您需要使用Convert该类:

long l = Convert.ToInt64(selectCommand.ExecuteScalar());
于 2011-03-10T13:40:16.030 回答
5

如果你认为你的计数会溢出 int/Int32,你应该在你的 SQL中使用COUNT_BIG() - 它有正确的返回类型。


至于为什么演员表不起作用,我不确定。以下 C#:

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
long lCount = (long)cmd.ExecuteScalar();
Int64 iCount = (Int64)cmd.ExecuteScalar();

编译为此 IL:

L_0000: nop 
L_0001: newobj instance void [System.Data]System.Data.SqlClient.SqlCommand::.ctor()
L_0006: stloc.0 
L_0007: ldloc.0 
L_0008: callvirt instance object [System.Data]System.Data.Common.DbCommand::ExecuteScalar()
L_000d: unbox.any int64
L_0012: stloc.1 
L_0013: ldloc.0 
L_0014: callvirt instance object [System.Data]System.Data.Common.DbCommand::ExecuteScalar()
L_0019: unbox.any int64
L_001e: stloc.2 
L_001f: ret 

也就是说,它们似乎编译为相同的代码。

于 2011-03-10T14:08:42.897 回答