JDBC的增删改操作可用同一个方法实现
java.sql.Statement的executeUpdate(sql)方法或者java.sql.PreparedStatement的executeUpdate()方法
Statement由java.sql.Connection的createStatement()方法实现;PreparedStatement由java.sql.Connection的prepareStatement(sql)方法实现。
Statement做数据库操作比较麻烦需拼接字符串,而且造成sql注入;PreparedStatement采用预编译手段通过占位符"?"避免了这些。PreparedStatement用setXxx填充占位符。
照例贴一段复用性高德代码
/**
* 执行出增删改数据库操作
* @param sql 数据库语句
* @param args 填充占位符,多态表现形式个数不确定
*/
public void getStatment(String sql,Object... args){
Connection conn = null;
PreparedStatement statment = null;
//1.获得数据库连接
JdbcClass jdbcClass = new JdbcClass();
conn = jdbcClass.getConnection();
try {
//2.调用connection 获得statment
statment = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
statment.setObject(i+1, args[i]);
}
//3.发送sql
statment.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//4.关闭资源
releaseDB(null, statment, conn);
}
}
/**
* 关闭资源
* @param resultSet 结果集
* @param statement 申明
* @param conn 连接
*/
public void releaseDB(ResultSet resultSet,PreparedStatement statement,Connection conn){
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}