So, your actual problem is that you did not know how to set the values โโ/ parameters in the SQL query? The only right way to do this is PreparedStatement .
String sql = "select * from Customers where Cust_ID = ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setLong(custId); resultSet = preparedStatement.executeQuery();
It not only simplifies the installation of Java objects ( String , Long , Integer , Date , InputStream , etc.) in the SQL query, but, most importantly, it will save you from SQL Injection risks . Further, it is also faster than a Statement , because it is precompiled.
As for your code logic, you should always close database resources in the reverse order in the finally block to avoid resource leaks in case of exceptions. Here is a basic example of how to get Customer right JDBC path:
public Customer find(Long customerId) throws SQLException { String sql = "SELECT id, name, age FROM customer WHERE id = ?"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Customer customer = null; try { connection = getConnectionSomehow(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setLong(custId); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { customer = new Customer(); customer.setId(resultSet.getLong("id")); customer.setName(resultSet.getString("name")); customer.setAge(resultSet.getInteger("age")); } } finally { if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {} if (preparedStatement != null) try { preparedStatement.close(); } catch (SQLException ignore) {} if (connection != null) try { connection.close(); } catch (SQLException ignore) {} } return customer; }
You can find this tutorial to get more ideas and examples.
Balusc
source share