Have you looked into the IDataReader types, such as OdbcDataReader?
thines01
Postaholic
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
You have the words "Data Source" twice in your connection string.
You could also change your function so it can also be used outside of a WinForms app sorta like this:
private static bool readDatabase(ref string strError)
{
bool blnRetVal = true;
// Define the Select statement.
string selectSQL = "SELECT name, surname FROM Players";
try
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbDataReader rdr = (new OleDbCommand(selectSQL, conn)).ExecuteReader())
{
while (rdr.Read())
{
// Populate player
}
rdr.Close();
}
conn.Close();
}
}
catch (Exception exc)
{
blnRetVal = false;
strError = exc.Message;
}
return blnRetVal;
}
...then it can be called like this:
static void FunctionThatUsesTheData()
{
string strError = "";
if (!readDatabase(ref strError))
{
// Display ErrorMessage Here
// MessageBox.Show or Console.WriteLine, etc...
return; // <-- RETURN!
}
// more code goes here
}
Another benefit is that the variables have a more limited scope and you won't have to figure out if the database is open or closed.
I "smothered" that OleDbCommand because it only has one purpose (to bring you the OleDbDataReader).
Of course, if you were adding parameters (or doing something else with it), it should have its own variable.
thines01
Postaholic
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
Inside the while(rdr.Read()), you can use:
string strMyField = rdr["FIELDNAME"].ToString().Trim();
So, depending on the structure of the object "Player", you can query the values like this directly into the fields of Player;
thines01
Postaholic
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
Another technique I use is to let the constructor of the object take the entire IDataReader and parse into its own fields.
Check out this posting .
thines01
Postaholic
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402