Advertisement
Guest User

Untitled

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