I'm using .NET Connector to connect to MySQL. In my application there are few threads using the same connection, so if a MySQLDataReader is not closed yet and some thread is trying execute a query it gives that error:
There is already an open DataReader associated with this Connection which must be closed first.
Will there ever be support in MySQL for multiple result sets or however it's called?
My database management class:
public class DatabaseConnection
{
private MySqlConnection conn;
public void Connect(string server, string user, string password, string database, int port = 3306)
{
string connStr = String.Format("server={0};user={1};database={2};port={3};password={4};charset=utf8",
server, user, database, port, password);
conn = new MySqlConnection(connStr);
conn.Open();
}
private MySqlCommand PrepareQuery(string query, object[] args)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
for (int i = 0; i < args.Length; i++)
{
string param = "{" + i + "}";
string paramName = "@DBVar_" + i;
query = query.Replace(param, paramName);
cmd.Parameters.AddWithValue(paramName, args[i]);
}
cmd.CommandText = query;
return cmd;
}
public List<Dictionary<string, object>> Query(string query, params object[] args)
{
MySqlCommand cmd = PrepareQuery(query, args);
MySqlDataReader reader = cmd.ExecuteReader();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
while (reader.Read())
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row.Add(reader.GetName(i), reader.GetValue(i));
}
rows.Add(row);
}
reader.Close();
return rows;
}
public object ScalarQuery(string query, params object[] args)
{
MySqlCommand cmd = PrepareQuery(query, args);
return cmd.ExecuteScalar();
}
public void Execute(string query, params object[] args)
{
MySqlCommand cmd = PrepareQuery(query, args);
cmd.ExecuteNonQuery();
}
public void Close()
{
conn.Close();
}
}
An example of how I use this:
DatabaseConnection Conn = new DatabaseConnection();
Conn.Connect("localhost", "root", "", "foogle");
var rows = conn.Query("SELECT * FROM `posts` WHERE `id` = {0}", postID);
foreach (var row in rows)
{
Console.WriteLine(row["title"]); // Writes the post's title (example)
}