I am trying to run the below jdbc code to get the object key:
String sqlSelectObjKey = "select OBJ_KEY from obj where OBJ_NM=? and OBJ_TYP_CD='CONN';";
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = connection.prepareStatement(stmtSelectObjKey);
statement.setString(1, "Postal Connector");
rs = statement.executeQuery(stmtSelectObjKey);
while(rs.next()) {
this.executionLog.setObjKey(rs.getInt("OBJ_KEY"));
}
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
if (rs != null) try { rs.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
}
But every time it results in below exception:
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 '? and OBJ_TYP_CD='CONN'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1446)
at appMetadata.ConnectorMetadataLoad.insertExecutionLog(ConnectorMetadataLoad.java:67)
at appCore.PostalCodeInterface.getPostalData(PostalCodeInterface.java:37)
at appMain.PostalDataConnector.getPostalData(PostalDataConnector.java:19)
at PostalDemo.main(PostalDemo.java:14)
Removing the place holder and setting the value directly works fine.
I am not sure where the syntax is wrong, I will appreciate if anyone can point out the error.
?is the correct placholder??is problematic. It looks like the?is not replaced by the string argument.executeQuery()with no args. As a side note, you should also use a placeholder for the second 'CONN'.