C# database application using Ms access 2010 - c#

I am developing a database application on C# using MS Access for my perfume shop, i have created a table in ms access, named as "MIX", having columns (Brand name,Stock quantity,Retail price,Original price). I want to add their field through C# window form that i have created.
I am trying the following query for inserting my data but all the time i am getting an error "Syntax error in INSERT INTO statement"
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string str = string.Format("Insert into MIX([Brand name],Stock quantity,Retail price,Original price)Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + ")");
OleDbCommand cmd = new OleDbCommand(str,con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfull");
cmd.Dispose();
}

Four things:
You don't need string.Format when you're just concatenating values
Column names with spaces must be surrounded by square brackets:
string str = "Insert into MIX " +
"([Brand name],[Stock quantity],[Retail price],[Original price]) " +
"Values('" + textBox1.Text + "'," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + ")";
You should learn how to use Parameters instead of concatenating SQL:
string str = "Insert into MIX " +
"([Brand name],[Stock quantity],[Retail price],[Original price]) " +
"Values (?,?,?,?)");
OleDbCommand cmd = new OleDbCommand(str,con);
cmd.Parameters.AddWithValue("brand",textBox1.Text);
... repeat for other values
It appears you're reusing a shared OleDbConnection object. This is not a best practice since connections are pooled in .NET and are cheap to recreate after the first usage, and you don't hae to worry about leaving a connection open throughout the life of your application.

