JDBC PreparedStatemnt MySQLSyntaxErrorException - java

I have read previous questions related to my query.Tried making those changes in my existing code.But still getting this error.I have spent 3 hours resolving this,but not able to catch the bug.Please help me with it.
I am using PreparedStatement for sending SQL queries.Below is the query:
String getExistingFileEntry = "select * from test "
+ " where a = ? and b = ? and date < DATE_SUB(NOW(), INTERVAL 1 DAY)"
+ "order by id"
+ "limit 1";
PreparedStatement pstVerify = null;
pstVerify = con.prepareStatement(getExistingFileEntry);
pstVerify.setString(1, a);
pstVerify.setString(2, b);
ResultSet rsFirst =null;
String existingSum = null;
//execute select SQL statement
rsFirst = pstVerify.executeQuery();
Getting this error # rsFirst = pstVerify.executeQuery()
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: 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 '1' at line 1
I tried running this SQL query on workbench and returns the correct rows.
Can someone please point me where I am doing wrong?
Thanks!

check your spaces replace this
String getExistingFileEntry = "select * from test "
+ " where a = ? and b = ? and date < DATE_SUB(NOW(), INTERVAL 1 DAY)"
+ "order by id"
+ "limit 1";
by
String getExistingFileEntry = "select * from test "
+ " where a = ? and b = ? and date < DATE_SUB(NOW(), INTERVAL 1 DAY)"
+ " order by id"
+ " limit 1";

Related

PreparedStatement set Where clause [duplicate]

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 4 years ago.
I'm using PreparedStatement for a DELETE query.
My ps is configured as this
config.sql.statement.delete=DELETE FROM ? WHERE ?
Then in my Java code, I set values like this
ps.setString(1, schemaName == "F" ? "FUNDS" : "MANDATE" + "." + tableName);
ps.setString(2, whereClause);
The whereClause is set up as below
String whereClause = " ";
for (int m = 0; m < columns.size(); m++) {
String columnData = jsonObj.getString(columns.get(m));
log.info("Column Data for column " + columns.get(m) + " Value: " + columnData);
if (m == 0) {
whereClause = whereClause + columns.get(m) + " = " + "'" + columnData + "'";
} else {
whereClause = whereClause + " AND " + columns.get(m) + " = " + "'" + columnData + "'";
}
}
log.info("WHERE CLAUSE: " + whereClause);
whereClause is being logged as this:
WHERE CLAUSE: CLIENT_END_DT = '9998-12-31' AND CLIENT_START_DT = '2017-04-06' AND FUND_CODE = 'TEST_CODE'
ERROR that I got:
com.microsoft.sqlserver.jdbc.SQLServerException: An expression of non-boolean type specified in a context where a condition is expected, near '#P1'.
After google a bit, I noticed that it might be related to how I configure WHERE clause. Any exact problem with the way I use this ps?
With PreparedStatement you cannot use database object names i.e. table, columns as parameter.
In your sql query, use specific names for both table and columns, in order to avoid SQL injections.
DELETE FROM table_name WHERE column1 = ? and column2 = ?
Perhaps, you may use your custom placeholder for the same as work around, beware of SQL attacks !
config.sql.statement.delete=DELETE FROM $table WHERE $whereClause
Later build your sql as:
String sql = ...; /* your logic */
sql = sql.replace("$table",(schemaName == "F" ? "FUNDS" : "MANDATE" + "." + tableName));
sql = sql.replace("$whereClause",whereClause);
ps=conn.prepareStatement(sql);

Unexpected behaviour of SELECT query after UPDATE

Following is the logic in my java code :
con.setAutoCommit(false);
int starIndex = 0;
List Details = new ArrayList();
while (true) {
isRsEmpty = true;
String my_Query = "select * from x,y,z where"
+ " x.a = y.b"
+ " x.a = z.c"
+ "y.b = z.e"
+ " ORDER BY a ASC"
+ " limit 5"
+ " offset " + starIndex;
preparedStatement = con.prepareStatement(my_Query);
rs = preparedStatement.executeQuery();
while (rs.next()) {
isRsEmpty = false;
//Other processing steps
starIndex++;
Details.add(rs.getInt("id"));
}
if(isRsEmpty){
starIndex = 0;
}
Iterator itr = Details.iterator();
String updateTable = "UPDATE x SET status = ? where i = ? and j = ? and k = ?";
updatePreparedStatement = con.prepareStatement(updateTable);
while (itr.hasNext()) {
updatePreparedStatement.setInt(1, 1);
updatePreparedStatement.setString(2, "zzz");
updatePreparedStatement.setInt(3, 9);
updatePreparedStatement.setInt(4, 10);
updatePreparedStatement.addBatch();
}
updatePreparedStatement.executeBatch();
con.commit();
Details.clear();
}
The Problem :
I have 13 entries in my table which meets the select query.
When I first time run the query my Limit is 5 and Offset is 0 and I get
5 records correctly from the table and the selected 5 records are updated.
After doing the update to the table when the select query runs again it gives me 3 records.This is unexpected since I have more 8 records left in the table.Again the 3 records are updated.
Again when the select query runs it gives me 0 records.
Then again a select query runs which gives me 5 records and updates the 5 records.
I am not able to understand this behaviour. If I run my select query without update then it runs correctly which gives me 5,5,3 records , but with the above logic it gives me 5,3,0,5 records.
What is the problem here ?
Note : In the above program all the variables like PreparedStatement and other are declared correctly.
Thank you
Is there any chance you are missing "and" keyword between your conditions in the select query?
String my_Query = "select * from x,y,z where"
+ " x.a = y.b"
+ " AND x.a = z.c"
+ " AND y.b = z.e"
+ " ORDER BY a ASC"
+ " limit 5"
+ " offset " + starIndex;
I don't know if that would solve the problem but I find it weird that it works like this.

