簡體   English   中英

c#使用MySQL連接到數據庫

[英]c# Connecting to database using MySQL

我想連接到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主機。

我自己一直在努力解決這個問題,這是我的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設置選項卡中。

您可以像這樣調用它們: Properties.Settings.Default.serverIp

它稍微容易一些,所以最終您可以這樣做:

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

等等。

也可能試圖改變UID在你的ConnectionString TYO Uid

另外,您可以捕獲異常,但不使用它,在這種情況下,默認值應顯示為異常,以便您可以理解。 您可以這樣做:

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

您必須使用DBLinq將mysql集成到C#。

請訪問DBLinq

暫無
暫無

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

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