




引入mysql驱动依赖,一般会建个lib包,如果是java web项目 一般将以来包创建在web->WEB-INF下,
这里我就随便了


建议
try {
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
}
的写法,这里就简写了

写个工具类
public class DBUtil {
static{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取数据库连接对象 抛异常,谁使用,谁负责
public static Connection getConnection(String url,String username,String password) throws SQLException {
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
/**
* 释放资源
* @param conn 数据库连接对象
* @param st 执行对象
* @param rs 结果集对象
*/
public static void close(Connection conn, Statement st, ResultSet rs){
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
上面工具类的坏处就是换数据库驱动要改源码,改进下
在src下新建个文件夹 resource 如果不能创建,简单粗暴的方式,

创建个jdbc.properties文件,名字随意

新建个类DBUtil1,ResourceBundle会读resource目录下的文件
public class DBUtil1 {
//静态变量:在类加载时候执行,并且是有先后顺序的.自上而下
private static ResourceBundle bundle=ResourceBundle.getBundle("resource.jdbc");
private static String driver=bundle.getString("driver");
private static String url=bundle.getString("url");
private static String username=bundle.getString("username");
private static String password=bundle.getString("password");
static{
//注册驱动(注册却动只需要注册一次,放在静态代码块当中.DBUtil1类加载的时候执行)
try {
//"com.mysql.jdbc.Driver"是连接数据库的驱动,不能写死,因为可能以后改成Oracle数据库
//如果连接Oracle数据库的时候,还需要修改java代码,显然违背OCP开闭原则
//OCP开闭原则:对扩展开发,对修改关闭.(什么是复合OCP呢?在进行功能扩展的时候,不需要修改java源代码)
//Class.forName("com.mysql.cj.jdbc.Driver");
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取数据库连接对象 抛异常,谁使用,谁负责
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
//关闭连接 释放资源
/**
* 释放资源
* @param conn 数据库连接对象
* @param st 执行对象
* @param rs 结果集对象
*/
public static void close(Connection conn,Statement st,ResultSet rs){
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
新建个类Test1测试

public class Test1 {
public static void main(String[] args) throws SQLException {
// Connection connection = DBUtil1.getConnection();
// System.out.println(connection);
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn = DBUtil1.getConnection();
String sql="select * from user";
ps=conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil1.close(conn, ps, rs);
}
}
}



















