Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.function.Consumer;
- import java.util.function.Function;
- public class MySQL {
- private static Connection conn;
- public void connect(String host, String database, int port, String user, String password){
- if(!isConnected()){
- try {
- conn = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user, password);
- System.out.println("Connexion etablie avec la base de donnees");
- } catch (SQLException e) {
- e.printStackTrace();
- System.out.println("Connexion refuse avec la base de donnees");
- }
- }
- }
- public void disconnect(){
- if(isConnected()){
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- public static Connection getConnection(){
- return conn;
- }
- public void update(String qry){
- try {
- PreparedStatement s = getConnection().prepareStatement(qry);
- s.executeUpdate();
- } catch(Exception e){
- e.printStackTrace();
- }
- }
- public Object query(String qry, Function<ResultSet, Object> consumer){
- try {
- PreparedStatement s = getConnection().prepareStatement(qry);
- ResultSet rs = s.executeQuery();
- return consumer.apply(rs);
- } catch(SQLException e){
- throw new IllegalStateException(e.getMessage());
- }
- }
- public void query(String qry, Consumer<ResultSet> consumer){
- try {
- PreparedStatement s = getConnection().prepareStatement(qry);
- ResultSet rs = s.executeQuery();
- consumer.accept(rs);
- } catch(SQLException e){
- throw new IllegalStateException(e.getMessage());
- }
- }
- public boolean isConnected(){
- try {
- if((conn == null) || (conn.isClosed()) || (conn.isValid(5))){
- return false;
- }
- return true;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement