SqlCommand INSERT 查询不向数据库插入数据

SqlCommand INSERT query does not insert data into the database

我正在研究 Visual Studio 2013

在下面的代码中 MessageBox.Show("Connected to database") 显示正确,但是 SQL 查询没有将数据插入数据库 table。

当我手动插入数据时,它插入没有任何问题。但不幸的是,数据无法插入 button_click 命令。

private void DataAdd_Load(object sender, EventArgs e)
{
    try
    {
        conn = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Pathname;Integrated Security=True;Connect Timeout=30");
        conn.Open();
        MessageBox.Show("Connected to database");
        cmd = new SqlCommand("INSERT INTO datains (name, dob, gender, occupation, height, weight, relation, polexpo) values('abc', '22-Aug-2001', 'Male', 'qwe2', '23', '431', 'qw23e', 'asqwed');", conn);
    }
    catch (Exception e1)
    {
        MessageBox.Show("Connection failed");
    }
}

我在这里做错了什么或者我错过了什么?

您忘记执行查询:

cmd.ExecuteNonQuery();

工作完成后最好关闭连接:

conn.Close();

您必须 运行 您的 cmd 的 ExecuteNonQuery() 方法才能使其工作,但也建议将连接和命令都包装到一个 using 语句中,以便它们将被处理(连接应该也明确关闭)