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.
Related
I want to connect a Windows Form app with SQL Server and insert values from the app textboxes to a database. When the button is clicked, I receive an error:
Incorrect syntax near the keyword "Group".
What is the problem? How can I insert this data?
private void button1_Click(object sender, EventArgs e)
{
try
{
string myconnection = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=StudBase;Integrated Security=True";
string Query = "Insert Into StudentInfo (StudentID, Name,Surname,Group,Course,City,Sector,Average rating) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";
SqlConnection Myconn = new SqlConnection(myconnection);
SqlCommand Mycom = new SqlCommand(Query, Myconn);
SqlDataReader Reader1;
Myconn.Open();
Reader1 = Mycom.ExecuteReader();
MessageBox.Show("Save data");
while (Reader1.Read())
{
}
Myconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Use this for your query statement -
string Query = "Insert Into StudentInfo (StudentID,[Name],Surname,[Group],Course,City,Sector,[Average rating]) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";
Use [] for reserved keywords in SQL. Also the last column Average rating was not covered with [], as this column name has space then it should be quoted in [].
here is the story :
Im trying to insert some data form the form to my data base but some thing wrong with the syntax "Vs Say so" but i can't find the mistake and some one help ?
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=ltdb;UID=root;Password=1234;port=3306");
try
{
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
conn.Open();
MySqlCommand cmd = new MySqlCommand(command, conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Saved !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
INSERT INTO invoice companyName, ... missing opening brace, correct is
INSERT INTO invoice(column1, column2, ...) VALUES (#Columns1, #columns2, ...)
Coming to point 2: you're open for sql-injection. Use parameterized queries.
Change your
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
To
string command = "INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES (#name,#rate,#vatno,#tinno,#adline1,#adline2,#city)";
command.Parameters.AddWithValue("name",txtname.Text);
command.Parameters.AddWithValue("rate",txtrate.Text);
....
*Edit: For more info, google "c# parameterized sql"
You put Wrong bracket
INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES ('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');
I'm inserting some data to tables one by one. I've two tables adjustment_header and adjustment_grid.
First I'll insert data to adjustment_header table then I'll insert data to adjustment_grid table. If adjustment insertion fails, previously inserted data in adjustment_header table should be delete automatically.
Is there any query for this kind of problem?
SqlCommand sqlcmd1 = new SqlCommand("INSERT INTO adjustment_header values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"','"+TextBox4.Text+"')",conn);
conn.Open();
sqlcmd1.ExecuteNonQuery();
conn.Close();
//adjustment grid row 1
if (itemno1.SelectedItem.Text != "please select")
{
SqlCommand cmd1 = new SqlCommand("INSERT INTO adjustment_grid values('"+TextBox1.Text+"','" + itemno1.SelectedItem.Text + "','" + adj1.SelectedItem.Text + "','" + store1.SelectedItem.Text + "','" + qty1.Text + "','" + cost1.Text + "')", conn);
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
}
//adjustment grid row 2
if (itemno2.SelectedItem.Text != "please select")
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno2.SelectedItem.Text + "','" + adj2.SelectedItem.Text + "','" + store2.SelectedItem.Text + "','" + qty2.Text + "','" + cost2.Text + "')", conn);
conn.Open();
cmd2.ExecuteNonQuery();
conn.Close();
}
//adjustment grid row 3
if (itemno3.SelectedItem.Text != "please select")
{
SqlCommand cmd3 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno3.SelectedItem.Text + "','" + adj3.SelectedItem.Text + "','" + store3.SelectedItem.Text + "','" + qty3.Text + "','" + cost3.Text + "')", conn);
conn.Open();
cmd3.ExecuteNonQuery();
conn.Close();
}
In this code first I'm inserting data into adjustment_header table then I'm inserting into adjustment_grid table 3 times, in 3 transactions in adjustment_grid table any of one fails previously inserted data should be delete automatically.
Wrap the entire block in a SqlTransaction, and don't open/close your connection for each statement:
conn.Open();
using(SqlTransaction tran = conn.BeginTransaction("Adjustment"))
{
SqlCommand sqlcmd1 = new SqlCommand("INSERT INTO adjustment_header values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"','"+TextBox4.Text+"')",conn, tran);
sqlcmd1.ExecuteNonQuery();
//adjustment grid row 1
if (itemno1.SelectedItem.Text != "please select")
{
SqlCommand cmd1 = new SqlCommand("INSERT INTO adjustment_grid values('"+TextBox1.Text+"','" + itemno1.SelectedItem.Text + "','" + adj1.SelectedItem.Text + "','" + store1.SelectedItem.Text + "','" + qty1.Text + "','" + cost1.Text + "')", conn, tran);
cmd1.ExecuteNonQuery();
}
//adjustment grid row 2
if (itemno2.SelectedItem.Text != "please select")
{
SqlCommand cmd2 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno2.SelectedItem.Text + "','" + adj2.SelectedItem.Text + "','" + store2.SelectedItem.Text + "','" + qty2.Text + "','" + cost2.Text + "')", conn, tran);
cmd2.ExecuteNonQuery();
}
//adjustment grid row 3
if (itemno3.SelectedItem.Text != "please select")
{
SqlCommand cmd3 = new SqlCommand("INSERT INTO adjustment_grid values('" + TextBox1.Text + "','" + itemno3.SelectedItem.Text + "','" + adj3.SelectedItem.Text + "','" + store3.SelectedItem.Text + "','" + qty3.Text + "','" + cost3.Text + "')", conn, tran);
cmd3.ExecuteNonQuery();
}
tran.Commit();
}
You should also use parameters instead of string concatenation, but that's a separate issue...
I would ALSO not reference your controls directly. Put this type of logic in a separate class in a function that has parameters for the various options. That way you can decouple it from the UI and reuse it later if necessary.
I have tried as much to insert into an oracle database. but i found nothing in the database when i queried it. yet it returns no of isertions made into the database on every executenonquery.please find my code below
queryString = "INSERT INTO btable (CH_CODE, ME_NUM, CY_CODE, ER_CODE, SUB_CODE, _LIM, LIM__DATE)" +
" VALUES ('" + int.Parse(rows["ch_code"].ToString()) + "','" + int.Parse(rows["me_numb"].ToString()) + "','" + int.Parse(rows["cy_code"].ToString()) + "','" + int.Parse(rows["er_code"].ToString()) + "','" + int.Parse(rows["Sub_code"].ToString()) + "','" + double.Parse(rows["_limit"].ToString()) + "'," + "to_date('" + usedate +"','dd/mm/yyyy')" + "')";
command = new OracleCommand(queryString, conn);
command.Connection = conn;
if (command.Connection.State == ConnectionState.Closed)
{
command.Connection.Open();
}
//command.Connection.Open();
command.ExecuteNonQuery();
if (command.ExecuteNonQuery() > 0)
{
intResult++;
}
The connection string is
<add key="OraConnString" value="Data Source=testdr.world;Persist Security Info=False;user id=****;password=****"></add>
It was called in the program as
OracleConnection conn = new OracleConnection(ConfigurationManager.AppSettings["OraConnString"]);
OracleCommand command;
The database is an oracle database
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