org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: TOP near line 1, column 8 [SELECT TOP 10 IServe.ID FROM TopUp.dbo.IServe WHERE ExpireDate >= '2019-10-03' AND TelcoID = '2' AND ProductID = '2' AND RechargeAmt = '100.0' AND Available = 1 ORDER BY ExpireDate, SN]
String query3 = "SELECT TOP " + importStockList.getOrderQuantity() +" IServe.ID FROM IServe WHERE "
+ " ExpireDate >= '" + sqlDate + "' " + " AND TelcoID = '" + importStockList.getTelcoId()
+ "' AND ProductID = '" + importStockList.getProductId() + "' AND " + "RechargeAmt = '"
+ importStockList.getRechargeAmt() + "' AND Available = 1 ORDER BY ExpireDate, SN" ;
Session hbsessionSQL = HibernateUtilSQL.getSessionFactory().openSession();
List<Iserve> iserve = hbsessionSQL.createQuery(query3).list();
Can you please help me this error. I am stuck here
While your query is hard to read, and you should be using a prepared statement, I don't see anything wrong per se about the syntax. So the error is probably happening because TOP is not valid HQL syntax. TOP is really only supported on Microsoft databases, such as SQL Server or Access. Try using LIMIT instead:
try {
Session session = HibernateUtilSQL.getSessionFactory().openSession();
Connection conn = session.connection();
String sql = "SELECT ID FROM IServe WHERE ExpireDate >= ? AND TelcoID = ? AND ProductID = ? AND RechargeAmt = ? AND Available = 1 ORDER BY ExpireDate, SN LIMIT ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, sqlDate);
ps.setInt(2, importStockList.getTelcoId());
ps.setInt(3, importStockList.getProductId());
ps.setInt(4, importStockList.getRechargeAmt());
ps.setInt(5, importStockList.getOrderQuantity());
ResultSet rs = ps.executeQuery();
while(rs.next()) {
// process result set here
}
}
catch(HibernateException e) {
e.printStackTrace();
}
Since its not understood what type your variables are, try to see the data by yourself. If there is an option string values contain special characters, remove them first.
Related
I'm trying to make CRUD (Create, Read, Update, Delete) to my projects. But it seems the "update" doesn't work. It keeps saying
java.sql.SQLSyntaxErrorException : You have an error in your SQL syntax; check the manual that coresponds to your MariaDB server version for the right syntax to use near "Number" = 0813874810 WHERE Name = "Gregory" at line 1)
What the solution for this?
Here is my code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata", "root", "");
String sql = "UPDATE employeetab SET Name = '" + txtEmployeeName.getText()
+ "',Address = '" + txtEmployeeAddress.getText()
+ "',Gender = '" + gender_type
+ "',Phone Number = '" + txtEmployeePhone.getText()
+ "' WHERE Name = '" + txtEmployeeName.getText() + "'";
stm = conn.prepareStatement(sql);
stm.execute(sql);
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
Problem comes from the space in column Phone Number. To make it work you need to escape the column name with `.
UPDATE employeetab
SET Name = 'something',Address = 'some address',Gender = 'whatever',`Phone Number` = '000000000'
WHERE Name = 'something';
You should follow sql naming conventions, normally words in column names are separated by _. Your column name should be - phone_number.
Also, as mentioned in comments, you should not just add user input into sql queries, because you are leaving yourself wide open for sql injection.
You need to follow the naming conventions , their is space between 'Phone Number' column you should not write like this you need to add _ in between of this two.
try this :
String gender_type = null;
if (ButtonM.isSelected()){
gender_type = "Male";
}else if(ButtonFM.isSelected()){
gender_type = "Female";
}
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata","root","");
String sql = "UPDATE employeetab SET Name = ? ," +
" Address = ? ," +
" Gender = ? ," +
" Phone Number = ? ," +
" WHERE Name = ? ," ;
PreparedStatement pStmt = conn.prepareCall(sql);
pStmt.setString(1, txtEmployeeName.getText()+"");
pStmt.setString(2, txtEmployeeAddress.getText()+"");
pStmt.setString(3, gender_type+"");
pStmt.setString(4, txtEmployeePhone.getText()+"");
pStmt.setString(5, txtEmployeeName.getText());
pStmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
its cleaner and should work.
I have the following code:
try {
userPasswordNew = new String(ChangePW.passwordFieldconfirm.getPassword());
PreparedStatement prepStmt = connection.prepareStatement(
"UPDATE " + TABLE_NAME + " SET password = " + userPasswordNew + " WHERE username = " + username);
prepStmt.setString(2, BCrypt.hashpw(userPasswordNew, BCrypt.gensalt(bcryptRounds))); //2 represents number of column in database starting with 0
System.out.println(prepStmt);
return prepStmt.executeUpdate() != 0;
} catch (SQLException e) {
e.printStackTrace();
}
I tried 1 2 and 3 as indexes but everytime it throws an Index out of range exception. Is there another way to get the column, maybe adressed with its name? Or what am I doing wrong?
Could somebody please help?
To use prepared statements - please use ? instead provided values. Like in this sample:
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
updateSales = con.prepareStatement(updateString);
To get more, please look here. In your case that could be:
PreparedStatement prepStmt = connection.prepareStatement(
"UPDATE " + TABLE_NAME + " SET password = ? WHERE username = ?");
prepStmt.setString(1, "that new password");
prepStmt.setString(2, "user_name");
I assume password and username are textual values. Hence you will have to enclose the values by quotes.
That is the query will be
"UPDATE " + TABLE_NAME + " SET password = " + userPasswordNew + " WHERE username = " + username
Also, as you are using PreparedStatement, you must not mention the variables in the query. A neater approach would be to use ? instead. Something like this.
"UPDATE " + TABLE_NAME + " SET password = ? WHERE username = ?
And then use .setString() etc methods with userPasswordNew and username.
Check this, https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
When you use PreparedStatement, you define the parameters to pass in the sql statement by placing 1 or more ?.
Then you pass values to these parameters with methods like setString(), setInt(),... The order of the parameters is not 0 based but 1 based.
try {
userPasswordNew = new String(ChangePW.passwordFieldconfirm.getPassword());
PreparedStatement prepStmt =
connection.prepareStatement("UPDATE " + TABLE_NAME +" SET password = ? WHERE username = ?");
prepStmt.setString(1, userPasswordNew);
prepStmt.setString(2, username);
System.out.println(prepStmt);
return prepStmt.executeUpdate() != 0;
} catch (SQLException e) {
e.printStackTrace();
}
In your code there is this line:
prepStmt.setString(2, BCrypt.hashpw(userPasswordNew, BCrypt.gensalt(bcryptRounds)));
I don't know if this is a parameter that you want to pass.
If it is I can't see a ? placeholder in the sql statement.
I'm having some trouble using Oracle, since I was used to MySql syntax,
I'm trying to implement a query in my java program, but I keep getting the error:
ora-0933 sql command not properly ended.
My Query is:
String query1 = "SELECT t.nome, h.Valor_Atual, h.Valor_Antigo, a.nome
FROM Tecnologias t, Historico h, Academista a
WHERE h.Id_Academista = a.Id_Academista
AND h.Id_Tecnologia = t.Id_Tecnologia
AND (Valor_Atual || Valor_Antigo || nome)
LIKE '%" +ValToSearch + "%'";
Am I doing something wrong or is it Oracle syntax?
Thank you so much!
Although (Valor_Atual || Valor_Antigo || nome) LIKE '%" +ValToSearch + "%' is valid SQL syntax, it might match incorrectly, if the value to search happens to match a cross-over from value of one column to the next. So, you need to use OR, and you need to check columns separately.
Other issues:
Use JOIN syntax
Use PreparedStatement instead of string concatenation
Use try-with-resources (assuming you're not)
That means your code should be like this:
String sql = "SELECT t.nome, h.Valor_Atual, h.Valor_Antigo, a.nome" +
" FROM Historico h" +
" JOIN Academista a ON a.Id_Academista = h.Id_Academista" +
" JOIN Tecnologias t ON t.Id_Tecnologia = h.Id_Tecnologia" +
" WHERE h.Valor_Atual LIKE ?" +
" OR h.Valor_Antigo LIKE ?" +
" OR a.nome LIKE ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "%" + ValToSearch + "%");
stmt.setString(2, "%" + ValToSearch + "%");
stmt.setString(3, "%" + ValToSearch + "%");
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
// code here
}
}
}
This question already has answers here:
Difference between Statement and PreparedStatement
(15 answers)
Closed 4 years ago.
I am writing a simple method to update a record using spring jdbc the method is
#Override
public void updateEmployee(Employee e, int id) {
try {
Connection connection = DemoApplicationServiceImpl.getConnection();
Statement statement = connection.createStatement();
String update = "UPDATE salesforce.Employee__c SET First_Name__c = " + e.getFirst() + ", Last_Name__c = "
+ e.getLast() + ", Email__c = " + e.getEmail() + " WHERE Id = " + id;
System.out.println(update);
statement.executeQuery(update);
} catch (Exception ex) {
ex.printStackTrace();
}
}
It gives me an error
psqlexception column "umair" does not exist
umair is not even a column in database
Can anyone help?
Thanks
Your solution can cause SQL Injection or Syntax error, instead use PreparedStatement it is more secure and more helpful :
String update = "UPDATE salesforce.Employee__c SET First_Name__c = ?, Last_Name__c = ?, Email__c = ? WHERE Id = ? ";
try (PreparedStatement pstm = connection.prepareStatement(update)) {
pstm.setString(1, e.getFirst());
pstm.setString(2, e.getLast());
pstm.setString(3, e.getEmail());
pstm.setInt(4, id);
pstm.executeUpdate();
}
About your Error :
You get that error because you try to use something like this :
SET First_Name__c = umair
But String or varchar should be between two quotes :
SET First_Name__c = 'umair'
//------------------^_____^
Try this:
String update = "UPDATE salesforce.Employee__c SET First_Name__c = '" + e.getFirst() + "', Last_Name__c = '"
+ e.getLast() + "', Email__c = '" + e.getEmail() + "' WHERE Id = " + id;
When comparing fields to string values (and other values in general), you need to use quotes, like FIELD = 'Value'.
But as others said, is better to always use PreparedStatement
https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
I am trying to update a MS Access database. I have searched this and I have tried everything I have found but I am still getting the following error.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
Any help would be very helpful. My code is below...;
String sqlStatement = "UPDATE ProductCatalogue"
+ "SET [StockLevel] = ?"
+ "WHERE [ProductID] = ?;";
PreparedStatement prepStatement = connection.prepareStatement(sqlStatement);
prepStatement.setInt(1, quantity);
prepStatement.setInt(2, productID);
//= "UPDATE ProductCatalogue"
//+ "SET StockLevel = " + quantity
//+ "WHERE ProductID = " + productID + ";";
try {
//myStatement.executeUpdate(sqlStatement);
prepStatement.executeUpdate();
} catch (SQLException sqle) {
System.out.println("Oopss...." + sqle);
}
connection.close();
prepStatement.close();
you may need a few whitespaces. Try:
String sqlStatement = "UPDATE ProductCatalogue "
+ "SET [StockLevel] = ? "
+ "WHERE [ProductID] = ?;";
(note the space after ProductCatalogue and the first ?)