SqlCommand insertion query - c#

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?

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)";

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.

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)

Related

Exception Unhandled - MySql.Data.MySqlClient.MySqlException

I was gonna save my date and time record in my database when an unhandled exception always thrown at this code: int value = cmd.ExecuteNonQuery(); when I'm clicking the 'Time In' button.
it says that MySql.Data.MySqlClient.MySqlException 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Mar 2022 3:53:00 AM,System.Windows.Forms.DateTimePicker, Value
When I check my codes, there's no errors. I debugged it but no errors appeared.
Here's my codes:
private void btnTimeIn_Click(object sender, EventArgs e)
{
string connectstring = "datasource=localhost;port=3306;username=root;password=;database=employeedb;SslMode=none";
MySqlConnection conn = new MySqlConnection(connectstring);
conn.Open();
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
MySqlCommand cmd = new MySqlCommand(iQuery, conn);
int value = cmd.ExecuteNonQuery();
MessageBox.Show(value.ToString());
conn.Close();
}
Your immediate help, tips and advice are highly appreciated
I was gonna expect that I'm gonna save records in my database by timing in... but I can't even find what could be wrong because i just did all ways of inserting data into table in database. Still, I didn't also work, and the exception still throwing every time at the 'cmd.ExecuteNonQuery' line.
This line of code is causing the bug, and can also lead to SQL injection:
string iQuery = "INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`, `RecordDate`, `TimeIn`, `TimeOut`) VALUES (" + txtEmployeeID.Text + "," + txtLstName.Text + "," + txtFirstName.Text + "," + dateTimePicker1.Value + "," + dateTimePicker2 + "," + dateTimePicker3 + ")";
You should always use command parameters, not string concatenation:
using (MySqlConnection conn = new MySqlConnection(connectstring))
{
conn.Open();
string iQuery = #"
INSERT INTO `attendancerecord`(`EmployeeID`, `EmplLastName`, `EmplFirstName`,
`RecordDate`, `TimeIn`, `TimeOut`)
VALUES (#id, #last, #first, #date, #in, #out);";
using MySqlCommand cmd = new MySqlCommand(iQuery, conn))
{
cmd.Parameters.AddWithValue("#id", txtEmployeeID.Text);
cmd.Parameters.AddWithValue("#first", txtLstName.Text);
cmd.Parameters.AddWithValue("#last", txtFirstName.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#in", dateTimePicker2.Value);
cmd.Parameters.AddWithValue("#out", dateTimePicker3.Value);
int value = cmd.ExecuteNonQuery();
}
}
Additionally, use using statements to automatically close and clean up database resources.

Postgresql Npgsql.PostgresException in c#

I have a problem with cmd.ExecuteReader() i get a Npgsql.PostgresException
public void connectDB()
{
try
{
server = "localhost";
database = "DoveVer3";
uid = "admin";
password = "admin";
string connectionString;
connectionString = "Host=" + server + ";Username =" + uid + ";" + "PASSWORD=" + password + ";DATABASE=" + database;
connection.ConnectionString = connectionString;
connection.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
I get the Exeption in the code below:
public void AddDoveToDB(Dove dove)
{
//add new dove record to tableDB
connectDB();
cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM " + DoveTableDB + " WHERE `" + DoveIdColumnDoveTable + "` = '" + dove.GetDoveId() + "'";
NpgsqlDataReader rdr = cmd.ExecuteReader(); //// <<<<< HERE
if (rdr.Read() != true)
{
rdr.Close();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO " + DoveTableDB + "(" + DoveIdColumnDoveTable + "," + DoveIdFatherColumnDoveTable + "," + DoveIdMotherColumnDoveTable + "," + DoveEyesColorColumnDoveTable + "," + DoveFeatherColorDoveTable + "," + DoveImageNameColumnDoveTable + "," + DoveSexColumnDoveTable +") VALUES ('" + dove.GetDoveId() + "','" + dove.GetDoveFatherId() + "','" + dove.GetDoveMotherId() + "','" + dove.GetEyesColor() + "','" + dove.GetFeathersColor()+ "','" + dove.GetImageName() + "','" + dove.GetSex()+ "')";
cmd.ExecuteNonQuery();
}
connection.Close();
}
My database is called DoveVer3 and my schema DoveSchema here is my table code:
Name: DoveTable; Type: TABLE; Schema: DoveSchema; Owner: admin
--
CREATE TABLE "DoveTable" (
"doveId" character varying(20)[] NOT NULL,
"doveFather" character varying(20)[],
"doveMother" character varying,
"doveEyesColor" character varying(20)[],
"doveFeathersColor" character varying(20)[],
"doveSex" smallint DEFAULT 3 NOT NULL,
"imageName" character varying(30)
);
ALTER TABLE "DoveTable" OWNER TO admin;
The Exceptions Base messege:
relation "dovetable" don't exist; Statemants: {SELECT * FROM DoveTable
WHERE doveId = 'Test'}
By default all identifiers passed to PostgreSQL will be considered lower-case. Based on your creation script you used a quoted-identifer when defining your table so the following is required when using the name of your table.
SELECT * FROM "DoveTable"
Notice that it is wrapped in double quotes and the 'D' and 'T' are both capitalized. When using quoted-identifiers you must always write them out exactly the way you defined them.

Insert record(s) DB from Form

I have an Access DB connected to my form with that code ( C# ) :
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb";
try
{
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
// MessageBox.Show("Connessione Fallita!");
conn.Close();
}
finally
{
conn.Close();
}
The error I get when i click the buttton is this one :
Any ideas?
You are missing single quotations in Insert Statement where you are assigning values to columns. Your code is vulnerable so should avoid this here is a useful link.
Are Parameters really enough to prevent Sql injections?
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB \DataMG.mdb";
try
{
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT into Prodotti (Codice,Descrizione,Marchio,Deposito,Note,NumeroProdotti,PrzListinoBase_Aq,PrzListinoBase_Ve,Categoria,Posizione,Disponibilita,QtaVenduta,QtaAcquistata) VALUES('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "','" + this.Note.Text + "','" + this.NumProd.Text + "','" + this.PrzListAcq.Text + "','" + this.PrzListVen.Text + "','" + this.Categ.Text + "','" + this.Posiz.Text + "','" + this.Disp.Text + "','" + this.QtaVen.Text + "','" + this.QtaAcq.Text + "')";
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
// MessageBox.Show("Connessione Fallita!");
conn.Close();
}
finally
{
conn.Close();
}
I don't know italian (is that even the language? :) ) but from the look of it it could very well be a culture settings problem. If, for example, one of your fields is numeric then the database might expect a different decimal separator than the one in use in your UI.
Also your actual design seems very vulnerable to SQL Injection Attacks.
For these reasons, my suggestion is that you use the command's Parameters collection to set your values rather than trying to pass in a concatenated string.
I don't read the language you are posting the error from, however, it looks like a syntax error somewhere in your SqlCommand.
First thing I would suggest is wrapping your connection and command in using blocks to make sure they get disposed of correctly.
Then ALWAYS user parametarized SQL Commands to avoid SQL Injection:
using (var conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb"))
using (var cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.CommandText = "INSERT INTO TableName (column1, column2, column3) VALUES (#Value1, #Value2, #Value3)";
cmd.Parameters.AddWithValue("#Value1", this.TextBox1.Text);
cmd.Parameters.AddWithValue("#Value2", this.TextBox2.Text);
cmd.Parameters.AddWithValue("#Value3", this.TextBox3.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
Generally speaking, using parameters eliminates syntax errors because it makes the command much easier to read in it's string representation.
I think you may be missing single quotes around some of your text qualifiers in your INSERT statement.
"INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
Consider using a parameterized query rather than building your query string by hand. Not only is it safer, but it can help to weed out these kinds of errors which can be tedious to debug.
eg.
String StrSQL = "INSERT INTO tblLog ([Part_Number],[Quantity],[Date],[LOC_Warehouse],[LOC_Row],[LOC_Section],[LOC_Level],[LOC_Bin],[Stock_Added],[Stock_Removed],[Quarantine_Set],[Quarantine_Removed])"
+ "VALUES(#Part_Number, #Quantity, #Date, #Warehouse, #Row, #Section, #Level, #Bin, #Stock_Added, #Stock_Removed, #Quarantine_Set, #Quarantine_Removed)";
SqlConnection conn = new SqlConnection(WHITS.Properties.Settings.Default.LocalConnStr);
SqlCommand cmd = new SqlCommand(StrSQL, conn);
cmd.Parameters.AddWithValue("#Part_Number", Part_Number);
cmd.Parameters.AddWithValue("#Quantity", Quantity);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
//More Parameters... Skipped for brevity.
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Open your connection earlier. Also, use "using". Here's how I would do it:
try
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString))
{
conn.Open();
string insertQuery = "INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(insertQuery, conn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
}
}
Edit: My bad... the code I was referencing was filling a DataAdapter, which doesn't require a call to connection.Open(). Regular querying does. My apologies... I have edited my suggestion.

Syntax Error on a Sql Parametrized update command - c#

It's my first SQL Parametrized update command in c# and i have a syntax error when i exectued my update.
Here is my code :
string maRequete = "UPDATE " + strNomTable + " set "
+ "evetype = #evetype ,"
+ "evedes = #evedes ,"
+ "evecli = #evecli ,"
+ "eveusermo = #eveusermo ,"
+ "eveinterv = #eveinterv where eveNum = " + '"' + strEvtNumeroString.ToString() + '"';
OleDbCommand DbCommand = new OleDbCommand(maRequete);
DbCommand.Parameters.Add("#evetype", OleDbType.VarChar);
DbCommand.Parameters.Add("#evedes", OleDbType.VarChar);
DbCommand.Parameters.Add("#evecli", OleDbType.VarChar);
DbCommand.Parameters.Add("#eveusermo", OleDbType.VarChar);
DbCommand.Parameters.Add("#eveinterv", OleDbType.VarChar);
DbCommand.Parameters["#evetype"].Value = m_strEvtType.ToString().Trim();
DbCommand.Parameters["#evedes"].Value = m_strDesignation.ToString().Trim();
DbCommand.Parameters["#evecli"].Value = m_strCodeClient.ToString().Trim();
DbCommand.Parameters["#eveusermo"].Value = m_strUserModification;
DbCommand.Parameters["#eveinterv"].Value = m_strCodeIntervenant.ToString().Trim();
try
{
string strStringConnect = #"Provider=vfpoledb.1;Data Source=" + m_strDirectoryDBF + "\\" + strDbfFile + ".dbf;Collating Sequence=general";
OleDbConnection DbConnection = new OleDbConnection(strStringConnect);
DbCommand.CommandType = System.Data.CommandType.Text;
DbConnection.Open();
DbCommand.Connection = DbConnection;
DbCommand.ExecuteNonQuery();
return "O";
}
catch (Exception Ex)
{
return Ex.Message;
}
Anyone have an idea where is my mistake ? In addition, i wrote in a old DBF file (Visual Foxpro) and i think i don't have access to log in order to debug the query :(.
Thanks a lot :)
Best regards,
Nixeus
Try using single quotes in your UPDATE statement instead of double quotes. The last line
+ "eveinterv = #eveinterv where eveNum = " + '"' + strEvtNumeroString.ToString() + '"';
should be
+ "eveinterv = #eveinterv where eveNum = '" + strEvtNumeroString.ToString() + "'";
change your command text as
string maRequete = "UPDATE " + strNomTable + " set "
+ "evetype = #evetype ,"
+ "evedes = #evedes ,"
+ "evecli = #evecli ,"
+ "eveusermo = #eveusermo ,"
+ "eveinterv = #eveinterv where eveNum = '" + strEvtNumeroString.ToString() + "'";
If you print out maRequete, and try executing it interactively, you will find the SQL syntax is incorrect. It seems likely you're using double-quotes to denote string constants; in SQL you should use single quotes for that. It's possible your data contains a single quote (i.e. an apostrophe). In that case, you need to add and extra one e.g.
INSERT ... values ('you''ll need two apostrophes for this');
These are just SQL rules. You have to give the server valid syntax if it's to execute your query.

i'm trying to insert to the data base but i have an error called overflow

this is the code
public static void ChangeTable(string strSql, string FileName)
{
OleDbConnection c = MakeConnection(FileName);
OleDbCommand comm = new OleDbCommand();
comm.CommandText = strSql;
comm.Connection = c;
comm.ExecuteNonQuery();
c.Close();
}
strSql = "Insert into h3rot(name,lastname,tlfon,nyad,email,brodcuts)" +
" VALUES(
'
" +
TextBox1.Text +
"','" +
TextBox2.Text +
"'," +
phone +
"," +
pel +
",'" +
TextBox5.Text +
"','" +
DropDownList1.Text + "
')";
1) your code is SCREAMING out "sql injection" so you should REALLY be doing something to sanitize all of those textboxes. And you should at least be using parameter markers instead of just appending strings together.
2) you've probably exceeded the size of one of the columns in your database. without more information about what was in the textboxes or the schema of the database, there's not much else to say.
try DropDownList1.SelectedValue

Categories

Resources