连接必须有效并打开c#

时间:2016-06-23 16:24:12

标签: c# mysql

我是C#的新手,但我正在开发一个简单的GUI来管理我的mysql数据库。 我需要保持连接打开直到程序结束(当我关闭它)但点击连接按钮后,我插入一些数据,但程序显示“连接必须有效并打开”。你能帮帮我吗?

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 = "";
        }

    }
}

1 个答案:

答案 0 :(得分:0)

你只是在调用GetConn();点击按钮。

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

建立新连接并不会打开它。 将conn.Open()添加到GetConn();功能,然后在需要时只需conn.Close()