Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static DataSource getMySQLDataSource() { // Funkar denna som connect
- MysqlDataSource mysqlDS = null;
- try {
- mysqlDS = new MysqlDataSource();
- mysqlDS.setURL("jdbc:mysql://localhost:3306/mydb");
- mysqlDS.setUser("root");
- mysqlDS.setPassword("");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return mysqlDS;
- }
- public Connection getConnection() throws SQLException {
- Connection connection = null;
- // Get the MySqlDataSource
- DataSource dataSource = getMySQLDataSource();
- // Get connection from the database
- connection = dataSource.getConnection();
- return connection;
- }
- private int getUserID(int inputUserID) {
- PreparedStatement prstmt = null;
- int userID = 0;
- Connection connection = null;
- try {
- connection = getConnection();
- // Execute query
- // egentligen ska prepareStatement innehålla "GET_USERNAME
- String sql = "SELECT userName FROM USER WHERE userID = ?";
- prstmt = connection.prepareStatement(sql);
- prstmt.setInt(1, inputUserID);
- ResultSet rs = prstmt.executeQuery();
- while (rs.next()) {
- // Retrieve by column name
- userID = rs.getInt("userID");
- // Display values
- System.out.println("userID" + userID);
- }
- rs.close();
- } catch (SQLException se) {
- se.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- finally {
- // Finally block used to close resources
- closePrstmt(prstmt);
- closeConnection(connection);
- }
- return userID;
- }
- public void closePrstmt(PreparedStatement prstmt){
- try {
- if (prstmt != null) {
- prstmt.close();
- }
- } catch (SQLException sqlException) {
- sqlException.printStackTrace();
- }
- }
- public void closeConnection(Connection connection){
- try {
- if (connection != null) {
- connection.close();
- }
- } catch (SQLException sqlException) {
- sqlException.printStackTrace();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement