Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sql;
- //aici astea vin incluse
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Connection;
- public class DatabaseConnection {
- private String driver= "com.mysql.jdbc.Driver"; //asta ii de pe net il pun in biblioteci.adica ii un fisier si il includ
- private String dbName= "hospital"; //nume db creataa inainte
- private String connectionURL = "jdbc:mysql://localhost:3306/"; //psth db, asa ar trebui sa fie
- private String username="root"; //cum am pus la mysql
- private String password = "Best"; //parola aleasa de mine
- /**
- * @author Andreea Maria GUI
- * the private Constructor of @DatabaseConnection
- */
- private DatabaseConnection() { // is alea incluse sus
- try{
- Class.forName(driver); // asa ii sa fie conectat, is pe acolo prin includes
- System.out.println("Database successfully connected!");
- }
- catch(Exception e) {
- e.printStackTrace();
- };
- }
- private static DatabaseConnection instance = new DatabaseConnection(); //o instanta, instanta din propria clasa asta
- /**
- *
- * @return the created connection which is private in order not to open more than one connection at the same time
- * @throws Exception
- */
- private Connection createConnection() throws Exception{ // bibliotecile
- Connection connection = DriverManager.getConnection(connectionURL+dbName, username, password); //asa ii
- return connection;
- }
- /**
- *
- * @return the connection created especially for our instance object of DatabaseConnection class; this is the public method that gives the connection
- * to the database
- */
- public static Connection getConnection() { // getter
- try {
- return instance.createConnection();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- return null;
- }
- }
- /**
- * the public method for closing the connection
- */
- public static void closeConnection() { // important sa inchi mereu
- try {
- instance.createConnection().close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- DatabaseConnection db = new DatabaseConnection();
- try {
- Connection conn = db.getConnection();
- System.out.println("Database successfully connected!");
- conn.close();
- }catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement