
目录
导包:
加载驱动:
获取连接:
预编译sql语句:
填充占位符:
执行:(查询 *** 作额外步骤)
增删改:
查询:
资源关闭:
导包:
加载驱动:打开项目结构界面,点击库,导入包即可
将获取数据库三要素,存储在文件中,通过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 al = new ArrayList();
// *** 作数据
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();
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)