Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. import java.sql.DriverManager;
  2. import java.sql.SQLException;
  3. import java.sql.Statement;
  4.  
  5. import java.sql.Connection;
  6.  
  7. import java.sql.ResultSet;
  8.  
  9. public class DatabaseHandler {
  10. private Connection dbConnection = null;
  11. private String computer, db_name, userName, password, url;
  12.  
  13. DatabaseHandler() {
  14. computer = "atlas.dsv.su.se";
  15. db_name = "db_10746419";
  16. userName = "usr_10746419";
  17. password = "746419";
  18.  
  19. try {
  20. dbConnection = obtainConnection(computer, db_name, userName, password);
  21. } catch (SQLException e) {
  22. e.printStackTrace();
  23. } catch (InstantiationException e) {
  24. e.printStackTrace();
  25. } catch (IllegalAccessException e) {
  26. e.printStackTrace();
  27. } catch (ClassNotFoundException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31.  
  32. public Connection obtainConnection(String computer,
  33. String db_name, String userName, String password)
  34. throws SQLException, InstantiationException,
  35. IllegalAccessException, ClassNotFoundException {
  36.  
  37. url = "jdbc:mysql://" + computer + "/" + db_name;
  38. Class.forName("com.mysql.jdbc.Driver").newInstance();
  39. return DriverManager.getConnection(url, userName, password);
  40.  
  41. }
  42. public java.sql.ResultSet executeQuery(String sql){
  43. Statement statement = null;
  44. ResultSet resultSet = null;
  45. try {
  46. statement = dbConnection.createStatement();
  47.  
  48. if(statement.execute(sql)){
  49. return statement.getResultSet();
  50.  
  51. } else return null; // if query updates or inserts data.
  52.  
  53. } catch (SQLException e) {
  54. e.printStackTrace();
  55. return null;
  56. }
  57. finally {
  58. if(resultSet != null)
  59. try {
  60. resultSet.close();
  61. } catch (SQLException e) {
  62. e.printStackTrace();
  63. }
  64. if(statement != null)
  65. try {
  66. statement.close();
  67. } catch (SQLException e) {
  68.  
  69. e.printStackTrace();
  70. }
  71.  
  72. }
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement