Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

sql server ce - Isn't an Int64 equal to a long in C#?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

long is Int64 in .NET; it is just an alias in C#. Your problem is casting the return value to long 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 to long.

If it is the COUNT(*) which is coming back, then it is Int32. You need to use the Convert class:

long l = Convert.ToInt64(selectCommand.ExecuteScalar());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...