要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3 种类型:
- 执行静态SQL语句。通常通过Statement实例实现。
- 执行动态SQL语句。通常通过PreparedStatement实例实现。
- 执行数据库存储过程。通常通过CallableStatement实例实现
本篇文章介绍执行静态的SQL语句。
使用Statement接口实现CRUD操作,分为以下四个步骤:
步骤一:获取数据库连接
步骤二:创建Statement实例
步骤三:执行sql语句
步骤四:关闭连接
实现数据库表中数据的增删改操作
public void update(String sql){
Connection conn = null;
Statement st = null;
try {
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.创建一个Statement的实例
st = conn.createStatement();
//3.根据提供的sql语句,执行
st.execute(sql);
} catch (Exception e) {
e.printStackTrace();
}finally{
//4.资源的关闭
JDBCUtils.close(conn, st);
}
}
实现数据库表中的查询操作
publicT get(String sql, Class clazz) { T t = null; Connection conn = null; Statement st = null; ResultSet rs = null; try { // 获取连接 conn = JDBCUtils.getConnection(); // 创建Statement对象 st = conn.createStatement(); // 执行sql语句 rs = st.executeQuery(sql); // 获取结果集的元数据 ResultSetmetaData rsmd = rs.getmetaData(); // 获取结果集的列数 int columnCount = rsmd.getColumnCount(); if (rs.next()) { t = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { // //1. 获取列的名称 // String columnName = rsmd.getColumnName(i+1); // 1. 获取列的别名 // 注意:获取结果集中(相当于数据表)列的名称(别名) String columnName = rsmd.getColumnLabel(i + 1); // 2. 根据列名获取对应数据表中的数据 Object columnVal = rs.getObject(columnName); // 3. 将数据表中得到的数据,封装进对象 // 注意:反射根据Java中类的属性获取Field对象 Field field = clazz.getDeclaredField(columnName); field.setAccessible(true); field.set(t, columnVal); } return t; } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭资源 if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; }
Statement使用的弊端
弊端一:拼串操作繁琐
例如:在数据表person中插入一个person对象,sql语句为
String sql = "insert into person(id, name, sex, phone)values('"+ id +"', '"+ name +"', '"+ sex +"', '" + phone+"')"
如values后面的语句所示,如果数据表中的属性多,则sql语句写起来会相当麻烦,并且很容易出错。
弊端二:存在SQL注入问题
SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或者命令,从而利用系统的SQL引擎完成恶意行为的做法。
例如:执行如下sql语句,即使不知道用户名和密码也会成功进入系统。
SELECT user,password FROM user_table WHERe user = '1' or ' AND password = '=1 or '1' = '1'
避免这些弊端,可以使用Statement的子接口PreparedStatement代替Statement进行操作。



