Reputation: 9081
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.
Upvotes: 0
Views: 146
Reputation: 147
please enclose your string values in single quotes like below
New SqlCommand("insert into Type(TypeName,TypeOrder,CategoryID) values ('" + txtType1.Text + "','" + txtOrder.Text + "','" + ViewState("CatID").ToString() + "')", con)
Upvotes: 0
Reputation: 94653
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)";
Upvotes: 3
Reputation: 3010
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.
Upvotes: 1