SQL query exception issue - c#

Am trying to insert a record into my database using a function that consists of 11 arguments as input. The function is as follows:
public int check_in_visitor(int visitor_id,String date_in, String date_out,
String time_in, int check_in, int check_out, String employer,
String vehicle_number, int manual_entrychk, String time_out)
The corresponding query for it:
String query = "insert into visitor values('"+visitor_id +"','" +
date_in + "','" + date_out + "','" + time_in + "'," + check_in +
",'" + check_out + "'," + employer + ",'" + vehicle_number + "'," +
manual_entrychk + ",'" + time_out + "')
its always giving errors like expression incorrect! Please help me solve the issue

Use SqlParameter..
That way you would avoid sql injection attack,enclosing data with ' or " & other issues..
String query = "insert into visitor values(#visitor_id,#date_in,#date_out,#time_in,#check_in,#check_out,#employer,#vehicle_number, #manual_entrychk,#time_out)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add(new SqlParameter("visitor_id", visitor_id));
command.Parameters.Add(new SqlParameter("date_in", date_in));
....
command.ExecuteNonQuery();

You are missing to close the Query String with double quotes.
String query = "insert into visitor values('"+visitor_id +"','" + date_in + "','" + date_out + "','" + time_in + "'," + check_in + ",'" + check_out + "'," + employer + ",'" + vehicle_number + "'," + manual_entrychk + ",'" + time_out + "')";
Note1 : all VARCHAR feilds should be enclosed in single quotes properly.
Note 2: all INT feilds should not be enclosed with single quotes.
Note 3: your query is open to SQL injection attaks. please use parameterised queries.
untill unless you provide the feild types its defficult to solve the problem.

use string.format. Like string query = string.Format("insert into visitor values ('{0}','{1}'...",vistor_id ...); This syntax is a lot easier to troubleshoot and avoids the string concatenations. You should also consider not using data that's not fully trusted in your query (like anirudh mentioned in his reply), if that's an option at all.

if query below doesnt help you, please tell what is the error returned?
string query = "insert into visitor values ("+visitor_id+ ","+ date_in +","+date_out
+","+time_in+","+check_in+","+check_out+","+employer+","+vehicle_number+","
+manual_entrychk+","+time_out+")";

Related

What's the proper format to store DateTime from C# to a DateTime in SQL Database?

