I am working with a dbf database. I need to query it to get information back in string format. The dbf file is set up as follows:
Student Name Student Number Student Description
HelloWorld 123456789 Present
WorldHello 987654321 Absent
Here is the code i have so far:
OleDbCommand command;
OleDbConne开发者_运维知识库ction 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);
Now i want to get the result as a comma seperated string as follows:
HelloWorld,123456789,Present
How can i do this?
There is 2 options.. 1 - Create a 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 - Modify the SQL Statement
command = new OleDbCommand("SELECT STUDENTNAME + ',' STUDENTNUMBER + ',' + STUDENTDESCRIPTION" + " FROM " + DbfFile + " WHERE " + STUDENTNAME='HelloWorld', conn);
string result = (string)command.ExecuteScalar();
Fetch the results using a DataReader (as explained here), and concatenate the results:
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string line = string.Format(
"{0},{1},{2}",
reader["STUDENTNAME"],
reader["STUDENTNUMBER"],
reader["STUDENTDESCRIPTION"]);
...
}
}
There are a few ways - the most straight forward and probably the least desirable one is to modify the SQL:
command = new OleDbCommand("SELECT STUDENTNAME + ',' + STUDENTNUMBER + ',' ...
Using 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());
}
result will be null on no records or the value you want
I would use an OleDbDataReader, the concatentate the strings:
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();
}
Hope this helps,
John
精彩评论