2017-11-26 8 views
0

Helllo, mySQL 데이터베이스가 있는데 SQL select 쿼리를 통해 정보를 가져 와서이 정보를 DataGride보기에 표시하려고합니다. 이미 데이터베이스 클래스를 작성했습니다.mysql 데이터베이스에서 datagridview 채우기 C#

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.connectionproperty가 초기화되지 않았습니다. " –

+0

데이터베이스"헬퍼 "클래스를 만드는 것은 유감입니다. [ask]를 읽고 [둘러보기] – Plutonix

답변

0

별도의 기능과 별도의 try/catch 블록 안에 모든 것을 넣는 대신 하나의 try/catch를 사용하고 명령문을 사용하면됩니다. 모든 기본 데이터베이스 쿼리 기능에 따라서

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

이 코드가 내 문제를 해결하는 데 도움을 주셔서 감사합니다. 나는 지금 코드를 정리하고있다. –