SqlCommand insertion query

I have to execute a query of insertion in my c# code

connexion = new SqlConnection(connexionString);
            List<int> liste = client.GetIDFichiers(1210);
            int a = 2;
            foreach (int idfichier in liste)
                using (connexion)
                  using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO REL_Fab3DLotFichier_Fichier3D (IDREL_Fab3DLotFichier_Fichier3D,IDFichier3D,IDFab3DLotFichier,CreePar,CreeLe,ModifiePar,DateMaj,EstActif) VALUES (" + a + "," + idfichier + "," + 17965 + "," + null + "," + null + "," + null + "," + null + "," + 1 + ")", connexion))
                        catch (Exception ex) { MessageBox.Show(ex.ToString()); }



The insertion isn't working and i don't know why. the selection and delete queries worked fine. Only when i try to insert values a syntaxic error appears.

  • what is the syntax error?
  • How can i fix it?


Some of the values you are passing may be string/varchar objects and you aren't wrapping them with quotes:

new SqlCommand("INSERT INTO REL_Fab3DLotFichier_Fichier3D (IDREL_Fab3DLotFichier_Fichier3D,IDFichier3D) VALUES ('" + a + "', '" + idfichier + "')", connexion);

Really, as AVD suggested, you should use parameterisation, which is less prone to injection attacks.

what is the syntax error? and How can i fix it?

Yes. Use parameterized SQL statement.

string sql = "INSERT INTO TableName (Column1,Column2) VALUES (@value1,@value2)";
using(SqlCommand sqlCmd = new SqlCommand(sql,connection))
 sqlCmd.Parameters.Add("@value1",SqlDbType.Varchar,20).Value = varName1;
 sqlCmd.Parameters.Add("@value2",SqlDbType.Varchar,20).Value = DBNull.Value;

Try to include not null fields to prepare INSERT SQL.

sql=@"INSERT INTO REL_Fab3DLotFichier_Fichier3D 

Need Your Help

IIS/Visual Studio Publish Profiles

visual-studio-2012 iis-7.5 visual-studio-2013 publish-profiles

I know IIS allows the creation of Publish Profiles that can be "imported" into Visual Studio in order to upload a site directly into IIS (since I'm already using it).

rails, implementing a master detail yet staying RESTful

ruby-on-rails rest master-detail

Say that I have a Customers and an Orders tables, where each Customer may have many Orders.

Disabling call to function for 5 seconds after triggering

javascript jquery

I have a button that I want to disable from sending anymore calls to jquery while there is a function "active".