使用PreparedStatement实现增删改、查操作
作者:互联网
- 获取数据库的连接
public static Connection getConnection() throws Exception {
//1.加载配置文件
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
//2.读取配置信息
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//3.加载驱动
Class.forName(driverClass);
//4.获取连接
return DriverManager.getConnection(url,user,password);
}
- 关闭连接
//增删改!
public static void closeResource(Connection conn, Statement ps){
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//查询!
public static void closeResources(Connection conn, Statement ps, ResultSet rs) {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
- 通用的增删改操作
public int update(String sql, Object ...args){//sql中占位符的个数应与可变参数的长度相同
Connection conn = null;
PreparedStatement ps = null;
try {
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句,返回实例
ps = conn.prepareStatement(sql);
//3.填充占位符
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
//4.执行
/*
* 如果执行的是查询操作,有返回结果则返回true;
* 如果是其他的操作,无返回结果则返回false
*/
//ps.execute();
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
//5.资源的关闭
JDBCUtils.closeResource(conn,ps);
}
return 0;
}
- 通用查询操作
public <T> List<T> getForList(Class<T> clazz, String sql, Object... args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//获取数据库连接
conn = JDBCUtils.getConnection();
//预编译sql语句,得到PreparedStatement对象
ps = conn.prepareStatement(sql);
//填充占位符
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
//执行excuteQuery(),得到结果集。
rs = ps.executeQuery();
//结果集的元数据
ResultSetMetaData read = rs.getMetaData();
//得到数据库的列数
int columnCount = read.getColumnCount();
//创建集合对象
ArrayList<T> list = new ArrayList<>();
while (rs.next()){
T t = clazz.newInstance();
for (int i = 0; i < columnCount; i++) {
Object columnValue = rs.getObject(i + 1);
//获取列的别名
String columnLabel = read.getColumnLabel(i + 1);
//使用反射,给对象的相应属性赋值
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
}
list.add(t);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.closeResources(conn, ps, rs);
}
return null;
}
标签:ps,PreparedStatement,String,rs,try,增删,操作,null,conn 来源: https://www.cnblogs.com/ylxx-drizzle/p/16536496.html