1 定义配置文件
创建自定义xml 文件, 保存 数据库连接信息
jdbc-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <jdbc> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/db5? characterEncoding=UTF-8</property> <property name="user">root</property> <property name="password">123456</property> </jdbc>
2 编写工具类(配置式)
编写工具类 ,使用xpath 读取数据库信息
public class JDBCUtils {
//1. 定义字符串变量, 记录获取连接所需要的信息
public static String DRIVERNAME;
public static String URL;
public static String USER;
public static String PASSWORD;
//2.静态代码块
static {
try {
//使用 xpath读取 xml中的配置信息
SAXReader sr = new SAXReader();
Document document =
sr.read("H:\workspace01\JDBC_day02\src\com\lagou\xml03\jdbc-config.xml");
Node node =
document.selectSingleNode("/jdbc/property[@name='driverClass']");
//System.out.println(node.getText());
DRIVERNAME = node.getText();
URL =
document.selectSingleNode("/jdbc/property[@name='jdbcUrl']").getText();
USER =
document.selectSingleNode("/jdbc/property[@name='user']").getText();
PASSWORD =
document.selectSingleNode("/jdbc/property[@name='password']").getText();
//注册驱动
Class.forName(DRIVERNAME);
} catch (Exception e) {
e.printStackTrace();
}
}
//3.获取连接的静态方法
public static Connection getConnection(){
try {
//获取连接对象
Connection connection = DriverManager.getConnection(URL, USER,
PASSWORD);
//返回连接对象
return connection;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
3 测试工具类
测试 : 获取所有员工的姓名
//获取所有员工的姓名
public static void main(String[] args) {
try {
//1.获取连接
Connection connection = JDBCUtils.getConnection();
//2.获取 statement ,执行SQL
Statement statement = connection.createStatement();
String sql = "select * from employee";
//3.处理结果集
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
String ename = resultSet.getString("ename");
System.out.println(ename);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
4 XML - 练习