I have this code:
"SELECT tblschemeprojectpaymentgateway.paymentgatewayid, paymentgatewayname FROM " +
"tblschemeprojectpaymentgateway INNER JOIN tblpaymentgateway ON " +
"tblschemeprojectpaymentgateway.paymentgatewayid = tblpaymentgateway.paymentgatewayid"+
"WHERE tblschemeprojectpaymentgateway.schemeprojectid=`"+
SchemeProjectID.ToString()+"`", SqlConnection1);
sqlcmd.CommandType = CommandType.Text;
SqlConnection1.Open();
Npgsql.NpgsqlDataReader dr = sqlcmd.ExecuteReader();
which queries a Postgresql database. SchemeProjectID is a Guid. This code executes fine with the pgAdmin database query tool, but throws a syntax error in the C# code soemwhere around "tblschemeprojectpaymentgateway".
I have tried the SchemeProjectID in quotes, backtics and just as it is - with and without the .ToString().
I can not figure out what is wrong.
Classic problem when splitting strings over several lines; you're missing the space between tblpaymentgateway.paymentgatewayid and WHERE.
To help avoid missing spaces in strings split over multiple lines, I have found it helpful to use the # symbol before the string to take a multi line string literally. Like such:
string command = #"SELECT tblschemeprojectpaymentgateway.paymentgatewayid, paymentgatewayname FROM
tblschemeprojectpaymentgateway INNER JOIN tblpaymentgateway ON
tblschemeprojectpaymentgateway.paymentgatewayid = tblpaymentgateway.paymentgatewayid
WHERE tblschemeprojectpaymentgateway.schemeprojectid=`" + SchemeProjectID.ToString() + "`";
Also, you may want to look into parameterizing your statements and possibly wrapping them in stored procedures.
You are missing a space on the third line before the WHERE.
"SELECT tblschemeprojectpaymentgateway.paymentgatewayid, paymentgatewayname FROM " +
"tblschemeprojectpaymentgateway INNER JOIN tblpaymentgateway ON " +
"tblschemeprojectpaymentgateway.paymentgatewayid = tblpaymentgateway.paymentgatewayid "+
"WHERE tblschemeprojectpaymentgateway.schemeprojectid=`"+
Related
I have been getting a syntax error in my UPDATE datagridview code which happens to work in another .cs file. My group has been looking at different solutions online but everything won't work.
My group has been looking at different solutions online but everything won't seem to work.
{
connection.Open();
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Update Table1 set treatment = '" + treat.Text + "', remarks = '" + appRemarks.Text + "', cost = '" + treatCost.Text + "', Time = '" + textBox2.Text + "' where lastName = '" + Lastname.Text + "' ";
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Updated Successfully!");
}
The expected output should be Updated Successfully! and it should reflect in the database file after clicking the update button. Sometimes the output is "Microsoft Engine database" which does not save the changes.
The error says "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'" pointing to cmd.ExecuteNonQuery();
First, never use string concatenation to build a query. You're asking for a SQL Injection attack. The biggest thing I could see here is make sure that only columns that are string columns (varchar, char, text, etc..) have single-quoted values. Is cost a number? If so then it should be:
, cost=" + treatCost.Text + ",
If cost is a number, also make sure that there isn't a currency amount in the input field. If someone puts in 1,422.00 it's not a number and will fail since , is for decoration.
If someone puts in $1422.00 it's not a number as $ is for decoration.
Either of these would fail the query.
This would happen if someone types an apostrophe into the remarks field, which SQL server will interpret as the ending quote of the string. But much worse things can happen if the user knows a bit of sql and wants to cause trouble. For example, putting '-- in the remarks will result in
Update Table1 set treatment = 'blah', remarks = ''-- where lastName = 'foobar'
which will overwrite every row in the table, not only the one containing foobar.
Use query parameters so that user-provided values can't be interpreted as query keywords and structure.
Instead of remarks = '" + appRemarks.Text + "' you will have remarks = #Remarks as well as
cmd.Parameters.Add("#Remarks", SqlDbType.NText).Value = appRemarks.Text;
and all the other user inputs likewise.
'admin_table_name' is string array containing the names of table which are taken as an input from text file and 'table_index' is the index of an array.so,while firing the query below,"admin_table_name[table_index]" is avoided by throwing 'OdbcException was caught' as an exception.what is the mistake i am making in the code? please help.
cmd.CommandText = "SHOW KEYS FROM " + admin_table_name[table_index] + " where Key_name = 'PRIMARY'";
dr = cmd.ExecuteReader();
Why use ODBC? For most databases are native Drivers available.
Can you post the the complete String of the CommandText before executing the Reader?
If I use OleDb to connect to a database then use this to capture the info into a datareader -- how could I append this datareader results to a separate query that I am building?
string appendSQL = "";
xxx = new OleDbCommand("Select * from tbl_local, connstring);
dr = xxx.ExecuteReader();
while (dr.Read())
{
appendSQL = dr["salestatus"].ToString() + ",";
}
---- Separate Query I am building that I want to append the datareader results to:
var qd = new DAO.QueryDef();
qd.SQL = String.Format("Select salesName, saleAmount" + appendSQL + "dateSold from saleDB");
The above shows what I want to do, but when I try that I get multiple errors :(
That syntax as far as a coding standpoint goes looks good. Check your SQL statement and verify there are no issues with your SQL statement. Another solution would be to post the actual errors you are receiving as that will help us narrow down exactly what is causing the issue. As far as the syntax for joining multiple strings together in C# it is below. That would join the values of all three.
qd.SQL = String.Format(appendSQL + appendSQL1 + appendSQL2);
I tried to get values from access data base with two where clause. This is the error that I got!
"Syntax error (missing operator) in query expression 'unit1<=34 and unit2>=34 where"'.
and this is my code:
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Work\\Office\\Electricity_Board_bill_calculator\\gk.accdb;");
con.Open();
OleDbCommand com5 = new OleDbCommand("select id from tblBillConfig where unit1<="
+ contot + " and unit2>=" + contot + " where group=3 ", con);
You have 'where' in 2 places of the SQL string. This is at least one reason for the error.
There are a couple of potential issues:
You can't have 2 where clauses. The second filter needs to be introduced with and`
Group is a reserved keyword, so and needs to be escaped. (This would be [group] in Sql Server. I'm not sure how to do this in MS Access)
You should also look at using parameters to bind variables. This addresses a bunch of issues, such as sql injection, and also improves performance as the parameterization may allow your RDBMS to cache the query plan.
So your query should look something like this:
var com5 = new OleDbCommand("select id from tblBillConfig " +
" where unit1<=? and unit2>= ? and [group]=3 ", con);
command.Parameters.Add("#p1", OleDbType.Integer).Value = 34;
command.Parameters.Add("#p2", OleDbType.Integer).Value = 34;
I have an Access Db with C# and I am doing a concatenation in sql query aftere where clause but I am getting the following error
"Syntax error (missing operator) in query expression"
My code is below
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL=" + GlobalData.Email;
Please tell me what is causing the error and what the correct syntax is for concatenation.
You'd better use SqlParameter (more secure):
SqlCommand cmd = new SqlCommand("SELECT * FROM Temp1 WHERE Email LIKE #email")
cmd.Parameters.Add(new SqlParameter("email", GlobalData.Email));
To answer to the original question:
Using direct concatenation, without string delimiter, your query become:
SELECT * FROM Temp1 WHERE Email LIKE email#email.com
instead of
SELECT * FROM Temp1 WHERE Email LIKE 'email#email.com'
I think your your problem is missing quotes. Try this:
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL='" + GlobalData.Email + "'";
But that method can lead to SQL injection if you don't validate the email. Although there is nothing wrong with the above code, if data is validated, I do prefer to use SQL Parameters:
SqlCommand cmd = new SqlCommand( "SELECT * FROM Temp1 WHERE Email = #Email" )
cmd.Parameters.Add( new SqlParameter( "Email" , GlobalData.Email ) );
Try using Parameterised queries instead. It's usually the norm when working with SQL queries, for security reasons as well as readability.
You don't have any apostrophes around the string literal, so your query will end up like:
Select * from TEMP1 WHERE EMAIL=someone#somesite.com
This will of course cause a syntax error. You need the apostrophes around the string:
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL='" + Replace(GlobalData.Email, "'", "''") + "'";
However, encoding strings correctly is not trivial. (The above method works for Access and Microsoft SQL Server, but other databases needs other methods.) You should rather use parametrised queries:
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL=#email";
Then you add a parameter to the command object, for example:
cmp.Parameters.Add("#email", DbType.VarChar, 300).Value = GlobalData.Email;
Try something like below
cmd.CommandText = "Select * from TEMP1 WHERE EMAIL='" + GlobalData.Email + "'";
i'm not sure about the error, but you should try it like that
cmd.CommandText = string.Format("SELECT * FROM TEMP1 WHERE EMAIL='{0}'", GlobalData.Email);
That way you don't need to mess with ugly concatination that btw, takes alot of memory usage.