How can I get the alias name for my ResultSet from a Subquery?

I have a problem with getting the alias of the columnnames for my ResultSet.
I made a subquery, where i use the alias function(MAX(...) in SQL) but everytime I execute the Statement, I get java.sql.SQLException because the column name is not valid. And I use the current alias where I call the getString - Function of my ResultSet.
This is my SQL-Statement in Eclipse:
String sql = "SELECT a.steelgrade, a.prod_order_id, a.prod_order_item_pos, "
+"a.prod_order_version, a.strip_thickn_aim, a.strip_width_aim, "
+"a.customer, a.order_weight_plan, b.grund_kommlos, b.coil_weight "
+"FROM (SELECT prod_order_id, prod_order_item_pos, "
+ "MAX (prod_order_version) AS max_version "
+ "FROM production_order "
And in the ResultSet while.next()-Loop:
prod_order_version = AuftraegeProduction.getString("max_version");
This is the whole SQL-Statement( in the Database it works fine!):
SELECT a.steelgrade, a.prod_order_id, a.prod_order_item_pos,
a.prod_order_version, a.strip_thickn_aim, a.strip_width_aim,
a.customer, a.order_weight_plan, b.grund_kommlos, b.coil_weight
FROM (SELECT prod_order_id, prod_order_item_pos,
MAX (prod_order_version) AS max_version
FROM production_order
GROUP BY prod_order_id, prod_order_item_pos) c
JOIN
production_order a
ON a.prod_order_id = c.prod_order_id
AND a.prod_order_item_pos = c.prod_order_item_pos
AND a.prod_order_version = c.max_version
JOIN pps_plan_slab b
ON b.prod_order_id = c.prod_order_id
AND b.prod_order_item_pos = c.prod_order_item_pos
AND b.prod_order_version = c.max_version
WHERE a.strip_thickn_aim > 1.78
AND a.strip_thickn_aim < 3.26
AND a.steelgrade = 'M4R51'
AND a.prod_order_id NOT BETWEEN '0999551' AND '0999599'
AND a.strip_width_aim BETWEEN 1126 AND 1166
AND NVL (a.order_weight_plan, 0) > 0
AND a.order_weight_plan >= b.coil_weight
ORDER BY prod_order_id ASC
Anyone have a suggestion?
Maurice
when using aggregate functions max(),min(),sum(),... you must use group by clause clause.

update current date and time to db using sql from Java code

i have a table "queue_in_progress" whose structure is like the following :
I want to update the DATE_TIME_TOKEN_TAKEN , CE_PK , Service_status of the table . For this , I have the following code :
String sqlQuery = "UPDATE queue_in_progress\n" +
"SET CE_PK="+ce_pk+" ,SERVICE_STATUS=1 \n" +
"WHERE CATEGORY_PK="+Category_PK+" AND TOKEN_NO="+ Token_PK+" "
+ " AND SERVICE_COUNTER="+service_counter+" AND SERVICE_CENTER_PK="+service_center+" ;";
java.util.Date utilDate = new Date(); // Convert it to java.sql.Date
java.sql.Date date = new java.sql.Date(utilDate.getTime());
PreparedStatement stmt = con.prepareStatement(sqlQuery);
stmt.setDate(1, date);
success = stmt.executeUpdate();
But the success flag is returning -1 and the table is not updated . What is the problem ? What can I do to fix this problem ?
I don't see DATE_TIME_TOKEN_TAKEN=? in your query (the bind parameter), I think you wanted
String sqlQuery = "UPDATE queue_in_progress SET DATE_TIME_TOKEN_TAKEN=?, "
+ "CE_PK=" + ce_pk
+ ", SERVICE_STATUS=1 WHERE CATEGORY_PK="
+ Category_PK
+ " AND TOKEN_NO="
+ Token_PK
+ " AND SERVICE_COUNTER="
+ service_counter + " AND SERVICE_CENTER_PK=" + service_center;
OR if you want DATE_TIME_TOKEN_TAKEN to ALWAYS hold Current Time value, you can Set it on your Database side, no need to set it in your code.
ALTER TABLE queue_in_progress
MODIFY DATE_TIME_TOKEN_TAKEN DEFAULT CURRENT_TIMESTAMP;

Problem with query in MySql

String sql = "SELECT siteapplications.Application, Count(visits.VisitId) AS CountOfVisitId
FROM visits, siteapplications
WHERE visits.SiteApplicationId=siteapplications.ApplicationID
and Month(visits.VisitTime)=" + month + "
and Year(visits.VisitTime)=" + year +
"GROUP BY siteapplications.Application
ORDER BY CountOfVisitId DESC;";
rs = st.executeQuery(sql);
When I run it I get this error in java :
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 'BY Application ORDER BY CountOfVisitId DESC' at line 1
I don't see a error ...
Can anyone help ...
thx all
" and Year(visits.VisitTime)=" + year + "GROUP BY ...
Should be:
" and Year(visits.VisitTime)=" + year + " GROUP BY ...
Your version is missing a space before GROUP.

Categories

Resources