连接MYSQL数据库
1.在项目中加载jdbc的jar包
地址
工具地址: https://blog.csdn.net/qq_37654578/article/details/87487503
package com.scem.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
* DB类
*/
public class DBManager {
// 定义驱动地址
private static final String DRIVER = "com.mysql.jdbc.Driver";
// 定义数据库地址 本地数据库
private static final String URL = "jdbc:mysql://localhost:3306/patientsdb";
// 定义用户名
private static final String USER = "root";
// 定义连接密码
private static final String PASSWORD = "1234";
// 定义连接对象
private static Connection conn = null;
/**
* 打开数据库
*
* @return 返回连接对象
*/
public static Connection getConn() {
// 加载驱动
try {
Class.forName(DRIVER);
// 获取连接对象
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭资源对象
*/
public static void closeAll(ResultSet rst, PreparedStatement pst,
Connection conn) {
if (rst != null) {
try {
rst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}