2013-07-22 202 views
0

stackoverflow社區!再次,我來這裏尋求你的幫助...MySQL數據庫到C#連接超時

我的問題是:我做了一個c#應用程序用於註冊由Byethost(SecureSignup)託管的MySQL數據庫中的帳戶。即使沒有條件變化,連接也可以工作,但並非全部。 有一分鐘我可以提交查詢,PhpMyAdmin將它顯示爲寫入數據庫的蜜蜂,但幾分鐘後,當我嘗試完全相同的事情時,出現各種超時錯誤,範圍從「無法從傳輸連接讀取數據:連接嘗試失敗,因爲連接方在一段時間後沒有正確響應,或者由於連接的主機未能響應而建立連接失敗。「以「超時IO操作」...這是我的代碼,也許它可以幫助你理解爲什麼它有時會有這樣一個奇怪的行爲,因爲我確實不能。

(我已授予從的cPanel我的IP遠程MySQL訪問和登錄數據是100%正確的)

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using MySql.Data.MySqlClient; 

namespace Main 
{ 
    public partial class Form1 : Form 
    { 
     string connString; 
     MySqlDataReader reader; 
     MySqlConnection conn; 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********"; 
      conn = new MySqlConnection(connString); 
      MySqlCommand command = conn.CreateCommand(); 
      command.CommandText = "INSERT into users (Username,password) VALUES('" + usr.Text + "','" + pass.Text + "')"; 
      conn.Open(); 
      int timeoutvalue = conn.ConnectionTimeout; 
      command.ExecuteNonQuery(); 
      MessageBox.Show(timeoutvalue.ToString()); //This was a curiousity, it displays 15 
      conn.Close(); 
     } 
    } 
} 

回答

1

您應該使用parameters防止SQL injection.

而且使用using語句妥善處理你的MySQL對象。

private void button1_Click(object sender, EventArgs e) 
{ 
    connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********"; 
    using (conn = new MySqlConnection(connString)) 
    { 
     string query = "INSERT INTO users (Username, password) VALUES (@usr, @pass)"; 
     // are you sure your column name is Username and not username ? 
     conn.Open(); 
     using (MySqlCommand cmd = new MySqlCommand(conn, query)) 
     { 
      cmd.Parameters.AddWithValue("@usr", usr.Text); 
      cmd.Parameters.AddWithValue("@pass", pass.Text); 
      cmd.ExecuteNonQuery(); 
      // No need to close your connection. The using statement will do that for you. 
     } 
    } 
} 

至於連接問題,我認爲你應該聯繫你的主機尋求答案。我一直使用MySql,使用C#,沒有任何問題,所以我認爲這是您的主機問題。

+0

非常感謝:3 –