簡體   English   中英

在C#中從mysql數據庫填充datagridview

[英]Populating a datagridview from mysql database in c#

Helllo,我有一個mySQL數據庫,我想通過SQL select查詢從數據庫中提取信息,然后在datagride視圖中顯示此信息。 我已經寫了一個數據庫類。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using MySql;
using MySql.Data;
using System.Data;
using Renci.SshNet;
using Renci.SshNet.Common;
using System.Windows.Forms;
using System.Net.NetworkInformation;

namespace ExpTrackNEA

{
    class DatabaseManager
    {

        private MySqlConnection _Conn;
        public MySqlCommand Cmd;
        private MySqlDataAdapter _da;
        private DataTable _dt;
        private MySqlDataReader _dr;

        // This is the Database connection function
        public bool DBConnection()
        {
            // First step is to create an SSH Tunnel. This is done by calling the SSHTunnelCreate function
            if (SSHTunnelCreate() == true)
            {
                try // Start of Database connection Try attempt
                {
                    // Define the connection cerdentials
                    string ConnectionString = null;
                    ConnectionString = "server=SERVER;" +  // Database Address 
                        "               port=PORT;" +               // Port
                        "               database=DATABSAE;" + // Database Name
                        "               uid=USERNAME;" +              // Username
                        "               pwd=PASSWORd;";            // Password

                    // Define the connection
                    _Conn = new MySqlConnection(ConnectionString);

                    try // Attempt a connection
                    {
                        // Open the connection
                        _Conn.Open();


                        // Return true if connection is successful to the database
                        return true;

                    } // Rnd of database connection attempt

                    catch // Catach Database connection errors 
                    {
                        // Return False if a connection to the Database can't be made
                        return false;

                    } // End of Database connection errors catach


                } // End of Database connection Try attempt
                catch
                {

                    // If the connection is not successful it returns FALSE as it can't connect  
                    // to the database and the whole process is halted
                    return false;

                } // End of catch for Database Connection

            }// End of (SSHTunnelCreate() == true)
            else // If the SSH Tunnel Connection Failed
            {

                return false;

            }


        } // End of DBConnection Function



        private bool SSHTunnelCreate()
        {
            // Declaring the Connection string information
            ConnectionInfo ConnectionInformation = new ConnectionInfo(
                                                           "ssh.payneslan.co.uk",        // Host Name
                                                           22,                           // Connection Port
                                                           "UserNAME",                     // Username
                                                           new AuthenticationMethod[]{   // Define the Password
                                                            // Pasword based Authentication
                                                            // Define the connection information Username and Password respectfullt
                                                            new PasswordAuthenticationMethod("USERNAME","PASSWORD")
                                                           }
                                                         ); // End of ConnectionInformation

            using (var client = new SshClient(ConnectionInformation))
            {
                // Start an attempt to build an SSH Tunnel
                try
                { // SSH Tunnel Try Start
                    client.Connect();

                    if (client.IsConnected)
                    {
                        try
                        {
                            var PortFwdL = new ForwardedPortLocal("127.0.0.1", 3306, "localhost", 3306);
                            //ForwardedPortLocal PortFwdL = new ForwardedPortLocal("127.0.0.1", Convert.ToUInt32(22), "127.0.0.1", Convert.ToUInt32(3306));

                            client.AddForwardedPort(PortFwdL);
                            PortFwdL.Start();

                            // Checking Port Forwarding is working
                            if (PortFwdL.IsStarted)
                            {
                                return true;

                            }
                            else
                            {
                                return false;
                            }

                        }

                        catch
                        {
                            return false;
                        }

                    } // End of IF
                    else
                    {
                        // If the connection is not successful it returns FALSE as it now doesn't  
                        // have a secure connection to the server and now the database connection will
                        // halt.
                        return false;

                    } // End of Else
                } // End of Try
                catch // connection catch for SSH Tunnel creation
                {
                    // If the connection is not successful it returns FALSE as it now has a 
                    // secure connection to the server and now the database connection will
                    // halt
                    return false;

                } // End of connection catch for SSH Tunnel creation

            } // End of  using (var client = new SshClient(ConnectionInformation))

        } // End of SSHTunnelCreate Function.





        public void SQLQuery(string QueryText)
        {
            Cmd = new MySqlCommand(QueryText, _Conn);

        }




        public string strSQLQuery(string QueryText)
        {

            Cmd = new MySqlCommand(QueryText, _Conn);
            MySqlCommand cmd = new MySqlCommand(QueryText, _Conn);
          _dr = cmd.ExecuteReader();

           string _value = null;

            while (_dr.Read())
            {
                _value = _dr.GetString(0);
            }

            _dr.Close();
            return _value;

        }





        // For The select queries
        public DataGrid QueryEx(string QueryText)
        {
            MySqlDataAdapter adp = new MySqlDataAdapter("Select * from table1;", _Conn);

            DataSet ds = new DataSet();
            adp.Fill(ds);
            //change name according to your datagridview
            DataGrid dataGridView1 = new DataGrid();

            dataGridView1.DataSource = ds;
           // dataGridView1.DataBind();
            return dataGridView1;
        }




        // For Insert,Update and Delete etc.
        public void NonQueryEx()
        {
            try
            {
                Cmd.ExecuteNonQuery();
            }
            catch
            {
               MessageBox.Show("An error occured when trying to perform this databse action" + "\n" +
                        "Your action was not completed.",
                        "Error executing Action",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);


            }
        }

    } // End Of Class DatabaseManager
}

我想做的就是將SQL查詢傳遞到方法queryEx中,並獲取此方法以獲取所有字段並以某種狀態返回它,以便在表單上我可以簡單地放入類似內容。

DGV_Users.DataSource = DataBase.QueryEx("SELECT * FROM Users ");

我已經嘗試了幾天,但都失敗了,並且看了無數視頻,但是我什么也做不了。

謝謝。

因此,除了將所有內容放在單獨的函數和單獨的try / catch塊中之外,您可以只具有一個try / catch並使用using語句。

這樣做也意味着您可以擺脫大型的if / else語句和以下全局變量:

private MySqlConnection _Conn;
public MySqlCommand Cmd;
private DataTable _dt;

因此,所有基本數據庫查詢功能都應如下所示:

public DataTable FillDataTable()
{
    DataTable table = new DataTable();

    try
    {    
        // Define the connection credentials
        string ConnectionString = "server=SERVER;port=PORT;database=DATABSAE;uid=USERNAME;pwd=PASSWORd;"; 
        string commandString = "Select * from table1;";

        //Use the connection
        using(MySqlConnection connection = new MySqlConnection(ConnectionString))
        {
            connection.Open();

            //Pass in command text and connection string
            using(MySqlCommand command = new MySqlCommand(ConnectionString)
            {
                command.Connection = connection;
                command.Text = commandString;

                //Any parameters in command string, add here
                //command.Parameters.AddWithValue("@SomeValue", value)

                using(MySqlDataReader reader = command.ExecuteReader())
                {
                    table.Load(reader);
                }
            }
        }           
    }
    catch(Exception ex)
    {
        //Catch any exceptions here
    }

    return table;
}

然后在您的表單類中:

dataGridView1.DataSource = FillDataTable();

但這仍然不是最佳方法。 您可以使用DbConnection類,這樣就不必專門依賴MySql。

另外,您應該多清理一些代碼,例如變量命名約定和函數。 例如,此功能的目的是什么?

public void SQLQuery(string QueryText)
{
    Cmd = new MySqlCommand(QueryText, _Conn);

}

暫無
暫無

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

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