Guest User

Untitled

a guest
Jul 15th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. package DB;
  2. import java.sql.*;
  3.  
  4. public class DatabaseConnection {
  5.  
  6. private static final DatabaseConnection _instance = new DatabaseConnection( );
  7.  
  8. public static DatabaseConnection getInstance()
  9. {
  10. return _instance;
  11. }
  12.  
  13. private static final String DatabaseName = "test";
  14. private static final String DatabaseUsername = "root";
  15. private static final String DatabasePassword = "101010";
  16. private static final String DatabaseHost = "localhost";
  17.  
  18.  
  19. private Connection _databaseConnection;
  20.  
  21. private DatabaseConnection()
  22. {
  23. // String connectionUrl = String.format( "jdbc:mysql:///%s", DatabaseName );
  24. String connectionUrl = String.format( "jdbc:mysql://%s/%s", DatabaseHost, DatabaseName );
  25.  
  26. try {
  27. _databaseConnection = DriverManager.getConnection( connectionUrl, DatabaseUsername, DatabasePassword );
  28. }
  29. catch ( SQLException e ) {
  30. e.printStackTrace( );
  31. }
  32. }
  33.  
  34. public Connection getConnection()
  35. {
  36. return _databaseConnection;
  37. }
  38.  
  39. public ResultSet executeQuery( String query )
  40. {
  41. try {
  42. return _databaseConnection.createStatement( ).executeQuery( query );
  43. }
  44. catch ( SQLException e ) {
  45. e.printStackTrace( );
  46. return null;
  47. }
  48. }
  49.  
  50. public int executeUpdate( String query )
  51. {
  52. try {
  53. return _databaseConnection.createStatement( ).executeUpdate( query );
  54. }
  55. catch ( SQLException e ) {
  56. e.printStackTrace( );
  57. return -1;
  58. }
  59. }
  60.  
  61.  
  62. public static void main(String[] args) throws SQLException {
  63. String id = null;
  64. String nume = null;
  65. DatabaseConnection.getInstance().getConnection();
  66. ResultSet re =getInstance().executeQuery("SELECT * FROM `test`.`clients`;");
  67. while (re.next())
  68. try{
  69. id = re.getString("idClients");
  70. nume = re.getString("Name");
  71. }
  72.  
  73. catch (SQLException e ) {
  74. e.printStackTrace( );
  75. }
  76. System.out.println("id="+id+" nume="+nume);
  77.  
  78. }
  79. }
Add Comment
Please, Sign In to add comment