ExecuteNonQuery无法在C#中工作

时间:2013-06-03 18:29:49

标签: c# sql-server executenonquery

我正在使用Visual Studio 2008 c#构建数据库,当我尝试在我的数据库中插入新记录时,似乎ExecuteNonQuery尚未初始化。我复制我的代码,希望任何人都可以帮助我,因为我是新人。

 private void button1_Click(object sender, EventArgs e)
 {
     SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True");
     SqlCommand cmd = new SqlCommand();
     cn.Open();
     cmd.CommandText = "insert into Database1.mdf(Codigo,Nombre,Cantidad,Tipo) values('"+comboBox1.Text+"','"+textBox3.Text+"','"+textBox1.Text+"','"+comboBox2.Text+"')";
     cmd.ExecuteNonQuery();
     cmd.Clone();
     cn.Close();
     MessageBox.Show("Acabas de agregar un producto");
 }

3 个答案:

答案 0 :(得分:13)

您尚未设置与命令的连接:

cmd.Connection = cn;

答案 1 :(得分:8)

您的代码中存在许多问题:

  • 首先:insert into statement需要一个目标数据表,而不是名称 MDF文件
  • 第二:使用using statement关闭并处理连接
  • 第三:Parametrized query以避免解析问题和SQL 注射
  • 第四:您需要将连接与命令相关联(很容易 在SqlCommand constructor

    完成
    using(SqlConnection cn = new SqlConnection(.......))
    using(SqlCommand cmd = new SqlCommand("insert into table_name(Codigo,Nombre,Cantidad,Tipo)" + 
                              "values (@cod, @nom,@can,@tipo)", con))
    {
        cn.Open();
        cmd.Parameters.AddWithValue("@cod", comboBox1.Text);
        cmd.Parameters.AddWithValue("@nom", textBox3.Text);
        cmd.Parameters.AddWithValue("@can", textBox1.Text);
        cmd.Parameters.AddWithValue("@tipo", comboBox2.Text);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Acabas de agregar un producto");
    }
    

修改 下面由@RemusRusanu添加的链接提供的信息非常重要。使用AddWithValue虽然方便,但可能会妨碍查询的性能。正确的方法应该是使用具有显式数据类型和参数大小的正确定义的SqlParameter。 作为一个例子

SqlParameter p = new SqlParameter("@cod", SqlDbType.NVarChar, 255).Value = comboBox1.Text;
cmd.Parameters.Add(p);

但是,当然,这需要您检查列的确切数据类型和大小。

答案 2 :(得分:1)

您没有通过连接初始化SqlCommand。此外,您应该使用using将所有内容包含在内。并考虑使用参数化命令来避免SQL注入。

   private void button1_Click(object sender, EventArgs e)
    {
        using (SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Usuario\Documents\Visual Studio 2010\Projects\Nova\Nova\Database1.mdf;Integrated Security=True;User Instance=True"))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "insert into databaseTableName (Codigo,Nombre,Cantidad,Tipo) values (@Codigo, @Nombre, @Cantidad, @Tipo)";
                cmd.Parameters.AddWithValue("@Codigo", comboBox1.Text);
                cmd.Parameters.AddWithValue("@Nombre", textBox3.Text);
                cmd.Parameters.AddWithValue("@Cantidad", textBox1.Text);
                cmd.Parameters.AddWithValue("@Tipo", comboBox2.Text);
                cmd.Connection = cn; //this was where the error originated in the first place.
                cn.Open();
                cmd.ExecuteNonQuery();
                MessageBox.Show("Acabas de agregar un producto");
            }
        }
    }