不确定如何初始化数据库连接

Not sure how to initialise the database connection

我正在尝试插入名为“问题”的 SQL 数据库 table,每当我单击该按钮时,就会出现以下错误,我不确定如何解决这个问题,因为我以为我只需要打开数据库连接然后关闭它?

任何帮助都会很有帮助。

 private void button1_Click(object sender, EventArgs e)
    {


        string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
        SqlConnection connect = new SqlConnection(connectionString);
        connect.Open();

        SqlCommand command1 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (1)");
        command1.ExecuteNonQuery();

        connect.Close();

    }

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

Additional information: ExecuteNonQuery: Connection property has not been initialized.

错误信息明确;

您没有连接 SqlCommandSqlConnection。使用您的连接作为命令中的第二个参数,例如;

SqlCommand command1 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (1)",
                                      connect);

或者您可以使用 CreateCommand when you create your SqlCommand based on your connection. Also use using statement 自动处理您的连接和命令,而不是手动调用 .Close() 方法。

最好的方法;

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
    using(var connect = new SqlConnection(connectionString))
    using(var command1 = connect.CreateCommand())
    {
         command1.CommandText = "INSERT INTO Questions ([Question Type]) VALUES (1)";
         connect.Open();
         command1.ExecuteNonQuery();
    }
}