Syntax error in WHERE clause near '?) AND (Date = ?)' - sql

I am trying to send a SQL prepared statement to MySQL DB. This is what I have:
String sql1 = "SELECT idReimbursed_Funds As idReimFunds FROM reimbursedfunds Where ReimFundsName = ? AND Date = ?";
PreparedStatement pstmt1 = conn.prepareStatement(sql1);
pstmt1.setString(1, reimfund.getReimFundsName());
pstmt1.setDate(2, (Date) reimfund.getDate());
ResultSet rs1 = pstmt1.executeQuery(sql1);
while(rs1.next()){
idReimFunds = rs1.getInt("idReimFunds");
}
After googling this problem, I found solutions to use parenthesis around the question marks or the whole where clause such as:
String sql1 = "SELECT idReimbursed_Funds As idReimFunds FROM reimbursedfunds Where (ReimFundsName = ?) AND (Date = ?)";
This didn't work though. I get the same error message that is generated by my original code:
"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 '?) AND (Date = ?)' at line 1.
When I try the SQL statement in MySQL Workbench is works fine. Is there a way to use 2 where clauses with JDBC? I know in other posts people have answered that it has to be sent as two different queries, but I thought I would ask just in case someone else reads this posts and knows of a way. Thank you!

The problem (apart from the Date issue as mentioned by bgp), is the line:
ResultSet rs1 = pstmt1.executeQuery(sql1);
You are trying to execute a query string on a prepared statement, which is not allowed by the JDBC standard (MySQL should actually throw an exception instead of sending it to the server as it currently does, but the end result is the same). The documentation of Statement.executeQuery(String sql) says:
Throws:
SQLException - if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces anything other than a single ResultSet object, the method is called on a PreparedStatement or CallableStatement
(emphasis mine)
The reason is that you want to execute the prepared statement, not any other query. You should call PreparedStatement.executeQuery() (so without a parameter):
ResultSet rs1 = pstmt1.executeQuery();

Pretty sure this is because "Date" is a MySQL keyword (reserved). Call the field something else or escape it with backticks, i.e. `Date`

Related

How to delete multiple entities using Doctrine QueryBuilder

I am working on a Symfony 2.8 based project to manage contact. The user can select from a list any number of contacts and should be able to delete all selected contacts at once. How can this be done in a single Query Builder statement?
// Contact entity uses a GUID as ID
$guids = array(...);
try {
$this->getEntityManager()->getConnection()->beginTransaction();
$qb = $this->getEntityManager()->getConnection()->createQueryBuilder()
->delete('AppBundle:Contact', 'c')
->where('c.guid in (:guids)')
->setParameter(':guids', array($guids, Connection::PARAM_STR_ARRAY));
log($qb->getSql());
$qb->execute();
$this->getEntityManager()->flush();
$this->getEntityManager()->getConnection()->commit();
} catch (\Exception $ex) {
// Rollback the transaction
$this->getEntityManager()->getConnection()->rollback();
}
1. Problem
Addressing the entity with AppBundle:Contact (which works without any problem when building a SELECT statement) does not work. This is the log output:
Query: DELETE FROM AppBundle:Contact c WHERE c.guid in (:guids)
Exception: Doctrine\DBAL\SQLParserUtilsException: Value for :Contact not found in params array. Params array key should be "Contact" in
2. Problem
Using the table name instead (->delete('contact', 'c')) does not work as well:
Query: DELETE FROM contact c WHERE c.guid in (:guids)
Exception: Syntax error or access violation: 1064 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 'c WHERE c.guid in ('Array')'
3. Problem
Deleting a single entity does not work either:
->delete('contact', 'c')
->where('c.guid = (:guid)')
->setParameter(':guid', $guids[0]);
Query: DELETE FROM contact c WHERE c.guid = :guid
Exception: Syntax error or access violation: 1064 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 'c WHERE c.guid = 'E7516B91-0549-4FFB-85F2-4BD03DC3FFC1''
What might be wrong her?
1st. Problem. Change setParameter line to the following, you don't need to use : in name of param.
->setParameter('guids', $guids);
Second problem - you should not use real table name if you're dealing with queryBuilder.
Third problem - your logic is not correct. If you want to delete single then
$qb = $this->getEntityManager()->createQueryBuilder()
->delete('AppBundle:Contact', 'c')
->where('c.guid = :guid')
->setParameter('guid', $guids[0]);
Additionally
I don't really know what doctrine version you're using, but
$this->getEntityManager()->getConnection()->createQueryBuilder() - seems wrong, because usually you're getting connection if you want to execute RAW SQL.
Try to change to
$qb = $this->getEntityManager()->createQueryBuilder()
And you need to use brackets around the variable only if it's array. Check code below
$queryBuilder->andWhere('r.id IN (:ids)')
->setParameter('ids', $ids);
Unless you want to execute raw SQL, you don't have to use your entity manager's connection, so you can replace $this->getEntityManager()->getConnection()->createQueryBuilder() by
$em->createQueryBuilder()
You could do something like
$qb = $this->createQueryBuilder()
->delete('AppBundle:Contact', 'c')
->where('c.guid in (:guids)')
->setParameter(':guids', $guids);
And if you want to log/execute it
$query = $qb->getQuery();
log($query->getSql());
$query->execute();
You also don't need to add the beginTransaction and rollback, if the query fails and an exception is thrown, doctrine will rollback automatically.

