Advertisement
Guest User

Untitled

a guest
May 1st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1.  
  2.     public static final String GET_USERNAME = "SELECT userName FROM USER WHERE userID = ?";
  3.  
  4. public static DataSource getMySQLDataSource() { // Funkar denna som connect
  5.         MysqlDataSource mysqlDS = null;
  6.  
  7.         try {
  8.             mysqlDS = new MysqlDataSource();
  9.             mysqlDS.setURL("jdbc:mysql://localhost:3306/mydb");
  10.             mysqlDS.setUser("root");
  11.             mysqlDS.setPassword("");
  12.  
  13.         } catch (Exception e) {
  14.             e.printStackTrace();
  15.         }
  16.         return mysqlDS;
  17.     }
  18.  
  19.     private void getUserInformation(int inputUserID) {
  20.         Connection connection = null;
  21.         PreparedStatement prstmt = null;
  22.  
  23.         // Get the MySqlDataSource
  24.  
  25.         DataSource dataSource = getMySQLDataSource();
  26.         try {
  27.  
  28.             // Get connection from the database
  29.  
  30.             connection = dataSource.getConnection();
  31.  
  32.             // Execute query
  33.  
  34.             prstmt = connection.prepareStatement(GET_USERNAME);
  35.  
  36.             prstmt.setInt(1, inputUserID);
  37.  
  38.             ResultSet rs = prstmt.executeQuery();
  39.  
  40.             while (rs.next()) {
  41.  
  42.                 // Retrieve by column name
  43.  
  44.                 int userID = rs.getInt(userID);
  45.  
  46.                 // Display values
  47.  
  48.                 System.out.println("userID" + userID);
  49.  
  50.             }
  51.             rs.close();
  52.         } catch (SQLException se) {
  53.             se.printStackTrace();
  54.         } catch (Exception e) {
  55.             e.printStackTrace();
  56.         }
  57.  
  58.         // catch (SQLException e) {
  59.         // e.printStackTrace();
  60.         // }
  61.  
  62.         finally {
  63.             // Finally block used to close resources
  64.             try {
  65.                 if (prstmt != null) {
  66.                     prstmt.close();
  67.                 }
  68.             } catch (SQLException sqlException) {
  69.                 sqlException.printStackTrace();
  70.             }
  71.             try {
  72.                 if (connection != null) {
  73.                     connection.close();
  74.                 }
  75.             } catch (SQLException sqlException) {
  76.                 sqlException.printStackTrace();
  77.             }
  78.         }
  79.  
  80.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement