目录
导包:
打开项目结构界面,点击库,导入包即可
加载驱动:
将获取数据库三要素,存储在文件中,通过IO流读取即可
加载 JDBC 驱动需调用 Class 类的静态方法 forName()
//加载配置文件
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbcproperties");
Properties pp = new Properties();
pp.load(is);
//读取配置信息
String user = pp.getProperty("user");
String password = pp.getProperty("password");
String url = pp.getProperty("url");
String driverClass = pp.getProperty("driverClass");
//加载驱动
Class.forName(driverClass);
获取连接:
通过DriverManager.registerDriver() 方法来获取实例
//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
预编译sql语句:
//预编译sql语句,返回PreparedStatement实例
ps = conn.prepareStatement(sql);//个人理解为完整版的sql语句
填充占位符:
//填充占位符
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
执行:(查询操作额外步骤)
增删改:
//执行
ps.execute();
查询:
//执行,获取结果集
rs = ps.executeQuery();
//获取结果集的元数据
ResultSetMetaData rsmd = rs.getMetaData();
//获取列数
int columnCount = rsmd.getColumnCount();
//创建集合对象
ArrayList<T> al = new ArrayList<T>();
//操作数据
while (rs.next()) {
//创建行对象
T t = clazz.newInstance();
for (int i = 0; i < columnCount; i++) {
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取列的别名
String columnLabel = rsmd.getColumnLabel(i + 1);
//通过反射,给对象的属性赋值
Field field = Order.class.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
}
al.add(t);
}
资源关闭:
//资源关闭
try {
if (ps != null) {
ps.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (rs != null) {
rs.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}