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

时间:2015-04-18 16:10:20

标签: c# button database-connection sql-insert

我正在尝试插入名为Questions的SQL数据库表,每当我点击按钮时出现下面的错误,我不知道如何解决这个问题,因为我以为我只需要打开数据库连接然后之后关闭它?

任何帮助都会非常有帮助。

 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();

    }
  

System.Data.dll中出现未处理的“System.InvalidOperationException”类型异常

     

其他信息:ExecuteNonQuery:尚未初始化Connection属性。

1 个答案:

答案 0 :(得分:2)

错误消息已清除;

您没有关联SqlCommandSqlConnection。将您的连接用作命令中的第二个参数,如;

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

或者,根据您的连接创建SqlCommand时,您可以使用CreateCommand。也可以使用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();
    }
}