【问题标题】:C# with MySQL through Connector/NET通过连接器/NET 使用 MySQL 的 C#
【发布时间】:2012-04-03 10:14:13
【问题描述】:

我正在用 C#(4.0 Framework) 开发 CMS 应用程序,它连接到远程服务器上的 MySQL 数据库 (5.0.95) 通过 MySQL 连接器 (6.5.4)。

我在执行查询时遇到问题。

例如 我的连接字符串:

"Server=" + Options.DbServer + ";Database="+ Options.Database +";Uid=" + Options.DbUser + ";Pwd=" + Options.DbPassword + ";CharSet=utf8; Connect Timeout=30;";

我有管理数据库相关内容的静态类,并且我有私有成员 _connection。

private static MySqlConnection _connection;
public static MySqlConnection Connection
{ 
    get
    {
        if (_connection.State != ConnectionState.Open)
            _connection.Open();

        return _connection;
    } 
    set { _connection = value; }
}

这是初始化连接的方法:

public static bool Init(string cs)
{
    _connection = new MySqlConnection(cs);
    MySqlCommand command = new MySqlCommand("SET NAMES utf8", Connection);
    command.ExecuteNonQuery();
    return true;
}

这是我得到异常的方法:

public static bool InsertRecord(MySqlCommand command)
{
    command.Connection = Connection;
    if(command.ExecuteNonQuery() > 0)
        return true;

    return false;
}

command.ExecuteNonQuery() 抛出异常:命令执行过程中遇到致命错误。

这是堆栈跟踪...

MySql.Data.MySqlClient.MySqlException was unhandled
  Message=Fatal error encountered during command execution.
  Source=MySql.Data
  ErrorCode=-2147467259
  Number=0
  StackTrace:
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
       at CMS.Database.InsertRecord(MySqlCommand command) in C:\_myStuff\VS2010\CMS\CMS\Database.cs:line 95
       at CMS.frmAddItem.btnDo_Click(Object sender, EventArgs e) in C:\_myStuff\VS2010\CMS\CMS\frmAddItem.cs:line 138
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.RunDialog(Form form)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at CMS.frmMain.btnNovi_Click(Object sender, EventArgs e) in C:\_myStuff\VS2010\CMS\CMS\frmMain.cs:line 381
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.RunDialog(Form form)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at CMS.frmLogin.DoLogin() in C:\_myStuff\VS2010\CMS\CMS\frmLogin.cs:line 55
       at CMS.frmLogin.button2_Click(Object sender, EventArgs e) in C:\_myStuff\VS2010\CMS\CMS\frmLogin.cs:line 31
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at CMS.Program.Main() in C:\_myStuff\VS2010\CMS\CMS\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: MySql.Data.MySqlClient.MySqlException
       Message=Fatal error encountered attempting to read the resultset.
       Source=MySql.Data
       ErrorCode=-2147467259
       Number=0
       StackTrace:
            at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
            at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       InnerException: MySql.Data.MySqlClient.MySqlException
            Message=Reading from the stream has failed.
            Source=MySql.Data
            ErrorCode=-2147467259
            Number=0
            StackTrace:
                 at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
                 at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
                 at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& insertedId)
                 at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int32& insertedId)
                 at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
                 at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
            InnerException: System.IO.EndOfStreamException
                 Message=Attempted to read past the end of the stream.
                 Source=MySql.Data
                 StackTrace:
                      at MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, Byte[] buffer, Int32 offset, Int32 count)
                      at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
                 InnerException:

有什么建议吗?

【问题讨论】:

  • Message=Attempted to read past the end of the stream. - 您正在某处执行 reader
  • 堆栈跟踪表明 ExecuteNonQuery 调用了 ExecuteReader。我会说你仍然没有成功连接到数据库。你有没有打电话给Init()
  • 什么是command 在您得到异常的地方?看看那里。断点对于在异常发生之前检查状态很有用...
  • @Oded:不,我没有执行阅读器。就像 dwerner 说的,读者被 ExecuteNonQuery() 间接调用
  • @dwerner:我已连接到数据库。更具体地说,我的查询有时会成功完成。一段时间不活动后抛出异常。

标签: c# mysql mysql-connector


【解决方案1】:

我注意到您打开了连接,但在完成连接后并没有关闭它们。我更喜欢在需要时打开连接的方法,而不是在它们尚未打开时打开它们。它们可能已经过时了。

缓存连接字符串,但不缓存连接本身。

public static string ConnectionString {get;set;}

public static bool InsertRecord(sql)
{
    bool success = false;
    using (var con = new Connection(ConnectionString)){
        var command = new SqlCommand(sql,con);
        success = (command.ExecuteNonQuery() > 0);
    }
    return success;
}

当不再需要资源时,应该释放它们。

【讨论】:

  • 是的,这显然是更好的方法。我根据您的建议更改了方法,并且异常消失了。目前。 :) 非常感谢!
【解决方案2】:

我建议您查看this 关于此问题的错误报告。

【讨论】:

  • @Mikhail Preyskurantov:谢谢你的建议,但在你指导我的例子中,家伙有一些内部异常消息:"Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."我的堆栈跟踪中没有那个消息.最后,我在连接字符串中添加了命令超时,但情况还是一样。
【解决方案3】:

MySQL 在不同级别使用了一堆不同的超时变量。

建立连接时 -> connect_timeout

当服务器空闲等待发送另一个查询时 -> wait_timeout

如果正在读取查询或正在发回结果集 -> net_read_timeoutnet_write_timeout

net_write_timeout 和 net_read_timeout 都是会话级别的变量,因此当您知道查询会很麻烦并且不会影响服务器的其余部分时,您可以简单地为每个连接更改它们。 (作为一种解决方法)

但首先,您应该通过执行以下操作检查服务器上每个超时值的默认值:

show variables like '%timeout%'

您还应该查看您正在插入的命令,看看它是否可以简化,或者分解为更小的更新。

【讨论】:

  • 这些是我的值: net_read_timeout 30 net_write_timeout 60 那么,这意味着读取超时是 30 秒吗?我的查询实际上很简单,我在 4 列的表中插入记录。
  • 是的,好像是这样^^ 是否与崩溃所需的时间相匹配?尝试'SET @@session.net_read_timeout=360;'如果是这样的话,在插入查询之前。
  • 不,它几乎立即崩溃,所以我认为增加此超时时间不会有帮助。
【解决方案4】:

添加MySqlDataAdapter.SelectCommand.CommandTimeout = 600 对我有用。这是我找到它的链接:

https://www.codeproject.com/Questions/665556/Connection-Timeout-Problem-with-MySqlDataAdapter-h

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 2012-02-12
    • 2011-12-16
    • 2011-09-17
    • 2016-01-27
    • 1970-01-01
    • 2017-09-14
    • 2011-06-19
    相关资源
    最近更新 更多