执行一个完成的数据库增删改查需要下面五个步骤:
(1)因为增删改不需要结果集,所以归为一类
(2)查自成一类
1、增删改——通用格式
- 获取数据库连接
数据库连接文章详解
InputStream is = ClassLoader.getSystemClassloader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
Connection connection = DriverManager.getConnection(url,user,password);
- 获取preparedStatement的实例
String sql = "update student set name = ? where id = ?";
PreparedStatement ps = connection.preparedStatement(sql);
- 填充占位符
ps.setObject(1,"chen");
ps.setObject(2,2);
- 执行sql语句
ps.execute();
- 关闭资源
connection.close();
ps.close();
2、查——通用格式
public <T> T getInstance(Class<T> clazz, String sql, Object... args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
if (rs.next()) {
T t = clazz.newInstance();
for (int i = 0; i < columnCount; i++) {
Object columnVal = rs.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnVal);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, ps, rs);
}
return null;
}