OleDBReader ExecuteReader返回1行而不是2

时间:2018-03-17 15:15:31

标签: c# ms-access-2016 oledbdatareader

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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您是否尝试连接字符串以输出行?此外,可能尝试将查询返回的值转换为字符串。请看下面的示例......

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();

希望这会有所帮助。