簡體   English   中英

通過Connector / NET與MySQL進行C#

[英]C# with MySQL through Connector/NET

我正在用C#(4.0 Framework)開發CMS應用程序,它通過MySQL Connector(6.5.4)連接到遠程服務器上的MySQL數據庫(5.0.95)。

我在執行查詢時遇到問題。

例如我的連接字符串:

"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:

有什么建議?

我注意到你打開了連接,但是當你完成它們時你不會關閉它們。 我更喜歡在需要時打開連接的方法,而不是在它們尚未打開時打開連接。 它們可能是陳舊的。

緩存連接字符串但不緩存連接本身。

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

當不再需要資源時,應釋放資源。

我建議您查看有關此問題的錯誤報告。

MySQL在不同級別使用一堆不同的超時變量。

建立連接時 - > connect_timeout

當服務器等待空閑以便發送另一個查詢時 - > wait_timeout

如果正在讀取查詢或正在發送結果集 - > net_read_timeoutnet_write_timeout

net_write_timeout和net_read_timeout都是會話級變量,因此當您知道查詢會很麻煩時,您可以根據連接更改它們,因此它不會影響服務器的其余部分。 (作為解決方法)

但首先,您應該通過執行以下操作來檢查服務器上每個超時值的默認值:

show variables like '%timeout%'

您還應該查看您正在插入的命令,看看它是否可以簡化,或者分解介紹較小的更新。

添加MySqlDataAdapter.SelectCommand.CommandTimeout = 600對我MySqlDataAdapter.SelectCommand.CommandTimeout = 600 這是我找到它的鏈接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM