Haifisch7734

DatabaseConnection

Sep 3rd, 2015
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package com.mallsystem.server.database;
  7.  
  8. import java.sql.*;
  9. import java.util.ArrayList;
  10. import com.mallsystem.server.mallsystemserver.Config;
  11. import com.mallsystem.net.packets.data.Row;
  12.  
  13. /**
  14. *
  15. * @author Łukasz
  16. */
  17. public class DatabaseConnection {
  18. private static DatabaseConnection dbc;
  19. private Connection conn;
  20.  
  21. private DatabaseConnection() throws SQLException
  22. {
  23. conn = DriverManager.getConnection(
  24. "jdbc:oracle:thin:@" + Config.DB_HOST + ":" + Config.DB_PORT + ":" + Config.DB_SID, Config.DB_USER, Config.DB_PASS);
  25. }
  26.  
  27. public static DatabaseConnection getInstance() throws SQLException
  28. {
  29. if (dbc != null)
  30. return dbc;
  31. else
  32. return dbc = new DatabaseConnection();
  33. }
  34.  
  35. public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException
  36. {
  37. ResultSetMetaData md = rs.getMetaData();
  38. int columns = md.getColumnCount();
  39. ArrayList <Row> list = new ArrayList<>();
  40.  
  41. while (rs.next())
  42. {
  43. Row row = new Row(columns);
  44.  
  45. for(int i=1; i<=columns; ++i)
  46. row.put(md.getColumnName(i),rs.getObject(i));
  47.  
  48. list.add(row);
  49. }
  50.  
  51. return list;
  52. }
  53.  
  54. public ArrayList query(String q) throws SQLException
  55. {
  56. ArrayList <Row> list;
  57.  
  58. try (Statement st = conn.createStatement()) {
  59. ResultSet rs = st.executeQuery(q);
  60. list = resultSetToArrayList(rs);
  61. }
  62.  
  63. return list;
  64. }
  65.  
  66. public void execute(String q) throws SQLException
  67. {
  68. try (Statement st = conn.createStatement()) {
  69. st.executeUpdate(q);
  70. }
  71. }
  72.  
  73. public void commit() throws SQLException
  74. {
  75. conn.commit();
  76. }
  77.  
  78. public void rollback() throws SQLException
  79. {
  80. conn.rollback();
  81. }
  82.  
  83. public void close() throws SQLException
  84. {
  85. conn.close();
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment