SqlCommand insertion query

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

connexion = new SqlConnection(connexionString);
             connexion.Open();
            List<int> liste = client.GetIDFichiers(1210);
            int a = 2;
            foreach (int idfichier in liste)
            {
                a++;
                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))
                    {
                        try
                        {
                            sqlCmd.ExecuteNonQuery();
                        }
                        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?

Answers


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 
                (IDREL_Fab3DLotFichier_Fichier3D,
                 IDFichier3D,
                 IDFab3DLotFichier,
                 DateMaj,EstActif) 
     VALUES 
                (@IDREL_Fab3DLotFichier_Fichier3D,
                 @IDFichier3D,
                 @IDFab3DLotFichier,
                 @DateMaj,@EstActif)";

Need Your Help

XML Processing in Python

python xml

I'm about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.