Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Connection myConn = null;
- PreparedStatement myPrepStmt = null; //<-- PreparedStatement, NOT Statement
- ResultSet myRs = null;
- String dbUrl = "jdbc:mysql://localhost:3306/test2";
- String dbUser = "user1";
- String dbPassword = "test2";
- try {
- myConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
- myPrepStmt = myConn.prepareStatement("select * from user where user_id = ?");
- //above this is boilerplate text that is repeated every time I work with JDBC.
- myPrepStmt.setInt(1, id);
- myRs = myPrepStmt.executeQuery();
- while(myRs.next()) {
- value = myRs.getString("first_name");
- firstName = myRs.getString("first_name");
- lastName = myRs.getString("last_name");
- System.out.println("First name: " + myRs.getString("first_name") + " Last name: " + myRs.getString("last_name") + " ID: " + myRs.getInt("user_id"));
- }
- //below this is boilerplate text that is repeated every time I work with JDBC.
- } catch (Exception e) {
- System.out.println("PROBLEM");
- System.out.println(e.getLocalizedMessage());
- } finally {
- if (myRs != null) {
- try {
- myRs.close();
- } catch (SQLException e) { /* ignored */}
- }
- if (myPrepStmt != null) {
- try {
- myPrepStmt.close();
- } catch (SQLException e) { /* ignored */}
- }
- if (myConn != null) {
- try {
- myConn.close();
- } catch (SQLException e) { /* ignored */}
- }
- }
Add Comment
Please, Sign In to add comment