2012-03-18 9 views
5

C# (4.0 Framework) CMS uygulamasında geliştiriyorum, bu da MySQL Bağlayıcısı (6.5.4) tarafından uzak sunucuda MySQL veritabanına (5.0.95) bağlanıyor.C# ile MySQL üzerinden Bağlayıcı/NET

Sorguları yürütmede sorun yaşıyorum.

örn. Benim bağlantı dizesi:

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

Ben veritabanı ile ilgili şeyler yöneten statik sınıf var ve orada özel üye _connection var.

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

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

Bu bağlantıyı başlatır yöntemdir:

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

    return false; 
} 

command.ExecuteNonQuery() istisna atar: Komut yürütme sırasında karşılaşılan önemli hata

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

Bu özel durum almak yöntemdir.

Bu

... iz

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: 

Herhangi öneri yığını edilir?

+2

'İleti = Akışın sonunu okumayı denediniz. '- Bir yerde _reader_ yürütüyorsunuz. – Oded

+1

Yığınlama, ExecuteNonQuery'nin ExecuteReader çağırdığını gösterir. Hala veritabanına başarılı bir şekilde bağlanmadığınızı söyleyebilirim. Hiç Init() 'i çağırır mısın? – dwerner

+0

İstisnayı elde ettiğiniz noktada 'komut 'nedir? Oraya bir bak. Ayrılma noktaları oluşmadan önce durumu incelemek yararlıdır ... – dwerner

cevap

6

Bağlantıları açtığınızı farkettim, ancak bunlarla işiniz bittiğinde bunları kapatmıyorsunuz. İhtiyaç duyulduğunda bağlantıları açmayı tercih ediyorum, zaten açık olmadıkları takdirde onları açmaktan ziyade. Bayat olabilirler.

bağlantı dizgisini bağlantı dizgisiyle önbelleğe alın.

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

Artık gerekli olmadığında kaynaklar serbest bırakılmalıdır.

+0

Evet, bu açıkça daha iyi bir yaklaşım. Yöntemleri önerinize göre değiştirdim ve istisnalar gitti. Şimdilik. :) Çok teşekkür ederim! – magic

+0

Rica ederim! – dwerner

2

Bu sorunla ilgili this hata raporunu kontrol etmenizi öneririz.

+0

varsayılan komut zaman aşımı = 3600; – dwerner

+1

@Mikhail Preyskurantov: Öneriniz için teşekkür ederim, ama mesela beni yönlendiriyorsun, adam İç istisnalar mesajında ​​bazılarına sahip: "Zaman aşımı süresi doldu. İşlemin tamamlanmasından önce zaman aşımı süresi doldu veya sunucu yanıt vermiyor. "' Bu iletiyi yığın izimde yok. Son olarak, bağlantı dizimde komut zaman aşımı ekledim, ancak durum yine aynı. – magic

1

MySQL, farklı düzeylerde bir grup farklı zaman aşımı değişkenini kullanır. >connect_timeout

sunucu başka sorgu için boşta bekler gönderilmek üzere - -

Bağlantı kurulurken zaman>

wait_timeout sorgu okunduğunu veya geri gönderiliyor kümesi neden - > net_read_timeout ve

net_write_timeout net_write_timeout ve net_read_timeout Hem şunlardır se ssion level degiskenleri, böylece sorgunun basarisiz oldugunu ve bu nedenle sunucunun geri kalanini etkilemeyecegini bildiğiniz zaman baglantilarina göre degistirebilirsiniz.

(geçici bir çözüm olarak) Ama önce, böyle bir şey yürüterek sunucunuzda bu zaman aşımı değerlerin her biri için varsayılan değer kontrolleri gerekir: Ayrıca komuta bakmak gerekir

show variables like '%timeout%' 

sen ekliyorsanız basitleştirilip genişletilemeyeceğini veya küçük güncellemelerin tanıtılabildiğini görün.

+0

Bunlar benim değerlerim: net_read_timeout net_write_timeout Yani, okuma zaman aşımı 30 saniye demektir? Benim sorgum aslında çok basit, 4 sütun ile tabloya kayıt ekliyorum. – magic

+0

evet, öyle görünüyor ki ^^ Çökmesi gereken süreyle eşleşiyor mu? 'SET @@ session.net_read_timeout = 360;' seçeneğini deneyin. Bu durumda, insert sorgulamadan önce. – Kharaone

+0

Hayır, neredeyse anında çöküyor, bu yüzden bu zaman aşımının artmasının yardımcı olacağını düşünmüyorum. – magic