I'm using this query on a wpf application:
"INSERT INTO [Table]([fname],[lname],[cdate]) VALUES(" + #fname + "," + #lname + "," + #DateTime.Now + ")"
But it doesn't seem to work, it says: Incorrect Syntax near '12'. The problem has got to be somewhere in my DateTime since when I turn my code to this:
"INSERT INTO [Table]([fname],[lname]) VALUES(" + #fname + "," + #lname + ")";
The query executes perfectly fine.
The cdate has a datetime data type in SQL, if anyone was wondering.
Try below query
"INSERT INTO [Table]([fname],[lname],[cdate]) VALUES('" + #fname + "','" + #lname + "','" + #DateTime.Now.ToString("d") + "')"
Or
"INSERT INTO [Table]([fname],[lname],[cdate]) VALUES('" + #fname +
"','" + #lname + "','" + #DateTime.Now + "')"
OR
"INSERT INTO [Table]([fname],[lname],[cdate]) VALUES('" + #fname + "','" + #lname + "','" + #DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')"
Please check the date format also whether you are sending mm/dd/yy or dd/mm/yy and what your database accept.
Try set DateTime format before your main script:
SET dateformat ymd
INSERT INTO ...
sgmoore was right, the use of sql parameters did the trick, I didn't even have to format it, my whole code is:
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Table]([fname],[lname],[cdate]) VALUES(" + #fname + "," + #lname + ",#mydate)", Conn))
{
cmd.Parameters.Add(new SqlParameter("#mydate", DateTime.Now));
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}

Saving DateTime value into microsoft access database

I am trying to save some data to access DB but the date is stored in incorrect format
dbCommand.CommandText = "insert into Clients(Name,Gender,PhoneNumber,ReciveServiceDate)
values ('" + name_txtBox.Text + "','" + gender_comBox.Text + "',"
+ long.Parse(phone_txtBox.Text) + ","
+ (recive_dateTimePicker.Value).ToShortDateString() + ");";
Listen to Jon's advice.
However, if you insist, you can do it like this:
+ (recive_dateTimePicker.Value).ToString("#yyyy'/'MM'/'dd#") + ");";

Wrong SQL syntax SQL lServer C# winforms

hey I'm trying to run this query:
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "','" + "(SELECT ProductId FROM Products WHERE ProductName =N'" + listBox1.Text + "')','" + listBox1.Text + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
now the command.UseSqlCommand is just running the query, but I keep getting this error:
incorrect syntax near 'intel'
(intel is the 'ProductName' (that I'm getting from here:
SELECT ProductId FROM Products WHERE ProductName =N'" + listBox1.Text + "'
Edit : this is the value of the command , (getting the 'incorrect syntax near 'intel')
INSERT INTO DisplayOrders
Values ('2', '(SELECT ProductId FROM Products WHERE ProductName =N'Intel Quad Core i5 3470 3.2Ghz 6MB Tray')','Intel Quad Core i5 3470 3.2Ghz 6MB Tray','1','900')"
As others have stated you should use Parameterised queries which will overcome this issue. But to answer your question "as-is"...
You need to double-close your single quote. Best way to see this is store into a string and debug / write to trace. Example of how to double-close query here: How to insert text with single quotation sql server 2005
As-is your query string will contain something like this:
INSERT INTO DisplayOrders Values ('1234','(SELECT ProductId FROM Products WHERE ProductName =N'Fred')'...
But it should really contain something like this (notice the '''):
INSERT INTO DisplayOrders Values ('1234','(SELECT ProductId FROM Products WHERE ProductName =N'''Fred''')'...
Otherwise you are closing the INSERT Values not the SELECT statement.
Just remove the single quotes around the SELECT statement
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "'," +
"(SELECT ProductId FROM Products WHERE ProductName =N'" + listbox.Text +"'), " +
"'" + listBox1.Text + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
But this code will fail if any of your listbox items contains a single quote.
I have read your comment about SQL Injection not been an issue here, but it is a good habit to use even for schoolworks. At least change to
string itemName = listBox1.Text.Replace("'", "''");
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "'," +
"(SELECT ProductId FROM Products WHERE ProductName =N'" + itemName +"'), " +
"'" + itemName + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
Need replace to this
command.UseSqlCommand("INSERT INTO DisplayOrders Values ('" + OrderId.Text + "'," + "(SELECT IdProduct FROM Products WHERE ProductName =N'" + listBox1.Text + "'),'" + listBox1.Text + "','" + OrderQuantity.Text + "','" + TotalCost.Text + "')");
SELECT ProductId FROM Products WHERE ProductName =N'" + listBox1.Text + "'
will return a table so it is wrong to use it inside insert statement.
instead of using this , execute this command alone then get the returned value and then execute the insert statement alone

Error with SQL syntax (in Windows form , C#)

I'm trying to insert some data into my table and that's how I try to do it
INSERT INTO OrdersDetail
Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '" + listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "'");
and I'm geting error I think my syntax is wrong, I'm use query in query to get the product id.
The columns are :
OrderId (int)
ProductId(int)
ProductName(Nvarchar)
OrderQuantity(Nvarchar)
TotalCost(NvarChar)
Thanks
You set your inside SELECT under '. Should be:
var query = "INSERT INTO OrdersDetail Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '"+ listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "')");
If for example TotalCost.Text is a numeric data type in SQL, use
"..." + OrderQuantity.TextAlign + "', " + Convert.ToDouble(TotalCost.Text) + ")";
As p.s.w.g stated: This is open for SQL injection. Replace it with a parameterized version!
I think the problem is with the first Line and your inside Select.
This should work
INSERT INTO OrdersDetail
Values ('" + OrderId.Text + "',(SELECT IdProduct FROM Products WHERE ProductName ='"+ listBox1.Text + "')," + TypeOfProductComboBox.Text + "','" + OrderQuantity.TextAlign + "','" + TotalCost.Text + "'");
The problem is that you are missing the last bracket, the query should finish with "')" instead of "'" . The initial code started with opening bracket and that is why you didn't get compile errors.
But you should not create such sql queries, use Parameters to avoid SQL injection attacks. You code is vulnerable to them.

DateTime value from Oracle to MySql database

I have a question, how to parse datetime value from Oracle to MySQL database.
I wrote this to extract a datetime from Oracle:
SELECT TO_CHAR(p1.creation_date,'DD.MM.RRRR HH24:mi:ss') AS dat_pot
FROM TABLE
then I put the result into data set, then I extract the value of date from dataset like this:
string lDat_otp = null;
if (rw_mat["dat_otp"].ToString().Length <= 0)
{
lDat_otp = "0";
}
else
{
lDat_otp = "convert(datetime,'" + rw_mat["dat_otp"] + "',4)";
}
Then I use lDat_otp in INSERT statement with some other values like this:
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
lDat_otp + ",'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
But there is an error on execute and it goes:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '26.01.2012 13:48:41',4)','100654', '0', '10')' at line 1
So help!!!
You can parse the datetime field into a DateTime struct and then create an insert into query with parameters and pass the date as parameter :
DateTime time = //Some value ...
String myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
"?date ,'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
MysqlCommand command = new MysqlCommand(query, connection);
command.Parameters.AddWithValue("?date", time);
Doing this you should not have problems with date formatting.
I strongly suggest to use parameters instead of string concatenation even for the others parameters of the query ...

Categories

Resources