在c#和SQL Server中插入按钮

本文关键字:插入 按钮 Server SQL | 更新日期: 2023-09-27 18:04:54

我试图修复插入按钮的代码。它是一个将数据插入数据库的按钮。

下面是我的代码:
 private void button2_Click(object sender, EventArgs e)
 {
        SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;
        sqlCon.Open();
        // string requete = "INSERT INTO [RECAP] VALUES ('" + textBox1.Text + "''" + textBox2.Text + "''" + comboBox2.SelectedValue + "''" + comboBox3.SelectedValue + "''" + textBox5.Text + "''" + textBox6.Text + "''" + Global.Global.GolbVar + "''" + DateTime.Now.ToShortDateString() + "');";
        string requete = "INSERT INTO dbo.RECAP(code_reseau, tot_dcl, mont_debou, gch_dep, typ_port, mois, annee, emt_dep, utilisateur, date_maj) VALUES ('" + textBox1.Text + "', " + textBox5.Text + "," + textBox6.Text + "," + comboBox2.SelectedValue + "," + comboBox3.SelectedValue + "," +0+ "," +0+ "," +0+ "," + 0 + "," + 0 + ")";
        cmd = new SqlCommand(requete, sqlCon);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Ajouté !");
        sqlCon.Close();
}

每次我尝试运行这个,它都会生成一个异常,说

','附近语法错误

在c#和SQL Server中插入按钮

尝试替换

string requete = "INSERT INTO dbo.RECAP(code_reseau,tot_dcl,mont_debou,gch_dep,typ_port,mois, annee, emt_dep,utilisateur,date_maj) VALUES ('" + textBox1.Text + "', " + textBox5.Text + "," + textBox6.Text + "," + comboBox2.SelectedValue + "," + comboBox3.SelectedValue + "," +0+ "," +0+ "," +0+ "," + 0 + "," + 0 + ")";

SqlCommand com = new SqlCommand("INSERT INTO RECAP (code_reseau, tot_dcl, mont_debou, gch_dep, typ_port,mois, annee, emt_dep, utilisateur, date_maj) VALUES(@txt1, @txt5, @txt6, ,@combo2, @combo3, 0, 0, 0, 0, 0)", sqlCon);
            com.Parameters.AddWithValue("@txt1", textBox1.Text);
            com.Parameters.AddWithValue("@txt5", textBox5.Text);
            com.Parameters.AddWithValue("@txt6", textBox6.Text);
            com.Parameters.AddWithValue("@combo2", comboBox2.SelectedValue);
            com.Parameters.AddWithValue("@combo3", comboBox3.SelectedValue);

,看看是否可以

检查下面

  • textBox5。文本
  • textBox6。文本
  • comboBox2。SelectedValue
  • comboBox3。SelectedValue

都是数字类型。

因为它们不是用单引号传递的,所以它们的值应该转换为数字(并且各自的列也属于该类型),或者它们会导致错误,因为一些文本插入SQL语句中而没有任何引号。