1.PreparedStatement介绍
可以通过调用 Connection 对象的 preparedStatement(String sql) 方法获取 PreparedStatement 对象
2.PreparedStatement的使用
获取connection连接方法:
@Test
public void 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.获取连接
Connection conn = DriverManager.getConnection(url,user,password);
return coon;
}
关闭资源:
public static void closeResource(Connection coon, Statement ps) {
try {
if (coon != null)
coon.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
通用的增删改操作:
//通用的增、删、改操作(体现一:增、删、改 ; 体现二:针对于不同的表)
public void update(String sql,Object ... args){
Connection conn = null;
PreparedStatement ps = null;
try {
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.获取PreparedStatement的实例 (或:预编译sql语句)
ps = conn.prepareStatement(sql);
//3.填充占位符
for(int i = 0;i < args.length;i++){
ps.setObject(i + 1, args[i]);
}
//4.执行sql语句
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}finally{
//5.关闭资源
JDBCUtils.closeResource(conn, ps);
}
}
其中,配置文件声明在工程的src目录下:【jdbc.properties】
user=root password=abc123 url=jdbc:mysql://localhost:3306/test(test为数据库名称) driverClass=com.mysql.jdbc.Driver
通用的查找操作:
public staticList AllSelect(Class Clazz,String sql,Object...args) throws SQLException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException { try { Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } ResultSet resultSet = ps.executeQuery(); ResultSetmetaData metaData = resultSet.getmetaData(); int columnCount = metaData.getColumnCount(); List arr = new ArrayList<>(); while (resultSet.next()) { T t = Clazz.newInstance(); for (int i = 0; i < columnCount; i++) { Object value = resultSet.getObject(i + 1); String name = metaData.getColumnLabel(i + 1); Field field = Clazz.getDeclaredField(name); field.setAccessible(true); field.set(t, value); } arr.add(t); } return arr; }catch (Exception e){ e.printStackTrace(); }finally { // 关闭资源 if ( resultSet!= null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; } }
其中,配置文件声明在工程的src目录下:【jdbc.properties】
user=root password=abc123 url=jdbc:mysql://localhost:3306/test(test为数据库名称) driverClass=com.mysql.jdbc.Driver



