Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package GestioneDatabase_sql;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- /**
- *
- * @author mstc
- */
- public class Connessione {
- private String JDBC_DRIVER = "com.mysql.jdbc.Driver";
- private String DB_URL = "jdbc:mysql://localhost/";
- // Database credentials
- private String USER = "root";
- private String PASS = "";
- private Connection conn = null;
- private Statement stmt = null;
- private ResultSet rs;
- public String errore="";
- /**
- * Crea una connessione al database avente User "root"
- * e password vuota
- * @param NomeDB
- */
- public Connessione(String NomeDB){
- this.DB_URL=this.DB_URL+NomeDB;
- }
- /**
- *
- * @param NomeDB
- * @param Password
- */
- public Connessione(String NomeDB,String User,String Password){
- if (User!=null){
- this.USER=User;
- }
- this.DB_URL=this.DB_URL+NomeDB;
- this.PASS=Password;
- }
- public int apriDatabase(){
- try {
- //STEP 2: Register JDBC driver
- Class.forName(JDBC_DRIVER);
- } catch (ClassNotFoundException ex) {
- errore=ex.getMessage();
- System.out.println("errore Connessione1");
- return 1;
- }
- //STEP 3: Open a connection
- System.out.println("Connessione Database...");
- try {
- conn = DriverManager.getConnection(DB_URL,USER,PASS);
- } catch (SQLException ex) {
- errore=ex.getMessage();
- System.out.println("errore Connessione2");
- return 2;
- }
- //STEP 4: Execute a query
- System.out.println("Creating statement...");
- try {
- stmt = conn.createStatement();
- } catch (SQLException ex) {
- errore=ex.getMessage();
- System.out.println("errore Connessione3");
- return 2;
- }
- return 0;
- }
- public Statement getStatement(){
- return this.stmt;
- }
- public ResultSet getResultSet(){
- this.rs=rs;
- return this.rs;
- }
- public void setResultSet(ResultSet rs){
- this.rs=rs;
- }
- public int chiudiDatabase(){
- try {
- if(rs!=null)
- rs.close();
- if(stmt!=null)
- stmt.close();
- if(conn!=null)
- conn.close();
- } catch (SQLException ex) {
- this.errore=ex.getMessage();
- System.out.println("errore Connessione4");
- }
- return 0;
- }
- public Errore Errori(int N){
- return Errore.values()[N];
- }
- private enum Errore{NessunErrore,ClassNotFoundException,SQLException}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement