I am having an error in this code:
public List<AvailableTest> srchInTestsInDb(String search, String catg) {
try
{
Connection conn = Dbconn.Connect();
System.out.println(catg);
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY="+catg+"";
// + "TST_NAME LIKE '"+search+"%'";// AND TST_CATAGORY ="+catg+"";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
List<AvailableTest> testList = new ArrayList<AvailableTest>();
while (rs.next())
{
AvailableTest newtest = new AvailableTest();
newtest.setTstNo(rs.getInt("TST_NO"));
newtest.setTstName(rs.getString("TST_NAME"));
newtest.setTstCatagory(rs.getString("TST_CATAGORY"));
newtest.setTstNormalValue(rs.getString("TST_NORMALVAL"));
testList.add(newtest);
}
return testList;
}
catch (SQLException ex)
{
Logger.getLogger(DbHandeler.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
Its output is:
chem
Jul 29, 2014 10:02:28 PM Db.DbHandeler srchInTestsInDb
SEVERE: null
java.sql.SQLSyntaxErrorException: ORA-00904: "CHEM": invalid identifier
When I print "catg" it prints "chem" which I need in my query, but it's not working.
It should be WHERE TST_CATAGORY='"+catg+"'", since a String parameter should be in quotes.
That said, that's a very bad practice, and you run the risk of SQL injection. Use a prepared statement :
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString (1, catg);
ResultSet res = stmt.executeQuery ();;
Oracle is considering CHEM a column name since it isn't quoted. To get Oracle to treat it as a string, use single quotes.
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY='"+catg+"'";
Try:
String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY='"+catg+"';";
Since the content of catg is a String it should also be in quotation marks (in the SQL-Query).
Related
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.
Using Statment, resultSet.getObject returns query plan as xml
Connection conn = getConnection();
String query = " SET SHOWPLAN_XML on ";
Statement st = conn.createStatement();
boolean execute=st.execute(query);
log.info("execute status {} " , execute);
query = " SELECT ATMPROFILES.TERMID as COLUMNID, ATMPROFILES.TERMID as COLUMNNAME FROM ATMPROFILES (NOLOCK) "
+ " WHERE Authprocessname = 'ATMST' "
+ "ORDER BY ATMPROFILES.TERMID ";
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
Object object = rs.getObject(1);
log.info("Query Plan {} ", object);
}
But If I execute the same through PreparedStatement, it returns actual result insteadof QueryPlan
Connection conn = getConnection();
String query = " SET SHOWPLAN_XML on ";
PreparedStatement ps = conn.prepareStatement(query);
boolean execute = ps.execute();
log.info("execute status {} " , execute);
query = " SELECT ATMPROFILES.TERMID as COLUMNID, ATMPROFILES.TERMID as COLUMNNAME FROM ATMPROFILES (NOLOCK) "
+ " WHERE Authprocessname = 'ATMST' "
+ "ORDER BY ATMPROFILES.TERMID ";
ps=conn.prepareStatement(query);
execute=ps.execute();
log.info("execute status {} " , execute);
ResultSet rs = ps.getResultSet();
while(rs.next())
{
Object object = rs.getObject(1);
// here it returns selected object
log.info("Query Plan {} ", object);
}
Any idea to acheive this via PreparedStatement.
I haven't found any reference why executing SET SHOWPLAN_XML ON as a prepared statement will not work; however, you should get the desired results when you run this statement directly and your actual query as a prepared statement. In code:
Connection conn = getConnection();
String showplanQuery = "SET SHOWPLAN_XML ON";
Statement st = conn.createStatement();
st.execute(showplanQuery);
String actualQuery = "SELECT ATMPROFILES.TERMID FROM ATMPROFILES (NOLOCK) ";
PreparedStatement ps=conn.prepareStatement(actualQuery);
ps.execute();
ResultSet rs = ps.getResultSet();
while(rs.next())
{
Object object = rs.getObject(1);
// should log the query plan
log.info("Query Plan {} ", object);
}
Hope that helps.
I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
com.mysql.jdbc.exceptions.jdbc4.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 '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...
I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?
Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.
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 ?)