簡體   English   中英

MySQL數據庫到C#的連接超時

[英]MySQL database to C# connection timeout

stackoverflow社區! 我再次來到這里尋求您的幫助...

我的問題是:我制作了一個ac#應用程序,用於在Byethost(SecureSignup)托管的MySQL數據庫中注冊帳戶。 即使沒有任何條件更改,連接也不會一直有效。 一分鍾后,我可以提交查詢,PhpMyAdmin會將其顯示為寫在數據庫中的蜜蜂,但是幾分鍾后,當我嘗試完全相同的操作時,遇到了各種超時錯誤,其范圍從“無法從傳輸連接讀取數據:A連接嘗試失敗,因為連接的一方在一段時間后未正確響應,或者建立的連接失敗,因為連接的主機未能響應。” 到“超時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();
        }
    }
}

您應該使用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.
        }
    }
}

至於連接問題,我認為您應該與您的房東聯系以尋求答案。 我一直在使用C#來使用MySql ,沒有任何問題,所以我認為這是您的托管問題。

暫無
暫無

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

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