2016-06-23 11 views
-2

私はC#の新機能ですが、私はmysqlデータベースを管理するための簡単なGUIを開発しています。 プログラムの最後まで接続を開いたままにする必要がありますが(接続を閉じると)、接続ボタンをクリックした後にデータが挿入されますが、プログラムは「接続が有効で開いている必要があります。私たちを手伝ってくれますか?接続は有効でオープンしている必要があります。C#

namespace MysqlConn 
{ 
    public partial class Form1 : Form 
    { 
     private static MySqlConnection conn; 
     MySqlCommand mcd; 

     private void button1_Click(object sender, EventArgs e) 
     { 
      GetConn();   
     } 

     public static MySqlConnection GetConn() 
     { 
      conn = new MySqlConnection("datasource=localhost;port=3306;username='+UserName'; password= '+PassWord'"); 
      MessageBox.Show("OK.."); 
      return conn; 
     } 

     public Form1() 
     { 
      InitializeComponent(); 
      String DataBase = textBoxDb.Text; 
      String UserName = textBoxUserName.Text; 
      String PassWord = textBoxPassword.Text; 

     } 

     public void openCon() 
     { 
      if (conn.State == ConnectionState.Closed) 
      { 
       conn.Open(); 
      } 
     } 

     public void closedConn() 
     { 
      if (conn.State == ConnectionState.Open) 
      { 
       conn.Close(); 
      } 
     } 

     public void executeQuery(String s) 
     { 
      try 
      { 

       mcd = new MySqlCommand(s, conn); 
       if (mcd.ExecuteNonQuery() == 1) 
       { 
        MessageBox.Show("Query executed"); 
       } 
       else 
       { 
        MessageBox.Show("Query not executed"); 
       } 

      } catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } finally 
      { 

      } 
     } 

     private void buttonInsert_Click_1(object sender, EventArgs e) 
     { 
      string s = "insert into prova_csharp.users (Name, Surname, Age) values ('"+textBoxName.Text+"', '"+textBoxSurname.Text+"', '"+textBoxAge.Text+"')"; 
      executeQuery(s); 
     } 

     private void buttonUpdate_Click(object sender, EventArgs e) 
     { 
      string s = "update prova_csharp.users set Name='" + textBoxName.Text + "', Surname='" + textBoxSurname.Text + "', Age=" + textBoxAge.Text + " where Id=" + textBoxId.Text; 
      executeQuery(s); 
     } 

     private void buttonDelete_Click(object sender, EventArgs e) 
     { 
      string s = "delete from prova_csharp.users where Id = " + textBoxId.Text; 
      executeQuery(s); 
      textBoxId.Text = ""; 
     } 

    } 
} 
+0

あなたが接続を開いている唯一の場所は 'openCon()'の中にあり、決して呼び出されません。 – pay

+0

エラーはかなり自明です。私はあなたが実際に 'openCon'を呼び出したり、そうでなければ' conn.Open'を呼び出すところがないので、接続が開いていないことをお勧めします。 –

+2

また、パラメータ化されたクエリを使用してください。これらは、古典的なSQLインジェクションであり、そのようなインサートにユーザー入力(テキストボックス)を使用します。それを終えたら、そのコネクションにDisposeを呼び出します。 – Nikki9696

答えて

0

GetConn()を呼び出しているだけです。ボタンをクリックします。

conn = new MySqlConnection("datasource=localhost;port=3306;username='+UserName'; password= '+PassWord'"); 
    MessageBox.Show("OK.."); 
    return conn; 

新しい接続を確立しても開けません。 conn.Open()をGetConn()に追加します。必要に応じてconn.Close()と入力します。

+0

おかげで、あなたの助けが基本でした! – alex

関連する問題