SHARE
TWEET

Untitled

a guest Jan 11th, 2019 122 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Connection myConn = null;
  2. PreparedStatement myPrepStmt = null; //<-- PreparedStatement, NOT Statement
  3. ResultSet myRs = null;
  4.  
  5. String dbUrl = "jdbc:mysql://localhost:3306/test2";
  6. String dbUser = "user1";
  7. String dbPassword = "test2";
  8.  
  9. try {
  10.   myConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
  11.   myPrepStmt = myConn.prepareStatement("select * from user where user_id = ?");
  12.   //above this is boilerplate text that is repeated every time I work with JDBC.
  13.   myPrepStmt.setInt(1, id);
  14.   myRs = myPrepStmt.executeQuery();
  15.  
  16.   while(myRs.next()) {
  17.     value = myRs.getString("first_name");
  18.     firstName = myRs.getString("first_name");
  19.     lastName = myRs.getString("last_name");
  20.     System.out.println("First name: " + myRs.getString("first_name") + " Last name: " + myRs.getString("last_name") + " ID: " + myRs.getInt("user_id"));
  21.   }
  22.   //below this is boilerplate text that is repeated every time I work with JDBC.
  23. } catch (Exception e) {
  24.   System.out.println("PROBLEM");
  25.   System.out.println(e.getLocalizedMessage());
  26. } finally {
  27.     if (myRs != null) {
  28.         try {
  29.           myRs.close();
  30.         } catch (SQLException e) { /* ignored */}
  31.     }
  32.     if (myPrepStmt != null) {
  33.         try {
  34.           myPrepStmt.close();
  35.         } catch (SQLException e) { /* ignored */}
  36.     }
  37.     if (myConn != null) {
  38.         try {
  39.           myConn.close();
  40.         } catch (SQLException e) { /* ignored */}
  41.     }
  42. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top