如何从访问数据库中获取多行

时间:2014-04-17 16:00:06

标签: c# mysql sql visual-studio

我正在尝试根据列Veh_ID存储访问数据库的每一行。找到的数据可能基于多行,也可能不基于多行。我目前使用的代码可以复制单行,但如果有多个结果,我只能得到第一个结果。有人可以帮我这个吗?在数据库方面我是菜鸟。我试图搜索谷歌,但似乎没有人需要我需要的东西。以下是我使用的代码:

string cmd1 = "SELECT * FROM Veh_checkup WHERE Veh_ID = " + veh_idd + "";
OleDbCommand cmd = new OleDbCommand(cmd1, con);            
OleDbDataReader read = cmd.ExecuteReader();
read.Read();
veh_id=null;

int i=0;

foreach (var a in read)
{
    try
    {
        veh_id = veh_id + " " + read[i].ToString();
    }
    catch { }
    i++;
}

2 个答案:

答案 0 :(得分:2)

我会指出一些事情,一些特定于你的问题,一些不是:

  • USE PARAMETERISED QUERIES
  • 使用OleDbDataReader.Read()移至下一条记录。
  • 使用StringBuilder在循环中连接字符串,使用string = string + "something"将在每次迭代时在堆上创建一个新字符串
  • 在Disposable对象上使用using
  • catch { }not good practice。你永远不会知道发生了错误。至少你应该在某个地方记录错误,这样你就知道需要修复一些东西了。
  • OleDbDataReader[i]将从列i获取正在读取的当前记录的数据,而不是来自行i的数据
  • 请勿在生产代码中使用SELECT *,尤其是如果您只使用1列。这是从数据库中检索不必要的数据以及不必要的网络流量。
  • USE PARAMETERISED QUERIES

好的,我知道我使用了两次参数化查询,但这就是我对它的强烈感受!

通过上述更改,您的完整代码将变为:

static string GetStringData(string vehID)
{
    StringBuilder builder = new StringBuilder();
    string cmd1 = "SELECT Column1 FROM Veh_checkup WHERE Veh_ID = @VehID";
    using (OleDbConnection con = new OleDbConnection("YourConnectionString"))
    using (OleDbCommand cmd = new OleDbCommand(cmd1, con))
    {
        con.Open();
        cmd.Parameters.AddWithValue("@VehID", vehID);

        using (OleDbDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                builder.Append(" " + reader.GetString(0));
            }
        }
    }
    return builder.ToString();
}

答案 1 :(得分:0)

您正在以错误的方式使用datareader。而不是像你一样调用它,你必须像这样在while循环中调用datareader:

while(theDataReader.Read())
{
    // do your stuff in a loop now
}

因此在代码中使用这种方法看起来像这样:

string cmd1 = "SELECT * FROM Veh_checkup WHERE Veh_ID = " + veh_idd + "";
OleDbCommand cmd = new OleDbCommand(cmd1, con);            
OleDbDataReader read = cmd.ExecuteReader();
veh_id=null;

con.Open();
while(read.Read()) //your reader
{
    try
    {
        veh_id = veh_id + " " + read[i].ToString();
    }
    catch { }

}