Syntax error (missing operator) in query expression "" - c#

I'm having trouble deleting(DELETE) rows. Everytime I add column names in my string sql it shows the error "Syntax error (missing operator) in query expression ". This is my code:
OleDbConnection myCon = new OleDbConnection("provider = Microsoft.Jet.OLEDB.4.0;DataSource = '" + fileLocation + "'; Extended Properties=Excel 8.0;");
OleDbCommand myCmd = new OleDbCommand();
myCmd.Connection = myCon;
string sql = "DELETE * FROM [" + tablename + "$] where _date = '" + full_date + "'";
myCmd.CommandText = sql;
myCon.Open();
myCmd.ExecuteNonQuery();
myCon.Close();
For Example my string sql value is
"DELETE * FROM [Sheet1$] where _date = '03 09 2015'"
It would produce this error:
Syntax Error (missing operator) in query expression "_date = '03 09
2015'"
I have no problems when inserting data in my excel file but when it comes to delete it says this error.

Try to use this i.e., remove the *, it is not required with DELETE statement:
string sql = "DELETE FROM [" + tablename + "$] where _date = '" + full_date + "'";
Also the value which you are getting in full_date doesnt seem to be in correct format. Do check the value which you are getting in full_date with the format in which you are having in your table.
On a side note:
You code is prone to SQL Injection. You need to use prepared statement to avoid that.

You have syntax error in your query, please remove * from your query, hence your query may look like the following: you can check the syntax here:
string sql = "DELETE FROM [" + tablename + "$] where _date = '" + full_date + "'";
And the query you are using will opens a wide way for sql injection, so better approach is to use parameterized queries instead.

you should try
string strQuery= "DELETE FROM #TableName where _date = '#date'";
usin (SqlCommand cmd = new SqlCommand(strQuery)){
cmd.Parameters.AddWithValue("#TableName", tablename+"$" );
cmd.Parameters.AddWithValue("#date", full_date );
myCon.Open();
cmd.ExecuteNonQuery();
}

Related

SQL query in C# (System.Data.OleDb.OleDbException: 'Syntax error (missing operator) in query expression)

OleDbCommand commandtwo = new OleDbCommand("SELECT * from tblShowings WHERE ShowFilmID = " + filmID.Text + " AND Showdate = " + date.Text + " AND Showtime = " + time.Text + "", con);
What is wrong with my SQL query? I keep getting this error:
System.Data.OleDb.OleDbException: 'Syntax error (missing operator) in query expression 'ShowFilmID = 1111 AND Showdate = 67/87/9999 AND Showtime = 10:00'
Your current code is vulnerable to Sql Injections. You should be using parameterized query to avoid sql injections and handling of value types correctly.
The error in your code is because you are missing ' single quotes for string value types.
"ShowFilmID = '" + date.Text + "'" + ...
Here's an example how you should be using parameterized query:
OleDbCommand command = new OleDbCommand(
"SELECT * from tblShowings WHERE ShowFilmID = ? AND Showdate = ? AND Showtime = ?", con);
OleDbParameterCollection paramCollection = command.Parameters;
OleDbParameter myParm = paramCollection.Add(
new OleDbParameter("ShowFilmID", filmID.Text),
new OleDbParameter("Showdate", date.Text),
new OleDbParameter("Showtime", time.Text));
Just a point to ponder here from a security standpoint. You need to ensure your data input/output is validated/sanitized to avoid exploit. The ideal process is stored procedure and parameterized values. If that is not possible, ensure that you have encoded your values so to avoid SQL Injection. Just my 2 cents worth.

In C# when I write a query to update there occurs an error "Syntax Error in UPDATE query"

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.

Why Am I getting this error in my SELECT statement in C# WinForms to MySQL Database?

