针对上篇博客的几个步骤,本篇博客主要以添加用户为例,演示一段完整的代码。
一般在实际项目中,我们将connection、preparedStatement、resultSet的创建和关闭都封装在一个类中。
public class DbUtil {
/*
* 取得Connection
*/
public static Connection getConnection(){
Connection conn=null;
try{
//加载JDBC驱动程序
Class.forName("oracle.jdbc.driver.OracleDriver");
//定义JDBC URL
//格式 ————驱动程序名:@主机名/IP:端口号:数据库实例名
String url="jdbc:oracle:thin:@localhost:1521:bjpowernode";
String username="DBName";
String password="PWD123";
//用DriverManger的getconnection()方法创建connection
conn=DriverManager.getConnection(url,username,password);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
/*
* 释放connection
*/
public static void close(Connection conn){
if(conn != null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
/*
* 释放PreparedStatement
*/
public static void close(PreparedStatement pstmt){
if(pstmt != null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/*
* 释放ResultSet
*/
public static void close(ResultSet rs){
if(rs != null){
try{
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
执行Sql语句的代码。
public User findUserById(String userId) {
String sql = "select user_id, user_name, password, from t_user where user_id=?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
User user = null;
try {
conn = DbUtil.getConnection();
//创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
//给sql语句中的占位符赋值
pstmt.setString(1, userId);
//创建RecordSet对象
rs = pstmt.executeQuery();
//处理查询的结果
if (rs.next()) {
user = new User();
//RecordSet的getXXX()方法
user.setUserId(rs.getString("user_id"));
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password")); }
}catch(SQLException e) {
e.printStackTrace();
}finally {
//关闭用到的对象
DbUtil.close(rs);
DbUtil.close(pstmt);
DbUtil.close(conn);
}
return user;
}