public class Test01 {
public static void main(String[] args) {
//1.准备工作
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
//2.从配置文件中获取驱动,url路径,用户名和密码;getBundle("db")文件名不要带后缀名
//ResourceBundle对象专门用于获取配置文件,采用键值对方式存储数据
ResourceBundle resourceBundle = ResourceBundle.getBundle("db");
String className = resourceBundle.getString("className");
String url = resourceBundle.getString("url");
String name = resourceBundle.getString("name");
String password = resourceBundle.getString("password");
try {
//3.注册驱动
Class.forName(className);
//4.获取数据库链接对象
conn = DriverManager.getConnection(url, name, password);
//5.编写sql语句
String sql = "select * from student";
//6.获取sql语句操作对象
stmt = conn.prepareStatement(sql);
//7.执行sql语句
rs = stmt.executeQuery();
//8.处理结果集
//获取数据库字段个数
int columnCount = rs.getMetaData().getColumnCount();
//rs.next() 类似于迭代器,一个是可以判断结果集还有没有数据,
//一个是可以移动指针
while (rs.next()) {
//打印一行数据
for (int i = 1; i <= columnCount; i++) {
System.out.print(rs.getObject(i) + "\t");
}
//换行
System.out.println();
}
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException(e);
}
//9.关闭资源,关闭资源顺序和使用资源的顺序相反,
//因为后面的资源使用是在前面的资源的基础上进行的,所以先关后面的。
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
}
db.properties
className=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/school name=root password=root注:如果是MySQL8以后的版本要用 com.mysql.cj.jdbc.Driver,
MySQL5的用com.mysql.jdbc.Driver
配置文件存放目录应为src的根目录