Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. package edu.ap.jdbc;
  2.  
  3. import java.util.ArrayList;
  4. import java.sql.*;
  5.  
  6. public class JDBConnection {
  7.  
  8. private static JDBConnection instance = null;
  9. private Connection conn = null;
  10.  
  11. private JDBConnection() {}
  12.  
  13. public static synchronized JDBConnection getJDBConnection() {
  14.  
  15. if(instance == null) {
  16. instance = new JDBConnection();
  17. }
  18. return instance;
  19. }
  20.  
  21. public void openConnection(String database, String user, String pwd) {
  22.  
  23. try {
  24. Class.forName("com.mysql.jdbc.Driver");
  25. String url = "jdbc:mysql://127.0.0.1/" + database;
  26. conn = DriverManager.getConnection (url, "root", "");
  27. }
  28. catch (Exception e) {
  29. System.out.println(e);
  30. }
  31. }
  32.  
  33. public void closeConnection() {
  34.  
  35. if (conn != null) {
  36. try {
  37. conn.close();
  38. }
  39. catch (SQLException ex) {
  40. System.out.println("Error: " + ex);
  41. }
  42. }
  43. }
  44.  
  45. public void executeInsert(String sql) {
  46.  
  47. try {
  48. Statement stmt = conn.createStatement();
  49. stmt.executeUpdate(sql);
  50. stmt.close();
  51. }
  52. catch(SQLException ex) {
  53. System.out.println("Error: " + ex);
  54. }
  55. }
  56.  
  57. public ArrayList<String> selectAll(String sql) {
  58.  
  59. ResultSet rs = null;
  60. ArrayList<String> result = new ArrayList<String>();
  61. try {
  62. Statement stmt = conn.createStatement();
  63. rs = stmt.executeQuery(sql);
  64. while(rs.next()) {
  65. result.add(rs.getString(1) + ";" + rs.getString(2)+ ";" + rs.getString(3)+";"+rs.getInt(4));
  66. }
  67. stmt.close();
  68. }
  69. catch(SQLException ex) {
  70. System.out.println("Error: " + ex);
  71. }
  72.  
  73. return result;
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement