please figure out the error in my code.it show syntax error INSERT INTO statement.
OleDbCommand cmd = new OleDbCommand("INSERT INTO tbbill(invoice,datetime,custm,total,tax,grand)VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",'" + dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "','" + Convert.ToString(txtcn.Text) + "','" + txtttl.Text + "','" + Convert.ToInt32(cmtax.Text) + "','" + txtgrdttl.Text + "')", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
It seems that you've commited all the sins possible in this short fragment.
Something like that is expected:
// Make SQL readable
String sql =
#"INSERT INTO tbbill(
invoice,
[datetime], /* reserved word */
custm,
total,
tax,
grand)
VALUES(
?, ?, ?, ?, ?, ?)"; // Make SQL parametrized
// Put IDisposable into "using"
using (OleDbCommand cmd = new OleDbCommand(sql, con)) {
// Parameterized
cmd.Parameters.Add(txtinvoice.Text);
cmd.Parameters.Add(dateTimePicker1.Value);
cmd.Parameters.Add(txtcn.Text);
cmd.Parameters.Add(txtttl.Text);
cmd.Parameters.Add(cmtax.Text);
cmd.Parameters.Add(txtgrdttl.Text);
cmd.ExecuteNonQuery();
}
// Do not close that's not opened by you (i.e. con)
Apart from your weird INSERT statement, your column name datetime is a reserve word in Access. You should escape it suing [] like below.
INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand)
Your current query is open to SQL Injection and so as suggested in comment consider using parameterized query instead.
This should work:
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO tbbill(invoice,[datetime],custm,total,tax,grand)
VALUES(" + Convert.ToInt32(txtinvoice.Text) + ",\"" +
dateTimePicker1.Value.ToString("yyyy/MMM/dd") + "\",\"" +
Convert.ToString(txtcn.Text) + "\",\"" + txtttl.Text + "\",\"" +
Convert.ToInt32(cmtax.Text) + "\",\"" + txtgrdttl.Text + "\")", con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
EDIT:
As stated by others, your query is still open to SQL injection. Dmitry's answer will be the safest and efficient option.
Related
SqlConnection con = new SqlConnection(#"Data Source=HAMMAD2-PC\SQLEXPRESS;Initial Catalog=StockManagement;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [StockManagement].[dbo].[Product] ([ProductID], [ProductName], [SalePrice], [PurchasePrice], [Status])
VALUES ('" + pcodetxt.Text + "','" + pnametxt.Text + "','" + rtlpricetxt + "','" + purpricetxt.Text + "','" + statuscbox.SelectedIndex+")'",con);
cmd.ExecuteNonQuery();
con.Close();
This code causes an error
Incorrect syntax near '0)'
What is the solution?
I'm using Visual Studio 2012 and SQL Server
There wouldn't be such an error if you have used parameters, plus you would be protected from "SQL injection attack". ie:
using (SqlConnection con = new SqlConnection(#"server=.\SQLEXPRESS;Initial Catalog=StockManagement;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO [StockManagement].[dbo].[Product]
([ProductID]
,[ProductName]
,[SalePrice]
,[PurchasePrice]
,[Status])
VALUES
(#pid, #pname, #salePrice, #purPrice, #status)", con))
{
cmd.Parameters.Add("#pid", SqlDbType.Int).Value = int.Parse(pcodetxt.Text);
cmd.Parameters.Add("#pname", SqlDbType.VarChar).Value = pnametxt.Text;
cmd.Parameters.Add("#salePrice", SqlDbType.Money).Value = decimal.Parse(rtlpricetxt);
cmd.Parameters.Add("#purPrice", SqlDbType.Money).Value = decimal.Parse(purpricetxt.Text);
cmd.Parameters.Add("#status", SqlDbType.Int).Value = statuscbox.SelectedIndex;
con.Open();
cmd.ExecuteNonQuery();
con.Close(); // This is not needed: it is done by the implicit Dispose when exiting the using block
}
The error is because you're missing a closing quote in your sql statement, but you shouldnt be creating your statement manually with string manipulation in any case - this is very error prone, and extremely unsafe!
Use declared parameters instead.
See What's the best method to pass parameters to SQLCommand?
Incorrect Syntax near X, tries to show you that there is some thing wrong just before or after the X.
In your query you have placed ' in wrong place
So just rewrite it as below:
SqlCommand cmd = new SqlCommand(#"INSERT INTO [StockManagement].[dbo].[Product] ([ProductID], [ProductName], [SalePrice], [PurchasePrice], [Status])
VALUES ('" + pcodetxt.Text + "','" + pnametxt.Text + "','" + rtlpricetxt + "','" + purpricetxt.Text + "','" + statuscbox.SelectedIndex+"')",con);
Note: Using following code you put your self in the scope of the SQL Injection vulnerability, so you should always try to write the code as #CetinBasoz posted or other similar methods that makes you secure against the similar vulnerabilities.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SAGAR\\SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("insert into Patient_Details (Patient Id,Name,Age,Contact No,Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "',);", con);
object o= sc.ExecuteNonQuery();
MessageBox.Show(o +"Saved data");
con .Close();
}
I see a few things;
Patient Id should be [Patient Id] and Contact No should be [Contact No] since they are more than one word. As a best practice, change their names to one word.
You have extra , at the end of textBox5.Text + "', part.
But much more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var con = new SqlConnection(connection))
using(var sc = con.CreateCommand())
{
sc.CommandText = #"insert into Patient_Details ([Patient Id],Name,Age,[Contact No],Address)
VALUES(#id, #name, #age, #no, #address)";
sc.Parameters.AddWithValue("#id", textBox1.Text);
sc.Parameters.AddWithValue("#name", textBox2.Text);
sc.Parameters.AddWithValue("#age", textBox3.Text);
sc.Parameters.AddWithValue("#no", textBox4.Text);
sc.Parameters.AddWithValue("#address", textBox5.Text);
con.Open();
int i = sc.ExecuteNonQuery();
MessageBox.Show(i + " Saved data");
}
By the way, I used AddWithValue in my example since you didn't tell us your column types but you don't. This method might generate surprising results sometimes. Use Add method overloads to specify your parameter type (SqlDbType) and it's size.
Getting an object from ExecuteNonQuery is really strange as well. It will return int as an effected rows count. It will be 1 or 0 in your case.
As a last thing, I strongly suspect your Patient Id, Age and Contact No columns should be some numeric type, not character typed.
fields and table names with spaces must be inside [], also you have 1 extra comma in the end of your query. Try:
SqlCommand sc = new SqlCommand("insert into [Patient_Details] ([Patient Id],Name,Age,[Contact No],Address) VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "');", con);
object o= sc.ExecuteNonQuery();
also consider using parameters, since you are open to sql injection.
In C# when I write a query to update there is an error
Syntax Error in UPDATE query
My code:
public void Update()
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\Employees.mdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand("UPDATE employee SET ([Name],[Jobtitle],[Company])Values ('" + Name + "','" + Jobtitle + "','" + Company + "') where [EmpID] = '" + EmpID + "'", conn);
cmd.ExecuteNonQuery();
}
This is not the right syntax for UPDATE statements.
You should do this instead: SET column_1 = 'value 1', column_2 = 'value 2'
This is probably unrelated to your issue (unless there are special characters in the variables), but you should not use concatenation in SQL requests.
Use prepared requests instead.
So I have this code to insert values from text-box into my database, but every time i execute my code and enters my data i get this message
"Syntax Error near keyword user"
string Connectionstring = #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Bank_System.mdf;Integrated Security=True; User Instance=True";
SqlConnection cnn = new SqlConnection(Connectionstring);
cnn.Open();
SqlCommand cmd1 = new SqlCommand("insert into user values('" + int.Parse(textBox1.Text) + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + int.Parse(textBox6.Text) + "')", cnn);
SqlDataReader dr1 = cmd1.ExecuteReader();
dr1.Close();
MessageBox.Show(" Record inserted ", " information inserted");
cnn.Close();
USER is a reserved keyword in T-SQL. You should use it with square brackets like [USER]. However, the best solution is to change the name to a non-reserved word.
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
By the way, I don't understand why you used ExecuteReader for an INSERT command. Looks like you just need to use ExecuteNonQuery instead.
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command.
Also use using statement to dispose your SqlConnection, SqlCommand.
using(SqlConnection cnn = new SqlConnection(Connectionstring))
using(SqlCommand cmd1 = cnn.CreateCommand())
{
cmd1.CommandText = "INSERT INTO [USER] VALUE(#p1, #p2, #p3, #p4, #p5, #p6)";
cmd1.Parameters.AddWithValue("#p1", int.Parse(textBox1.Text));
cmd1.Parameters.AddWithValue("#p2", textBox2.Text);
cmd1.Parameters.AddWithValue("#p3", textBox3.Text);
cmd1.Parameters.AddWithValue("#p4", textBox4.Text);
cmd1.Parameters.AddWithValue("#p5", textBox5.Text);
cmd1.Parameters.AddWithValue("#p6", int.Parse(textBox6.Text));
cnn.Open();
int count = cmd1.ExecuteNonQuery();
if(count > 0)
MessageBox.Show("Record inserted");
}
You try to concatenate int to string. The error is here: int.Parse(textBox1.Text) -> you need to convert to string after you test if is integer.
Try this for test : int.Parse(textBox1.Text).ToString() to see if this is your problem.
You try gather string to an integer by using:
"insert into user values('" + int.Parse(textBox1.Text) ....
=> string + int
Correct is:
SqlCommand cmd1 = new SqlCommand("insert into user values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "')", cnn);
try to validate if textBox1.Text and textBox6.Text before concatenate but is recommended to use parameters.
I am using sql server for database and visual studio for inserting data in a table but i want the entered entries to be changed into uppercase before entry in database. which syntax to use for that.
Tell me what changes I can make in this statement:
SqlCommand cmd = new SqlCommand("insert into student values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
Google for SQL Injection, and change this to a parametrized query
Either TextBox.Text.ToUpper method:
SqlParameter parameter = new SqlParameter("#Param1", TextBox1.Text.ToUpper()
INSERT INTO ... VALUES(#Param1, #Param2,...)
or use the SQL UPPER function (SQL Server) - it's UCASE in some other databases:
INSERT INTO ... VALUES( UPPER(#Param1), UPPER(#Param2),...)
If you care about internationalization, be aware that ToUpper() without parameters will use the current culture (CultureInfo.CurrentCulture) to decide how to convert to upper case. SQL Server's UPPER function will depend on the database collation, so might give a different result. Google for "Turkish I problem" to understand the kind of issues this might cause.
SqlCommand cmd = new SqlCommand(
"insert into student
values('" + TextBox1.Text.ToUpper() + "','"
+ TextBox2.Text.ToUpper() + "','"
+ TextBox3.Text.ToUpper() + "')", con);
Use String.ToUpper();
some thing like this
SqlCommand cmd = new SqlCommand(
"insert into student values('" +
TextBox1.Text.ToUpper() + "','" +
TextBox2.Text.ToUpper() + "','" +
TextBox3.Text.ToUpper() + "')",
con);
This is c#
SqlCommand cmd = new SqlCommand("insert into student values('" + TextBox1.Text.ToUpper() + "','" + TextBox2.Text.ToUpper() + "','" + TextBox3.Text.ToUpper() + "')", con);
cmd.ExecuteNonQuery();
Check for sql injection, and use SqlParameters though.