【问题标题】:MySQL database to C# connection timeoutMySQL 数据库到 C# 连接超时
【发布时间】:2013-07-21 13:34:35
【问题描述】:

stackoverflow 社区!再一次,我来这里寻求你的帮助......

我的问题是:我制作了一个 c# 应用程序,用于在 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();
        }
    }
}

【问题讨论】:

    标签: c# mysql timeout


    【解决方案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#,没有任何问题,所以我认为这是您的托管问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 2011-11-18
      • 2019-12-09
      • 2012-04-27
      • 2013-07-26
      相关资源
      最近更新 更多