首页 > 代码库 > Mysql--JDBC的基础

Mysql--JDBC的基础

针对自己jdbc总是记不住的问题,我决定写在博客上,每天都看看--

完整可行的例子:

第一点:

连接jdbc

    public static String jdbc_url = "jdbc:mysql://XXXXXXX:3306/mlhx_log_1?useUnicode=true&autoReconnect=true&characterEncoding=UTF-8&allowMultiQueries=true";
    public static final String usr_name = "xgame";
    public static final String usr_pass = "qingyouyile2013123456";
    private Connection con = null;
    private Statement stmt = null;

    public void init() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(jdbc_url, usr_name, usr_pass);
            stmt = con.createStatement();
            System.out.println("connect succ !");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("connect problem ");
            e.printStackTrace();
        }
    }

 第二点:

执行sql语句

public ResultSet execute(String sql) {
        try {
            return stmt.executeQuery(sql);
        } catch (SQLException e) {
            System.out.println("query problem: " + sql);
            e.printStackTrace();
        }
        return null;
    }

 

 第三点:

关掉连接

    public void close(){
        try {
            stmt.close();
            con.close();
            System.out.println("close succ!");
        } catch (SQLException e) {
            System.out.println("close Exception!");
            e.printStackTrace();
        }
    }

 

Mysql--JDBC的基础