Sie sind auf Seite 1von 2

/*

* 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.
*/
package tugasakhir;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author hp
*/
public class Database {

public Connection koneksi;

public Database(){

}

public Connection getConn(){
return koneksi;
}

public PreparedStatement prepState(String query)throws SQLException, Illegal
StateException{
PreparedStatement prst = koneksi.prepareStatement(query);
return prst;
}

public void connectFirst() throws SQLException{
String server = "localhost", db="pemetaandigilib", user = "root", pass =
"";
getConnection(server, db, user, pass);
if(isConnected()){
System.out.println("Connected");
}
else{
System.out.println("Not Connected");
}
}
public boolean isConnected() {
if(koneksi != null){
return true;
}
return false;
}

public boolean getConnection(String server, String db, String user, String p
ass)throws SQLException, IllegalStateException{
this.destroyConnection();
String dbDriver = "com.mysql.jdbc.Driver";
String dbUrl = "jdbc:mysql://" + server + "/" + db;
try{
Class.forName(dbDriver);
koneksi = DriverManager.getConnection(dbUrl, user, pass);
return true;
}
catch(ClassNotFoundException ex){

}
catch(SQLException ex){

}
return false;

}
public void destroyConnection()throws SQLException, IllegalStateException{
if(koneksi != null){
koneksi.close();
koneksi = null;
}
}

public ResultSet executeSelect(String query) throws SQLException, IllegalSta
teException {
Statement stm;
ResultSet rs = null;
stm = koneksi.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stm.executeQuery(query);
return rs;
}
public Statement createStat() throws SQLException {
return koneksi.createStatement();
}
public int executeUpdate(String query) throws SQLException, IllegalStateExce
ption {
Statement stmt;
if (koneksi == null) {
return 0;
}
stmt = koneksi.createStatement();
return stmt.executeUpdate(query);
}
}