c# - 应用程序上的并发用户导致 MySQL 数据库错误

标签 c# mysql multiple-users

我有一个连接到 MySQL 数据库的 C# Web 应用程序。当多个用户同时访问该站点时,我们会看到“已经有一个与此命令相关联的打开的数据阅读器必须先关闭”错误。当只有一个人访问网站时,该应用程序工作正常。

我发现多篇文章在连接字符串中设置了 MultipleActiveResultSets=True,但这只适用于 SQL Server 而不是 MySql。

我将错误追溯到我的 runSQL 函数,该函数处理我的大部分数据库查询,但无法找到解决方案。

这是一个相当直接的函数,它采用原始 sql 代码、参数列表、一个转换为许多可能的数据库连接字符串之一的枚举,以及一​​个确定我们是否需要设置事务的 bool 值。

我很茫然。

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;
}

最佳答案

MySql 中的并发是一场噩梦。很抱歉以这样的方式开始,但如果可能的话,您应该移植到 MSSQL,因为您使用的是 c# 并且它集成起来非常容易。

使用 MyISAM MySQL 数据库引擎时,并发性特别差。首先,一个大的危险信号是 MyISAM 不支持事务。这意味着您不能更改任何读取或更新的隔离级别。其次,与第一个相关的是,对表使用读取会发出低级表锁。但是,为了进行更新,它必须具有独占表锁,其他任何东西(即使是低级别的锁)都会阻止更新发生,并且它会进入锁队列。

没有解决这个问题,因为它是设计使然。

关于c# - 应用程序上的并发用户导致 MySQL 数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325716/

相关文章:

c# - 如何在 gRPC 服务器上关闭 HTTPS

php - SQL INNER JOIN 未正确连接?

具有多个帐户的 Git 在执行 ssh 时提供相同的用户名

Facebook批量请求多个用户

C# Help Basic in 矩阵

c# - C#中 'this'关键字的用途是什么

c# - 通过 Newtonsoft.Json 将 JSON 消息的日期时间数组解析为 C# 时出错

android - 从 mysql (BLOB) 检索图像并将它们显示到 ListView

php - 如何使用 MySQL 手动跟踪 Wordpress 中的沙箱 Paypal 重复交易

sql-server - 如何测量Azure sql server数据库中用户消耗的数据?