gpt4 book ai didi

c# - 从 MS Access 数据库中获取 Long 后使用 OleDbDataReader.GetInt64() 时获取 System.InvalidCastException

转载 作者:行者123 更新时间:2023-11-30 21:59:27 27 4
gpt4 key购买 nike

我一直在处理一个项目(使用 Visual Studio 2013),我需要从本地存储的 MS Access 2007 数据库中检索信息。我现在正在使用 OleDb 来处理连接。数据库有一个表,有几个字段。我正在尝试从 SID 检索值 - 这是主键,从 Access 中设置为自动编号作为长整数。

这是我的问题:当 OleDbDataReader 完成执行并且我尝试检索结果(使用 GetInt64 方法)时,我收到此错误:

An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll

Additional information: Specified cast is not valid.

无论我是否将结果分配给一个值,都会发生这种情况。更改对 GetInt32 的调用使其工作,但我不知道为什么!

谁能阐明为什么会这样?

我在这里和其他地方进行了广泛的搜索,大多数情况下他们建议在 Access 中字段类型未设置为长整型,但我的已经设置了,所以我认为这不是问题所在。其他解决方案似乎都不适用或有效。

我已经从我的主应用程序中提取了问题代码,并剥离了所有非必要代码,但仍然出现错误,这是简单版本:

        // Set up connection and test query
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Combobulator\\Desktop\\Testing Databases\\Reagents Database\\Reagents.mdb");
string query = "SELECT SID FROM MolTable WHERE [Chemical Name] = 'Acetyl Chloride'";

OleDbCommand command = new OleDbCommand(query, connection);

try {
connection.Open();
OleDbDataReader reader = command.ExecuteReader();

if (!reader.HasRows) {
System.Console.WriteLine("Returned no rows.");
Environment.Exit(-1);
}

// Find all matching entries
while (reader.Read()) {
reader.GetInt64(0); // This is where the error is thrown
}

// Close the reader and connection
reader.Close();
} catch (OleDbException e) {
System.Console.WriteLine("Error: " + e.Errors[0].Message);
} finally {
connection.Close();
}

我完全被难住了,这是我第一次不得不在线寻求帮助。

感谢您花时间阅读!

编辑:我忘了说,这不只是我混淆了 Access 中 Long Integer 的长度,是吗?我假设它是 64 位的,如果我错了请纠正我。

最佳答案

I forgot to mention, this isn't just me confusing the length of Long Integer in Access is it? I assume that it's 64-bit, please correct me if I'm wrong.

是的,我认为正是问题所在。例如,来自 "Field types in MS Access" :

Integers in Access come in 1, 2 and 4 byte varieties. The single byte number is named Byte (Range 0-255), the two-byte number is named Integer (-32768 to 32767) and then there is the Long Integer (-2 billion to 2 billion).

(This site 同意。)

MS 文档在地面上很薄,但 HansUp 找到了这个 "Introduction to data types and field properties"其中包括:

Field Size

  • ...
  • Long Integer — Use for integers that range from -2,147,483,648 to 2,147,483,647. Storage requirement is 4 bytes.

关于c# - 从 MS Access 数据库中获取 Long 后使用 OleDbDataReader.GetInt64() 时获取 System.InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265006/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com