×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Lê hoàng Dương
Added: Oct 9, 2021 9:20 AM
Views: 2448
Tags: no tags
  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 Bai8.connect;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.SQLException;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13.  
  14. /**
  15.  *
  16.  * @author HAI TU
  17.  */
  18. public class MyConnection {
  19.     private static final MyConnection instance = new MyConnection();
  20.     private MyConnection(){
  21.         this.dbName = "qlsv";
  22.        
  23.     }
  24.     String hostName = "localhost";
  25.     String dbName;
  26.     String userName = "root";
  27.     String password = "";
  28.     String url = "jdbc:mysql://" + hostName + ":3306/" + dbName;
  29.     Connection conn = null;
  30.     public static MyConnection getInstance(){
  31.         return instance;
  32.     }
  33.     public Connection getConnection(){
  34.         if(conn == null){
  35.             conn = open();
  36.         }
  37.         return conn;
  38.     }
  39.     private Connection  open(){
  40.         try {
  41.             Class.forName("com.mysql.jdbc.Driver");
  42.             conn = DriverManager.getConnection(url, userName, password);
  43.         } catch (ClassNotFoundException | SQLException ex) {
  44.         }
  45.         return conn;
  46.     }
  47.     private void close(){
  48.         try {
  49.             if(conn != null){
  50.                 conn.close();
  51.             }
  52.         } catch (SQLException e) {
  53.         }
  54.     }
  55.     public static void main(String[] args) {
  56.         MyConnection myConnection = MyConnection.getInstance();
  57.         Connection conn = myConnection.getConnection();
  58.         if(conn != null){
  59.             System.out.println("Thành công");
  60.         } else{
  61.             System.out.println("Không thành công");
  62.         }
  63.     }
  64. }
  65.