I’m working on a basic mysql database class, with a couple of functions. One of the functions should return a list of all rows and columns. The code is working, and it’s pretty dynamic, but it also looks like it could be improved. I was hoping someone could take a look at this code and tell me if there’s another solution to doing this?
One of the other solutions I tried was without lists, but it involved recreating an array for every row it had to return, so I dropped that and moved on to lists.
public List<object[]> ReadAllRows(string sQuery)
{
List<object[]> oResults = new List<object[]>();
try
{
MySqlCommand msCommand = new MySqlCommand
{
CommandText = sQuery,
Connection = Connection
};
using (MySqlDataReader msReader = msCommand.ExecuteReader())
{
if(!msReader.HasRows)
return EmptyList;
while (msReader.Read())
{
object[] oRowValues = new object[msReader.FieldCount];
{
msReader.GetValues(oRowValues);
}
oResults.Add(new object[] { oRowValues });
}
}
}
catch (MySqlException ex)
{
LastError = "Error: " + ex;
return EmptyList;
}
return oResults;
}
If there are any questions, please feel free to ask
I would highly recommend against doing this.
First off, you should only keep a connection open as long as it takes to execute the command. Also, MySqlCommand implements IDisposable, so that should be wrapped in a using clause.
One reason I recommend against it is that this functionality is already covered. A simple way is to have your methods just return a DataTable. DataTables are going to give you every bit of information you’ll need anyway (data type, rows, columns, etc) while yours is very limiting.
Another reason has to do with maintaining an open connection: bad idea. Connection Pooling will take care of opening/closing connections very very quickly so it’s just not necessary. Also, in case your app crashes then you are going to be leaking connections. At some point you’ll end up with wonderful little database errors.