I am getting this error:
Unknown column 'admin' in 'where clause'
This is my code for the Log-In button:
mycon.Open();
string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = " + textBox1.Text + "";
cmd = new MySqlCommand(cmdstr, mycon);
dr = cmd.ExecuteReader();
string inputpw = "";
string dbpw = "";
while (dr.Read())
{
inputpw = maskedTextBox1.Text;
dbpw = (dr["user_pw"].ToString());
}
dr.Close();
mycon.Close();
I can't quite get why I get that error since my Select statement is the same with all the other select statements I see online
enclose the textbox value in single quotes
string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = '" + textBox1.Text + "'";
Edit:
As commented by Tigran. Use Parametarized queries instead just concatenating values from the controls
I can't quite get why I get that error
Then start debugging. Put a breakpoint on the cmd = line and inspect cmdstr's contents. You'll see the query is:
SELECT * FROM usersettingsdb WHERE user_ID = admin
Then you'll see you need to put quotes around the username. Now go read about SQL injection, parametrized queries and DAL's.
You need an extra set of " " in your where clause surrounding the textbox1.Text otherwise you are not passing it a string.
string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = \"" + textBox1.Text + "\"";
Do something like this..
string cmdstr = string.Format("SELECT * FROM usersettingsdb " +
"WHERE user_ID = '{0}'", textBox1.Text.Replace("'","''"));
Replacing ' with '' because sql think ' as escape character.
But going with Parameterized queries is rocommended.

Odac ORA-00911: invalid character

I am writing a C# code that connects to ODAC. I think my query got no errors, but I get this error, I don't know how to solve.
This is my query
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = '" + login_id +
"' AND APPID = '" + app_id + "' ;";
Can any one figure out what is wrong in here?
Your query is vulnerable for a security issue called SQL injection!
You should NEVER use string concatenation for building a query from strings (some SQL, some parameters)... Use always parameterized queries...
Sample code:
comm.BindByName = true;
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = :login_id AND APPID = :app_id";
comm.Parameters.AddWithValue ("login_id", login_id);
comm.Parameters.AddWithValue ("app_id", app_id);
Why there is a ; in your sql command? Try this;
comm.CommandText = "SELECT * FROM ZAEDBA WHERE USER_ID = '" + login_id + "' AND APPID = '" + app_id "';
By the way, you should always use parameterized queries. This clearly open for an sql injection. For your query, use like this;
string commandText = "SELECT * FROM ZAEDBA WHERE USER_ID = #login_id " + AND
+ "WHERE APPID = #app_id;";
command.Parameters.Add("#login_id", SqlDbType.Int);
command.Parameters["#login_id"].Value = login_id;
command.Parameters.Add("#app_id", SqlDbType.Int);
command.Parameters["#app_id"].Value = app_id;

Parameterize a SELECT ROWCOUNT sql statement

I am using VS2005 C# and SQL Server 2005.
I have a a few SQL queries which I am converting them from using parameters instead concatenations for SQL injection prevention.
Below is a SELECT query which is parameter-ed:
string loggedinuser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [UserTable] where [" + DropDownList1.Text + "] like #searchtb AND [LoggedInUser] LIKE #userlog";
SqlDataSource1.SelectParameters.Add("searchtb", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("userlog", "%" + loggedinuser+ "%");
The above sql query searches for records base on the user's input in a search textbox and return results which matches the search input and username in the database.
I have another SQL query which is also a SELECT statement. However, this time it does not use SqlDataSource, but using cmd instead. Thus I need some help in converting the SQL statement below to parameter form:
string loggedinuser = (User.Identity.Name);
string stmt = "SET ROWCOUNT 1 SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [LoggedInUser] LIKE '%"+loggedinuser +"%'";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
This SQL query searches for number of records that the user is trying to search base on his search input and username. And if countuser returns a 0 value, I will prompt the user after that.
I need help in converting the 2nd SQL statement into parameter form.
Thank you.
Try,
string stmt = "SELECT COUNT(*) FROM MP.dbo.UserTable where [" + DropDownList1.Text + "]
like #searchTb AND [LoggedInUser] LIKE #loggedinuser";
int count = 0;
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
cmdCount.Parameters.Add("#searchTb",SqlDbType.VarChar,40).Value="%" + searchTB.Text + "%";
cmdCount.Parameters.Add("#loggedinuser",SqlDbType.VarChar,40).Value="%" + loggedinuser + "%";
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
Using stored procedures is your best bet, but if you cannot use them, this code should work:
SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = #au_id", conn);
SQLParameter parm = myCommand.SelectCommand.Parameters.Add("#au_id",
SqlDbType.VarChar, 11);
Parm.Value = Login.Text;
This is from the MSDN article on SQL injection.
http://msdn.microsoft.com/en-us/library/ms161953.aspx

Categories

Resources