Pacific-Design.com

    
Home Index

1. Java

2. MySQL

Java / MySQL /

Java MySQL

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

/*------------------------------------------------------------------------------------------------*/
public class BaseMySQL {

    protected Connection connection;
    protected Statement statement;
    protected ResultSet result;

    /*--------------------------------------------------------------------------------------------*/
    public BaseMySQL() {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://192.168.0.1:3306/youtube?user=root&password=pass");
            statement = connection.createStatement();
        } catch (ClassNotFoundException | SQLException e) {
            System.err.println(e);
        }
    }

    /*--------------------------------------------------------------------------------------------*/
    public ResultSet query(String query) {

        try {
            statement = connection.createStatement();
            result = statement.executeQuery(query);
        } catch (SQLException ex) {
            System.err.println("query: " + ex.getMessage());
        }
        return result;
    }

    /*--------------------------------------------------------------------------------------------*/
    public int insert(String insertQuery) {

        int total = 0;
        try {
            statement = connection.createStatement();
            total = statement.executeUpdate(insertQuery);

        } catch (SQLException ex) {
            System.err.println("insert: " + ex.getMessage());
        }
        return total;

    }

    /*--------------------------------------------------------------------------------------------*/

    public void close() {

        try {
            if (result != null) {
                result.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }

        } catch (SQLException ex) {
            System.err.println("close: " + ex.getMessage());
        }
    }
    /*--------------------------------------------------------------------------------------------*/
}

pom.xml

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>