我有一个连接到 MySQL 数据库的 C# Web 应用程序。当多个用户同时访问该站点时,我们会看到“已经有一个打开的数据读取器与此命令关联,必须先关闭”错误。当只有一个人访问该站点时,该应用程序可以正常工作。
我发现多篇文章在连接字符串中设置了 MultipleActiveResultSets=True,但这仅适用于 SQL Server 而不是 MySql。
我将错误追溯到处理大量数据库查询的 runSQL 函数,但找不到解决方案。
这是一个相当直接的函数,它需要原始 sql 代码、参数列表、转换为许多可能的数据库连接字符串之一的枚举以及确定我们是否需要设置事务的布尔值。
我很茫然。
public DataTable runSQL(string QueryStr, List<MySqlParameter> Parameters, ConnectionType Connection, bool Transaction)
{
DataTable results = new DataTable();
MySqlConnection con = new MySqlConnection(getConnection(Connection));
MySqlTransation trans;
MySqlCommand command;
con.Open();
//if a transaction was requested, tie one to the query
if(Transaction)
{
trans = con.BeginTransaction();
command = new MySqlCommand(QueryStr, con, trans);
}
else
{
command = new MySqlCommand(QueryStr, con);
}
//if parameters were provided add them to the query
if(Parameters.Count > 0)
foreach(MySqlParameter parm in Parameters)
command.Parameters.Add(parm);
try
{
//send the command and get the results
MySqlReader rdr = command.ExecureReader();
//populate the column names
string columnName;
Type type;
foreach(DataViewRow row in rdr.GetSchemaTable().DefaultView)
{
columnName = row["ColumnName"].ToString();
type = (Type)row["DataType"];
results.Columns.Add(columnName, type);
}
//populate the results
results.Load(rdr);
//so far so good, close the transaction if one was requested
if(Transaction)
{
command.Transaction.Commit();
}
con.Close();
}
catch (Exception up)
{
//something bad happened, rollback if there was a transaction
if(Transaction)
{
command.Transaction.Rollback();
}
con.Close();
//report the error for handling at source.
throw up;
}
return results;
}