获取在c#中以字符串形式返回的statabase查询

时间:2011-07-12 14:31:27

标签: c#

我正在使用dbf数据库。我需要查询它以字符串格式获取信息。 dbf文件设置如下:

Student Name  Student Number  Student Description
HelloWorld      123456789          Present
WorldHello      987654321          Absent

这是我到目前为止的代码:

    OleDbCommand command;
    OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = " + dbfPath + ";Extended Properties=dBase III");
    command = new OleDbCommand("SELECT STUDENTNAME, STUDENTNUMBER, STUDENTDESCRIPTION" + " FROM " + DbfFile + " WHERE " + STUDENTNAME='HelloWorld', conn);

现在我想将结果作为逗号分隔字符串,如下所示:

的HelloWorld,123456789,现状

我该怎么做?

5 个答案:

答案 0 :(得分:1)

有2种选择.. 1 - 创建DataReader

 myCommand.ExecuteReader ( CommandBehavior.CloseConnection );
   string result;
   while ( myReader.Read ( ) ) {
      result = string.format("{0},{1},{2}"),myReader.GetString(0),myReader.GetString(1),myReader.GetString(2) );
   }
   myReader.Close ( );
   myConn.Close ( );

2 - 修改SQL语句

command = new OleDbCommand("SELECT STUDENTNAME + ',' STUDENTNUMBER + ',' + STUDENTDESCRIPTION" + " FROM " + DbfFile + " WHERE " + STUDENTNAME='HelloWorld', conn);
string result = (string)command.ExecuteScalar();

答案 1 :(得分:0)

有几种方法 - 最直接的,也可能是最不可取的方法是修改SQL:

command = new OleDbCommand("SELECT STUDENTNAME + ',' + STUDENTNUMBER + ',' ...

答案 2 :(得分:0)

使用DataReader获取结果(如here所述),并连接结果:

using (var reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        string line = string.Format(
                          "{0},{1},{2}",
                          reader["STUDENTNAME"],
                          reader["STUDENTNUMBER"],
                          reader["STUDENTDESCRIPTION"]);

        ...
    }
}

答案 3 :(得分:0)

使用Linq .... using System.Linq

string result;
var reader=command.CreateReader();
if (reader.Read()) {
  result=String.Join(",",Enumerable.Range(0,reader.FieldCount).Select(x=>reader.IsDbNull(x) ? String.Empty : reader[x].ToString()).ToArray());
}
没有记录或你想要的值

结果将为null

答案 4 :(得分:0)

我会使用OleDbDataReader,连接字符串:

using (OleDbConnection connection = new OleDbConnection(connectionString))

    {
        OleDbCommand command = new OleDbCommand(queryString, connection);
        connection.Open();
        OleDbDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            // put your logic here to concatenate the strings
            Console.WriteLine(string.Format("{0},{1},{2}",
                  reader["STUDENTNAME"],
                  reader["STUDENTNUMBER"],
                  reader["STUDENTDESCRIPTION"]);    
        }
        reader.Close();
    }

希望这有帮助,

约翰