SQL select query not working with variable parameter in my servelets

i'm trying to execute following line of code with my servelet in netbeans:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD =" + searchTxt);
where searchTxt is String variable.
but it says "Column 'zeeshan' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join . . . . ".
it really works fine, if i provide the hardcoded value instead of variable, as:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD= 'zeeshan'");
i'm not getting, what i'm missing?
You are missing the single quotes around the sql string you are constructing. So this should work:
ResultSet rs = stmnt.executeQuery("select * from ZEE.WORDCOUNT where WORD ='" + searchTxt+"'");
Please note that constructing SQL statements in this way is really dangerous, because it opens your application up for SQL injection attacks. Use bind parameters instead.
This will also allow better caching of parsed statements on many rdbms's.

error when executing query in linqpad

I have just started using LinqPad:
var con1 = from con in table
where con.tableKey == Guid.Parse("8EA5DC2C-2603-499A-A9D3-00019B53421F")
select con;
con.Dump();
throws me error
") or end of expression expected (change the Query Language to 'C# Statements' for multi-statement queries)"
Can anyone please correct me?
And also i have notices File-> New Query, New Query same properties on linqpad.
What is the difference between them? Thanks.
Make sure your type of query is C# statements and not C# expression... but if you aren't doing more than 1 statement you don't need the con.Dump(); (I think)

SQL Syntax Error near ADD [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I've been staring at this thing for a while now and I can't seem to figure out what the syntax error is. I've been in this situation before and last time it was something so unbelievably simple I felt stupid afterwards. But here's to another attempt:
//update database
$q = "
UPDATE
users
SET
id='$edit_id',
name='$edit_name',
bdm='$edit_bdm',
add='$edit_add',
pc='$edit_pc',
location='$edit_outletL',
style='$edit_outletS',
coName='$edit_coName',
coNum='$edit_coTel',
coEmail='$edit_coEmail',
password='$edit_pass'
WHERE
id='$query_title'
";
$edit_query = mysql_query($q) or die("Database Query Error: ". mysql_error());
Database Query Error:
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 'add='Llancadle, Nr Barry', pc='CF62 3AQ', location='rural', style='food', coName' at line 1
You neeed to backquote add since it is a keyword:
`add` = ...
I think add is a reserved word in MySQL.
your problem is that "add" is a MySQL reserved word. See: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html. If you have a column named "add", escape it like this:
//update database
$edit_query = mysql_query("UPDATE users SET id='$edit_id', name='$edit_name', bdm='$edit_bdm', `add`='$edit_add', pc='$edit_pc', location='$edit_outletL', style='$edit_outletS', coName='$edit_coName', coNum='$edit_coTel', coEmail='$edit_coEmail', password='$edit_pass' WHERE id='$query_title'") or die("Database Query Error: ". mysql_error());
as bobby noted in a comment, add is a mysql reserved word
`add`='$edit_add'
will tell mysql you are talking about a column

Php mysql statement with set and select

I have a weird problem, when i use the query on phpmyadmin, it works. but when i use using a php script it returns an error.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I tried to troubleshoot and discovered that the problem lies with the set statement.
this is my example code.
$sql = 'set #rank=0; select * from user;';
Please help somebody.
First Run
$sql = set #rank=0;
it will store value of rank
then run:
select * from user;
In sort you need to run both queries separately .
set statement stores values. that can be used by next executing query,
like code below :
$sql ="SET #id:=0";
$Executives=$DB->exec($sql);
$sql = "SELECT #id:=#id+1 as id,pes.* FROM profile_executive_summary as pes where profile_id=".$pid;
$Executives=$DB->fetchAssoc($sql);
See what mysql_error returns after you run mysql_query('...'). That might help. In general, mysql_query only permits one query. You can't separate them by newlines or semicolons. mysqli will do it for you though.