MySQL连接Demo

1.引入jar包
mysql-connector-java-8.0.11.jar
2. 创建一个工具类获取Connection

public class JDBCUtils {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    static {
        try {
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            InputStream is = classLoader.getResourceAsStream("db.properties");
            Properties prop = new Properties();
            prop.load(is);
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        Connection conn = null;
        try {
            //加载驱动
            Class.forName(driver);
            //通过获取连接
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;

    }
}

3…编写数据库登录配置文件db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3307/user?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong
user=root
password=123456

注:driver的路径具体根据引入的jar包决定(打开jar包寻找到Driver类)

猜你喜欢

转载自blog.csdn.net/qq_37325256/article/details/80636302