c# 使用 MySQL 连接到数据库

本文关键字:数据库 连接 MySQL 使用 | 更新日期: 2023-09-27 17:57:24

我想在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:无法连接到任何指定的 MySQL 主机 。

c# 使用 MySQL 连接到数据库

我自己一直在努力解决这个问题,这是我的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);
            }
        }

    }
}

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

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

因此,您可以将服务器IP,端口,数据库,Uid和密码放在de设置选项卡中。

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

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

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

等等。

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

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

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

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

请访问DBLinq