2017-11-26 10 views
0

Helllo、 私はmySQLデータベースを持っています.SQL選択クエリを使用して情報を取り出し、この情報をDataGridビューに表示したいとします。私はすでにデータベースクラスを作成しています。mysqlデータベースからdatagridviewにデータを設定する#

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 
} 

そして、私は何をしたいかの方法queryExにSQLクエリを渡し、すべてのフィールドを取得するには、この方法を取得し、そのフォームに私は単にのようなものを置くことができるような状態でそれを返しこの。

DGV_Users.DataSource = DataBase.QueryEx("SELECT * FROMユーザー");

私が試したし、数日のためにこれを行うに失敗し、数え切れないほどのビデオを見ているが、私は任意のものを動作させることはできませんしています。

ありがとうございます。

+0

あなたはそのコードにどのような問題がありますか? –

+0

塗りつぶし:SelectedCommand.connectionプロパティが初期化されていません " –

+0

このデータベースの"ヘルパー "クラスを後悔します。[ask]を読んで[ツアー]を受けてください – Plutonix

答えて

0

別々の機能と別々のtry/catchブロックの中にすべてを入れておくのではなく、ただ一つのtry/catchとusingステートメントを使うだけです。

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

だから、すべては、すべての基本的なデータベースクエリ機能では、次のようになります:

は、この方法はまた、/ else文と、次のグローバル変数があれば、あなたは大きなを取り除くことができることを意味し、それをやってフォームクラスで次に

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); 

} 
+0

このコードは私の問題を解決する助けをしてくれてありがとう私のコードを整理する作業をしています。 –

関連する問題