我的 MS Access 数据库中的查询返回 2 行
SELECT * FROM [qSales]
例如:
sTYPE KILK WART
-------------------
HD 100 1000
LD 200 2000
现在,我想通过 C# 获得此结果。我的代码:
private static string connString = "Provider=Microsoft.ACE.OLEDB.12.0;"+
"Data Source=tgdb.accdb;" +
"Jet OLEDB:Database Password = wix;";
static void Main(string[] args)
{
string answer = string.Empty;
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
Console.WriteLine("Connection Is Established");
string SQL = "SELECT * FROM [qSales]";
using (OleDbCommand comm = new OleDbCommand(SQL, conn))
{
using (OleDbDataReader reader = comm.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
answer = $"{reader[0]}:t{reader[1]} t{reader[2]}n";
Console.WriteLine(answer);
}
}
}
}
conn.Close();
}
Console.WriteLine("Hit ENTER For Exit");
Console.ReadLine();
}
但我得到的结果与 MS Access 结果不同。总结
HD 300 3000
我做错了什么?
您是否尝试连接字符串以输出行? 另外,也许尝试将从查询返回的值转换为字符串。 请参阅下面的示例...
string answer = string.Empty;
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
Console.WriteLine("Connection Is Established");
string SQL = "SELECT * FROM [qSales]";
using (OleDbCommand comm = new OleDbCommand(SQL, conn))
{
using (OleDbDataReader reader = comm.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var firstCol = reader[0]?.ToString() ?? string.empty;
var secCol = reader[1]?.ToString() ?? string.empty;
var thirdCol = reader[2]?.ToString() ?? string.empty;
answer += string.Format(@"{0}:t{1}t{2}n", firstCol, secCol, thirdCol);
}
}
}
}
conn.Close();
}
Console.WriteLine(answer);
Console.WriteLine("Hit ENTER For Exit");
Console.ReadLine();
希望这有帮助。