【问题标题】:c# Connecting to database using MySQLc# 使用 MySQL 连接数据库
【发布时间】:2015-06-22 07:34:09
【问题描述】:

我想在 VirtualBox 上连接到我的 SqlDatabase。我尝试了不同的方法来做到这一点,但不幸的是,它不起作用。
我添加了MySql.DataMySql.Data.MySqlClient

        MySqlConnection connection;
        string server;
        string database;
        string uid;
        string password;
        string port;
        server = "192.168.1.21";
        port = "3306";
        database = "terminal1";
        uid = "root";
        password = "pass";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "PORT=" + port +         ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";" + "Pooling=false";
        connection = new MySqlConnection(connectionString);


        try
        {
            connection.Open();
            label1.Text = "NET - OK";
        }
        catch (MySqlException ex)
        {
            //0: Cannot connect to server.
            //1042: Unable to connect to any of the specified MySQL hosts.
            //1045: Invalid user name and/or password.
            switch (ex.Number)
            {
                case 0:
                    MessageBox.Show("Cannot connect to server.  Contact administrator");
                    break;
                case 1042:
                    MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
                    break;
                case 1045:
                    MessageBox.Show("Invalid username/password, please try again");
                    break;
                default:

                        label1.Text = "NET - ERROR";

                    break;
            }

        }

谁能帮忙?

编辑: 程序显示错误 1042: Unable to connect to any specified MySQL hosts 。

【问题讨论】:

  • 不工作怎么办? mysql 服务器是否接受来自本地主机以外的其他主机的连接?
  • 在 PHP 中我可以通过 ip 连接,所以我认为服务器接受来自 localhost 以外的其他主机的连接
  • 请...不要使用标准的点网名称
  • 而 catch 1042 本身并不是错误,试试这个以获得真正的错误:1 MessageBox.Show("Error: " + ex.Message)
  • 我已经编辑了我的 awnser 也许它可以提供帮助

标签: c# mysql linq database-connection


【解决方案1】:

我自己也遇到过这个问题,这是我的 sqlclass:

namespace Chat
{
    internal class DBConnect
    {
        private MySqlConnection _connection = new MySqlConnection();
        private MySqlConnection _register = new MySqlConnection();
        private MySqlConnection _userdata = new MySqlConnection();
        private string _server;
        private string _database;
        private string _uid;
        private string _password;
        public String MessageRecieved;
        //private string _table = "testconnectie";
        private string _port;
        //private bool succes = false;


        //Constructor
        public DBConnect()
        {
            InitializeChat();
            InitializeRegister();
        }

        //Initialize values
        public void InitializeChat()
        {
            _server = "localhost";
            _port = "3307";
            _database = "test";
            _uid = "root";
            _password = "usbw";


            string connectionString = "Server=" + _server + ";" + "Port=" + _port +";" + "Database=" +
                               _database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";

            _connection = new MySqlConnection(connectionString);
        }

        public void InitializeUserData()
        {
            _server = "localhost";
            _port = "3307";
            _uid = "root";
            _password = "usbw";


            string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
                               _database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";

            _connection = new MySqlConnection(connectionString);
        }

        public void InitializeRegister()
        {
            _server = "localhost";
            _port = "3307";
            _database = "testlogin";
            _uid = "root";
            _password = "usbw";


            string registerString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
                               _database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";

            _register = new MySqlConnection(registerString);
        }

        public bool OpenConnection()
        {
            try
            {
                _register.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        MessageBox.Show("Cannot connect to server");
                        break;

                    case 1042:
                        MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
                        break;

                    case 1045:
                        MessageBox.Show("Invalid username/password");
                        break;
                }
                return false;

            }

        }

        public void Select()
        {
            string selectquery = "SELECT * FROM testconnectie";

            MySqlCommand cmd = new MySqlCommand(selectquery, _connection);

            MySqlDataReader dataReader = cmd.ExecuteReader();

            _messagelist.Clear();
            while (dataReader.Read())
            {
                _messagelist.Add(dataReader["time"] + "      ");
                _messagelist.Add(dataReader["text"] + "\r\n");
            }

            dataReader.Close();


            MessageRecieved = _messagelist.ToString(); 

        }

        public void Insert(string textvalue)
        {
            //DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");

            //dt.ToString("H:mm"); // 7:00 // 24 hour clock

            //var now = DateTime.Now;
            //var minutes = now.Minute;
            //var hour = now.Hour;
            //var time = now;

            string time = DateTime.Now.ToString("HH:mm:ss");

            string insertquery = "INSERT INTO testconnectie(time, text) VALUES ('"+time+"','"+textvalue+"')";

            try
            {
                MySqlCommand cmd = new MySqlCommand(insertquery, _connection);

                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error(1)" + ex);
            }
        }

        private void Update()
        {
            string updatequery = "UPDATE tabelnaam SET waarde='', waarde'' WHERE waarde=''";

            MySqlCommand cmd = new MySqlCommand();

            cmd.CommandText = updatequery;
            cmd.Connection = _connection;

            cmd.ExecuteNonQuery();
        }

        private void Delete()
        {
            string deletequery = "DELETE FROM tabelnaam WHERE waarde=''";

            MySqlCommand cmd = new MySqlCommand(deletequery, _connection);
            cmd.ExecuteNonQuery();
        }

        public bool CloseConnection()
        {
            try
            {
                _connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;

            }

        }


        public void Backup()
        {
            try
            {
                DateTime Time = DateTime.Now;
                int year = Time.Year;
                int month = Time.Month;
                int day = Time.Day;
                int hour = Time.Hour;
                int minute = Time.Minute;
                int second = Time.Second;
                int millisecond = Time.Millisecond;

                //Save file to C:\ with the current date as a filename
                string path;
                path = "C:\\ChatBackup" + year + "-" + month + "-" + day +
            "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
                StreamWriter file = new StreamWriter(path);


                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = "Database Backup";
                psi.RedirectStandardInput = false;
                psi.RedirectStandardOutput = true;
                psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
            _uid, _password, _server, _database);
                psi.UseShellExecute = false;

                Process process = Process.Start(psi);

                string output;
                output = process.StandardOutput.ReadToEnd();
                file.WriteLine(output);
                process.WaitForExit();
                file.Close();
                process.Close();
            }
            catch (IOException ex)
            {
                MessageBox.Show("Error , unable to backup! " + ex);
            }
        }



    }

}

希望这有助于它可能有点大,但只需使用您需要的功能

你可以做的是使用项目属性中的设置来存储你所有的连接数据。

所以你可以把 serverIp、Port、Database、Uid 和密码放在 de setting 选项卡中。

你可以这样称呼他们:Properties.Settings.Default.serverIp

它更容易,所以最后你可以这样做:

string serverIp = Properties.Setting.Default.serverIp;
string port = Properties.Setting.Default.port;
string username = Properties.Setting.Default.Uid;

等等。

也可以尝试更改连接字符串中的UID Uid

您也捕获了异常但您不使用它,在这种情况下,默认值应显示为异常,以便您理解它。你可以这样做:

label1.Text = "Error: " + ex.Message;

【讨论】:

    【解决方案2】:

    您必须使用 DBLinq 将 mysql 集成到 C#。

    请访问DBLinq

    【讨论】:

    • 为什么必须使用它?我的意思是 Mysql.Data 工作得很好
    猜你喜欢
    • 2012-04-27
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    相关资源
    最近更新 更多