gpt4 book ai didi

c# - 从 OleDbDataReader 读取 Access 数据库取回值

转载 作者:太空狗 更新时间:2023-10-29 23:55:00 28 4
gpt4 key购买 nike

在它下面是我用来连接到 Access 数据库并从查询中提取值的代码。问题是..我无法从读者对象中取回任何值。我可以看到行数正确,但是我不断收到 InvalidOperationException(无论我使用 GetValue() 还是 GetString())说“行/列不存在数据。”

        System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft Office 12.0 Access Database Engine OLE DB Provider;" +
@"Data source= C:\Users\nearod\Desktop\ImportDB.accdb";
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [SQL Agent Unique ID Test Load]", conn);

OleDbDataReader reader = cmd.ExecuteReader();

string companyCode = reader.GetValue(0).ToString();
string agentId = reader.GetString(1);
string firstName = reader.GetString(2);
string lastName = reader.GetString(3);
string nameSuffix = reader.GetString(4);
string corporateName = reader.GetString(5);
string entityType = reader.GetString(6);
string obfSSN = reader.GetString(7);
string obfFEIN = reader.GetString(8);
string dummyIndicator = reader.GetString(9);
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}

最佳答案

你必须像下面这样调用 Read 方法(使用 using 而不是自行处理连接

string connectionString = @"Provider=Microsoft Office 12.0 Access Database Engine OLE DB Provider;" + @"Data source= C:\Users\nearod\Desktop\ImportDB.accdb";

string queryString= "SELECT * FROM [SQL Agent Unique ID Test Load]";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();

while (reader.Read())
{
string companyCode = reader.GetValue(0).ToString();
string agentId = reader.GetString(1);
string firstName = reader.GetString(2);
string lastName = reader.GetString(3);
string nameSuffix = reader.GetString(4);
string corporateName = reader.GetString(5);
string entityType = reader.GetString(6);
string obfSSN = reader.GetString(7);
string obfFEIN = reader.GetString(8);
string dummyIndicator = reader.GetString(9);
// Insert code to process data.
}
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}

关于c# - 从 OleDbDataReader 读取 Access 数据库取回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12081111/

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