This is a really bad idea since the values are being directly dropped into the query, but the problem you are experiencing is the multi-word column names:
Insert into MIX([Brand name],Stock quantity,Retail price,Original price)
These need to have bracket around them:
Insert into MIX([Brand name],[Stock quantity],[Retail price],[Original price])[

You need to enclose column names that contain spaces insquare brackets []. Also, you need to use parameters instead of concatenating values to the SQL query like that. Google "SQL injection attack" to know the reason why.
Insert into MIX([Brand name],[Stock quantity],[Retail price],[Original price])Values(?,?,?,?)
You replace those ?'s with values this way:
cmd.Parameters.AddWithValue("?", Textbox1.text);
cmd.Parameters.AddWithValue("?", Textbox2.text);
cmd.Parameters.AddWithValue("?", Textbox3.text);
cmd.Parameters.AddWithValue("?", Textbox4.text);
Be aware that the order matters.

Related

Insert into access database Query Error in C#

OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
my_con.Open();
OleDbCommand o_cmd1 = my_con.CreateCommand();
o_cmd1.CommandText = "INSERT INTO Personal_Details(Date,Time,Patient_Name,Contact_Number,Gender,Allergic_To,KCO) VALUES ('" + DateTime.Now.ToString("dd-MM-yyyy") + "','" + DateTime.Now.ToString("h:mm:ss tt") + "','" + txtPatientName.Text + "','" + txtContactNo.Text + "','" + comboBoxGender.Text + "','" + txtAllergic.Text + "','" + txtKCO.Text + "')";
int j = o_cmd1.ExecuteNonQuery();
I am getting the Syntax error in Insert Statement I don't understand what is mistake if any one help me I am really thank full.Thanks in Advance.
Date and Time are typically reserved keywords in many database systems. You should at the very least wrap them with [ ]. More preferably, if you are designing the table, change the field name to something more descriptive. For example if the Date and Time represented a reminder then you could use ReminderDate and ReminderTime so as not to interfere with reserved keywords.
And follow the parameter advice that's already been given.
Use command parameters instead of concatenating strings. Your code is open for SQL Injection attacks or in your specific case the problem may be related with invalid user input. Try to thing about this situation:
What if the txtContactNo.Text returns this string "Peter's contact is +123456" ? How does the SQL query will look then? Pay close attention to ' character.
You should ALWAYS use parametrized SQL queries no matter how good you thing your input validation is. It also has more advantages like query plan caching etc.
So in your case the code must be written like this:
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
using(my_con)
{
my_con.Open();
using(OleDbCommand o_cmd1 = my_con.CreateCommand())
{
o_cmd1.CommandText = #"
INSERT INTO Personal_Details ([Date], [Time], Patient_Name, Contact_Number, Gender, Allergic_To, KCO)
VALUES (#date, #time, #name, #contNo, #gender, #alergic, #kco)";
o_cmd1.Parameters.AddWithValue("#date", DateTime.Now.ToString("dd-MM-yyyy"));
o_cmd1.Parameters.AddWithValue("#time", DateTime.Now.ToString("h:mm:ss tt"));
o_cmd1.Parameters.AddWithValue("#name", txtPatientName.Text);
o_cmd1.Parameters.AddWithValue("#contNo", txtContactNo.Text);
o_cmd1.Parameters.AddWithValue("#gender", comboBoxGender.Text);
o_cmd1.Parameters.AddWithValue("#alergic", txtAllergic.Text);
o_cmd1.Parameters.AddWithValue("#kco", txtKCO.Text);
o_cmd1.ExecuteNonQuery();
}
}
Also make sure that you are properly disposing the connection and the command objects (by using :) the using keyword)
For more info read the docs in MSDN
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx

asp.net inserting data with " ' " causes exception

I am inserting data into a .mdf database through a webpage. When I insert words that contain the apostrophe " ' ", it causes an exception. I tried the escape \' but this inserts the whole " \' ". I don't want to insert these directly into the database table through visual studio because I need the Date.Now time/date to be inserted too (through C#).
Please show me how to insert the " ' " and other like characters. Thanks in advance.
That is because you are inserting the data in a way that you should never use. NEVER, NEVER write an SQL command string using string concatenation. Use parameters instead. ie:
Instead of doing this:
var cmd = new SqlCommand("insert into myTable (FirstName, LastName) values ('" +
txtFirstName.Text + "','" +
txtLastName.Text + "')", connection);
Do it like this:
var cmd = new SqlCommand(#"insert into myTable
(FirstName, LastName)
values (#fName, #lName)", connection);
cmd.Parameters.AddWithValue("#fName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#lName", txtLastName.Text);
You can escape it with double apostrophe '', but you shouldn't use it in SqlCommand text. Always add parameters using SqlCommand.Parameters to avoid sql injection possibility.

Getting SQLException when debugging

I've got a error which I can't understand. When I'm debugging and trying to run a insert statement, its throwing the following exception:
"There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement."
I have looked all over my code, and I can't find the mistake I've made.
This is the query and the surrounding code:
SqlConnection myCon = DBcon.getInstance().conn();
int id = gm.GetID("SELECT ListID from Indkøbsliste");
id++;
Console.WriteLine("LNr: " + listnr);
string streg = GetStregkode(navne);
Console.WriteLine("stregk :" + strege);
string navn = GetVareNavn(strege);
Console.WriteLine("navn :" + navne);
myCon.Open();
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(" + id + "," + listnr + ", '" + strege + "','" + navn + "'," + il.Antal + ", "+il.Pris+")";
Console.WriteLine(il.Antal+" Antal");
Console.WriteLine(il.Pris+" Pris");
Console.WriteLine(id + " ID");
SqlCommand com = new SqlCommand(query, myCon);
com.ExecuteNonQuery();
com.Dispose();
myCon.Close();
First of all check the connection string and confirm the database location and number of columns a table has.
Suggestion : Do not use hardcoded SQL string. Use parameterized sql statements or stored-proc.
Try parameterized way,
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris)
Values (#ListID, #ListeNr, #Stregkode, #Navn, #Antal, #Pris)"
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.Add("#ListID",System.Data.SqlDbType.Int).Value=id;
com.Parameters.Add("#ListeNr",System.Data.SqlDbType.Int).Value=listnr;
com.Parameters.Add("#Stregkode",System.Data.SqlDbType.VarChar).Value=strege ;
com.Parameters.Add("#Navn",System.Data.SqlDbType.VarChar).Value=navn ;
com.Parameters.Add("#Antal",System.Data.SqlDbType.Int).Value=il.Antal;
com.Parameters.Add("#Pris",System.Data.SqlDbType.Int).Value=il.Pris;
com.ExecuteNonQuery();
Please always use parametrized queries. This helps with errors like the one you have, and far more important protects against SQL injection (google the term, or check this blog entry - as an example).
For example, what are the actual values of strege and/or navn. Depending on that it may render your SQL statement syntactically invalid or do something worse.
It (looks like) a little more work in the beginning, but will pay off big time in the end.
Are you using danish culture settings?
In that case if il.Pris is a double or decimal it will be printed using comma, which means that your sql will have an extra comma.
Ie:
INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(33,5566, 'stegkode','somename',4, 99,44)
where 99,44 is the price.
The solution is to use parameters instead of using the values directly in you sql. See some of the other answers already explaining this.

How to solve a syntax error when using this INSERT INTO statement and the .NET OleDb namespace?

I keep getting an error when I attempt to insert values into a Access database.
The error is syntactic, which leads to the following exception:
OleDbException was unhandled Syntax error in INSERT INTO statement.
private OleDbConnection myCon;
public Form1()
{
InitializeComponent();
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\File.mdb");
}
private void insertuser_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
myCon.Open();
cmd.Connection = myCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO User ([UserID], [Forename], [Surname], " +
"[DateOfBirth], [TargetWeight], [TargetCalories], [Height]) " +
"VALUES ('" + userid.Text.ToString() + "' , '" +
fname.Text.ToString() + "' , '" +
sname.Text.ToString() + "' , '" +
dob.Text.ToString() + "' , '" +
tarweight.Text.ToString() + "' , '" +
tarcal.Text.ToString() + "' , '" +
height.Text.ToString() + "')";
cmd.ExecuteNonQuery();
myCon.Close();
}
Well, you haven't specified what the error is - but your first problem is that you're inserting the data directly into the SQL statement. Don't do that. You're inviting SQL injection attacks.
Use a parameterized SQL statement instead. Once you've done that, if you still have problems, edit this question with the new code and say what the error is. The new code is likely to be clearer already, as there won't be a huge concatenation involved, easily hiding something like a mismatched bracket.
EDIT: As mentioned in comments, Jet/ACE is vulnerable to fewer types of SQL injection attack, as it doesn't permit DML. For this INSERT statement there may actually be no vulnerability - but for a SELECT with a WHERE clause written in a similar way, user input could circumvent some of the protections of the WHERE clause. I would strongly advise you to use parameterized queries as a matter of course:
They mean you don't have to escape user data
They keep the data separate from the code
You'll have less to worry about if you ever move from Jet/ACE (whether moving this particular code, or just you personally starting to work on different databases)
For other data types such as dates, you don't need to do any work to get the data into a form appropriate for the database
(You also don't need all the calls to ToString. Not only would I expect that a property called Text is already a string, but the fact that you're using string concatenation means that string conversions will happen automatically anyway.)
I posted this as a comment to the duplicate question at: Syntax error in INSERT INTO statement in c# OleDb Exception cant spot the error
Put brackets [] around the table name
"User". It's a reserved word in SQL
Server.
"User" is also a reserved word in Access (judging by the provider in your connection string).
But I completely agree with Jon--if you fix your current implementation, you are just opening up a big security hole (against your User table, no less!)
This problem may occur if your database table contains column names that use Microsoft Jet 4.0 reserved words.
Change the column names in your database table so that you do not use Jet 4.0 reserved words.
If TargetWeight, Height, and TargetCalories are floating-point or integer values, they don't need to be surrounded by quotes in the SQL statement.
Also, not directly related to your question, but you should really consider using a parameterized query. Your code is very vulnerable to SQL injection.
public decimal codes(string subs)
{
decimal a = 0;
con_4code();
query = "select SUBJINTN.[SCODE] from SUBJINTN where SUBJINTN.[ABBR] = '" + subs.ToString() + "'";
cmd1 = new OleDbCommand(query, concode);
OleDbDataReader dr = cmd1.ExecuteReader();
here is error in dr it says syntax error ehile in DBMS its working Well
if (dr.Read())
{
a = dr.GetDecimal(0);
MessageBox.Show(a.ToString());
}
return a;
}
After this
cmd.CommandText="INSERT INTO User ([UserID], [Forename], [Surname], [DateOfBirth], [TargetWeight], [TargetCalories], [Height]) Values ('" + userid.Text.ToString() + "' , '" + fname.Text.ToString() + "' , '" + sname.Text.ToString() + "' , '" + dob.Text.ToString() + "' , '" + tarweight.Text.ToString() + "' , '" + tarcal.Text.ToString() + "' , '" + height.Text.ToString() + "')";
check what this contains, maybe [DateOfBirth] has illegal format

Update textbox value into sql

When im trying to update the textbox values into db.It throws me an exception "Invalid syntax near (value of the txtkey.text)" Can anyone Help
SqlConnection con = new SqlConnection("server=server1;Database=testdb;User Id=dev;password=sqlad#2006");
SqlCommand com = new SqlCommand("insert into tbl_licensing(UserName,CompanyName,EmailId,LicenseKey) values ('" + txtUserName.Text + "','" + txtCompanyName.Text + "','" + txtEmailId.Text + "','"+ txtKey.Text + "'",con);
con.Open();
com.ExecuteNonQuery();
con.Close();
You have started this "values (" but you never closed it. Check again.
It will be good if you use parameterized query or stored procedure instead of directly writing query
You can check this article.
http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
You have forgotten closing bracket ) in your query
Updated code for you :
SqlCommand com = new SqlCommand("insert into
tbl_licensing(UserName,CompanyName,EmailId,LicenseKey) values ('" + txtUserName.Text + "','"
+ txtCompanyName.Text + "','" + txtEmailId.Text + "','"+ txtKey.Text + "')",con);
Your code is wrong in many ways. Use parameterized query and you will
Avoid sql injection attacks
You will
not have to escape the data entered
by user
The performance of your
queries will get better
The code will be much easier to read, understand and refactor.
The correct way to use SqlCommand with parameters is to fill the SqlCommand's Parameters collection with parameter names and values.
See MSDN documentation.

Categories