1.在项目src路径下创建一个db.propretoes文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxx?userSSL=false
username=xxx
password=xxx
- url后面的xxx是数据库名
- username后面的xxx是数据库用户名
- password后面的xxx是数据库密码
2.在util包下创建一个DBUtil_Plus类
package com.qfedu.utils;
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
/**
* @Author pengyu
* @Date 2022/8/19 19:36
*/
public class DBUtil_Plus {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String pwd = null;
/**
* 我们可以通过读取properties文件来获取数据库连接
*/
static {
//1.获取properties对象
Properties properties = new Properties();
try {
//2.通过properties对象来读取db.properties文件以流的形式,
// 也就是文件内容会存在于properties对象里面
properties.load(new FileInputStream("db.properties的路径"));
//3.通过properties对象来获取相应的值,key-value键值对,用key来获取值
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
pwd = properties.getProperty("password");
//加载驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() {
Connection conn = null;
try {
//获取数据库连接
conn = DriverManager.getConnection(url, username, pwd);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭资源
public void close(ResultSet rs,Statement s,Connection conn) {
try {
rs.close();
s.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//重载,也是关闭资源
public void close(Statement s,Connection conn) {
try {
s.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3.写一个查询所有用户的方法
public List<User> findAll() {
List<User> list = new ArrayList<>();
Connection conn = dbUtil.getConnection();
String sql = "select * from user";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
User user = new User();
//通过数据库表中的字段名来取值,赋值给user
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setBirthday(rs.getDate("birthday"));
user.setPhone(rs.getString("phone"));
user.setAddress(rs.getString("address"));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
dbUtil.close(rs,ps,conn);
return list;
}
4.测试
import org.junit.jupiter.api.Test;
public class Test02 {
//@Test注解需要导包,在idea中初次使用时按住alt+enter选择5.x版本即可,JUnit4可能会无法使用
//没有主方法依旧可以在控制台出现结果,该注解用于测试
@Test
public void query(){
ServiceImpl service = new ServiceImpl();
List<User> all = service.findAll();
for (User user : all) {
System.out.println(user);
}
}
}
一起学习,共同成长