Advertisement
Guest User

Untitled

a guest
Dec 12th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. public class Database {
  2. private String user;
  3. private String database;
  4. private String password;
  5. private String port;
  6. private String hostname;
  7. private Connection connection;
  8.  
  9. public void setup(){
  10. try{
  11. // Tak jak mówiłem, te wartości NIE powinny być bezpośrednio w kodzie.
  12. hostname = "localhost";
  13. port = "3306"; //3306 to domyślny port
  14. database = "testdb";
  15. user = "szymi";
  16. password = "czacha Ci dymi";
  17.  
  18. createTestTable();
  19. } catch(Exception e){
  20. e.printStackTrace();
  21. }
  22. }
  23.  
  24. public Connection getConnection() {
  25. try{
  26. if (connection != null && !connection.isClosed())
  27. return connection;
  28.  
  29. String connectionURL = "jdbc:mysql://" + hostname + ":" + port;
  30. if (database != null)
  31. connectionURL = connectionURL + "/" + database;
  32.  
  33. Class.forName("com.mysql.jdbc.Driver");
  34. connection = DriverManager.getConnection(connectionURL, user, password);
  35. return connection;
  36. } catch(Exception e){
  37. e.printStackTrace();
  38. }
  39. return null;
  40. }
  41.  
  42. private void createTestTable() throws SQLException{
  43. if(!getConnection().getMetaData().getTables(null, null, "gracze", null).next()){
  44. Statement statement = getConnection().createStatement();
  45. statement.executeUpdate("CREATE TABLE `gracze` ("
  46. + "`nick` VARCHAR(36) PRIMARY KEY NOT NULL,"
  47. + "`haslo` VARCHAR(128) NOT NULL,"
  48. + "`isModerator` BIT,"
  49. + "`ranga` ENUM('Gracz', 'Premium', 'Szlachcic') NOT NULL)");
  50. statement.executeUpdate("ALTER TABLE gracze ADD INDEX (nick)");
  51. statement.close();
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement