WinForms:连接必须有效且打开

WinForms: Connection must be valid and open

表单上有一个DataGridView元素,其中有一个相连的SQLtable。在表单上还有几个用于输入数据的元素和一个按钮,单击时,应提前执行添加数据的过程directly.Thanks。这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace Курсовая.Приложение
{
    public partial class ProfileForm : Form
    {
        public ProfileForm()
        {
            InitializeComponent();
        }
        private void ProfileForm_Load(object sender, EventArgs e)
        {
            TouristGridView.DataSource = GetTouristList();
        }
        private DataTable dtTourist = new DataTable();
        private DataTable GetTouristList()
        {
            string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(connString))
            {
                using (MySqlCommand cmd = new MySqlCommand("SELECT FIO, dob, phone FROM tourist", con))
                {
                    con.Open();
                    MySqlDataReader reader = cmd.ExecuteReader();
                    dtTourist.Load(reader);
                }
            }
            return dtTourist;
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(connString))
            {
                con.Open();
                MySqlCommand Command = new MySqlCommand("INSERT INTO [tourist] ([FIO], [dob], [phone]) VALUES ('" + NametextBox.Text + "','" + dobDate.Value + "','" + PhonetextBox.Text + "')");
                Command.ExecuteNonQuery();
            }
        }
    }
}

当你实例化你的 MySqlConnection 时,你必须像这样传递打开的连接对象:

private void button1_Click_1(object sender, EventArgs e)
        {
            string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(connString))
            {
                con.Open();
                MySqlCommand Command = new MySqlCommand("INSERT INTO [tourist] ([FIO], [dob], [phone]) VALUES ('" + NametextBox.Text + "','" + dobDate.Value + "','" + PhonetextBox.Text + "')", con);
                Command.ExecuteNonQuery();
            }
        }