我一直在通过 SqlCeConnection。我一直在使用 ExecuteReader 读取记录 ID 的结果和 BigInt 值被读入长整型。
今天,我一直在使用基于 COUNT 的语句('SELECT COUNT(*) FROM X')的 SQL 语句,并且一直在使用 ExecuteScalar 读取这些单值结果。
但是,我遇到了一个问题。我似乎无法将这些值存储到我到目前为止一直在使用的 Long 数据类型中。我可以将它们存储到 Int64 中。
我一直使用 BigInt 作为记录 ID 来获取最大潜在记录数。
因此,8 个字节的 BigInt 是一个 Int64。 Long 不等于 Int64 因为两者都是 64 位有符号整数吗?
因此,为什么我不能将 Int64 转换为 Long ?
long recordCount =0;
recordCount = (long)selectCommand.ExecuteScalar();
错误是:
指定的演员阵容无效。
我可以将 BigInt 读入 Long。这不是问题。
我无法将 SQL COUNT 读取为 long。
COUNT 返回一个 Int (Int32),因此问题实际上是将 Int32 转换为 long。
I have been playing around with SQL and databases in C# via SqlCeConnection. I have been using ExecuteReader to read results and BigInt values for record IDs which are read into Longs.
Today I have been playing with SQL statements that use COUNT based statements ('SELECT COUNT(*) FROM X') and have been using ExecuteScalar to read these single valued results.
However, I ran into an issue. I can't seem to store the values into a Long data type, which I have been using up to now. I can store them into Int64's.
I have been using BigInt for record IDs to get the maximum potential number of records.
A BigInt 8 bytes therefore is an Int64. Isn't a Long equal to an Int64 as both are 64-bit signed integers?
Therefore, why can't I cast an Int64 into a Long?
long recordCount =0;
recordCount = (long)selectCommand.ExecuteScalar();
The error is:
Specified cast is not valid.
I can read a BigInt into a Long. It is not a problem.
I can't read an SQL COUNT into a long.
COUNT returns an Int (Int32), so the problem is in fact casting an Int32 into a long.
发布评论
评论(2)
long
是Int64
在 .NET 中;它只是 C# 中的别名。您的问题是将返回值转换为long
,除非我们确定从您的查询返回的类型,否则我们不会知道您为什么会收到错误。 SQL BigInt 必须可转换为long
。如果返回的是 COUNT(*),则它是 Int32。您需要使用
转换
类:long
isInt64
in .NET; it is just an alias in C#. Your problem is casting the return value tolong
and unless we know the type coming back from your query for sure, we would not know why you get an error. SQL BigInt must be convertable tolong
.If it is the COUNT(*) which is coming back, then it is Int32. You need to use the
Convert
class:如果您认为计数将溢出 int/Int32,则应该使用 COUNT_BIG() - 它具有正确的返回类型。
至于为什么演员不起作用,我不确定。以下 C#:
编译为该 IL:
也就是说,它们似乎编译为相同的代码。
If you're thinking that your counts are going to overflow an int/Int32, you ought to use COUNT_BIG() in your SQL instead - it has the correct return type.
As to why the casts aren't working, I'm not sure. The following C#:
Compiles to this IL:
That is, they appear to compile to identical code.