Update textbox value into sql - c#

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.

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

Access 2013 syntax error on INSERT INTO statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following query in c# and don't have any idea why it shows me this error:
"syntax error on INSERT INTO statement".
I use Access 2013.
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO money (price,cardnum,checknum,dateTime,employeeid) values('" + TempPrice + "','" + TempCriditNum + "','" + TempCheckNum + "','" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "','" + id + "')";
command2.ExecuteNonQuery();
connection.Close();
A few things to check
dateTime is a reserved word. Try wrapping it in square brackets -
if the type of data you are dealing with is a Date\Time then you should be wrapping the input in # signs
if your data types are not strings, do not wrap them in quotes
as pointed out by Jia Jian, you should use parameterized queries
as pointed out by HansUp, Money is also a reserved word, so wrap it in square brackets
So the query ends up looking like :
command2.CommandText = "INSERT INTO [money] (price,cardnum,checknum,[dateTime],employeeid) values(" + TempPrice + "," + TempCriditNum + "," + TempCheckNum + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + id + ")";
Your SQL statement might be prone to SQL injection. Consider using parameterized queries by adding values via the OleDbCommand.Parameters property instead of concatenating it.
An example would be:
command2.CommandText = "INSERT INTO [money] (price, cardnum, checknum, [dateTime], employeeid) values(#tempPrice, #tempCreditNum, #tempCheckNum, #dateTime, #id)";
command2.Parameters.AddRange(new OleDbParameter[] {
new OleDbParameter("#tempPrice", TempPrice),
new OleDbParameter("#tempCreditNum", TempCriditNum),
new OleDbParameter("#tempCheckNum", TempCheckNum),
new OleDbParameter("#dateTime", dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString()),
new OleDbParameter("#id", id)
});
command2.ExecuteNonQuery();
This should also solve your syntax error.

C# database application using Ms access 2010

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.

I am getting error while inserting to SQL

datetime=Datetime.Now;
string strquery = #"INSERT INT0 [Destination_CMS].[dbo].[Destination_CMS_User]
values('" + userid + "','" + email + "','"
+ userType + "','" + userStatus + "','" + processed + "','"
+ datetime.ToLongDateString() + "')";
cmd = new SqlCommand(strquery, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I am getting error:
Incorrect syntax near 'Destination_CMS'.
You've written INT0 rather than INTO.
Also, use parameterized queries.
You should try to change INT0 to INTO.
INSERT INT0 [Destination_CMS].[dbo]
I think its INSERT INTO rather than INT0 (zero)
Print the query to the screen, and verify where the syntax error is.
Next to that; use parametrized queries, like this:
string query = "INSERT INTO [tablename] ( column, column ) VALUES (#p_param1, #p_param2)";
var command = new SqlCommand (query);
command.Parameters.Add ("#p_param1", SqlDbType.DateTime).Value = DateTime.Now;
...
You are risking sql injection, if not using parametrized queries..
Your problem looks solved, so my next question would be, why not use an ORM like NHibernate/EF etc.., depending on your requirements offocourse, but ADO.NET plumbing in my books is where performance is an absolute issue.
You could write this as a stored procedure instead, which has the advantage of making typos like this a lot easier to spot and fix.

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

Categories