JDBC 连接数据库之单例模式

JDBC 连接数据库之单例模式

package com.rocky.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbUtil {

    private static final String URL = "jdbc:mysql://127.0.0.1:3306/rocky";
    private static final String USER = "root";
    private static final String PASSWORD = null;
    private static Connection conn = null;
    static {
        try {
            // 加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            // 获取数据库的连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static Connection getConnection() {
        return conn;
    }

    public static void main(String[] args) throws SQLException {

        // // 加载驱动程序
        // Class.forName("com.mysql.jdbc.Driver");
        // //获取数据库的连接
        // Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        DbUtil db = new DbUtil();
        Connection conn = db.getConnection();

        Statement sta = conn.createStatement();
        ResultSet result = sta.executeQuery("select uses_name,age from rocky_goddess");
        while (result.next()) {
            System.out.println(result.getString("uses_name") + " " + result.getInt("age"));
        }
    }

}

你可能感兴趣的:(个人经验,数据库,jdbc,java,mysql,单例模式)