前面记得有过博客简单的介绍过JDBC和ODBC的区别,在Java开发中经常用到JDBC连接数据库,下面通过实例介绍如何实现:
<span style="font-family:KaiTi_GB2312;font-size:18px;">public class DbUtil { public static Connection getConnection(){ Connection conn=null; try { Class.forName("oracle.jdbc.driver.OracleDriver");//找到oracle驱动器所在的类 String url="jdbc:oracle:thin:@localhost:1521:bjpowernode"; //URL地址 String username="drp"; String password="drp"; conn=DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } <pre name="code" class="java"> public static void close(PreparedStatement pstmt){ if(pstmt !=null){ try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs){ if(rs !=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </span>
<span style="font-family:KaiTi_GB2312;font-size:18px;">public void addUser(User user){ String sql="insert into t_user(user_id,user_name,PASSWORD,CONTACT_TEL,EMAIL,CREATE_DATE)values(?,?,?,?,?,?)"; //?为参数占位符 Connection conn=null; PreparedStatement pstmt=null; //通常利用PreparedStatement进行操作,性能得到优化 try{ conn=DbUtil.getConnection(); pstmt=conn.prepareStatement(sql); pstmt.setString(1, user.getUserId()); pstmt.setString(2,user.getUserName()); pstmt.setString(3, user.getPassword()); pstmt.setString(4, user.getContactTel()); pstmt.setString(5,user.getEmail()); //pstmt.setTimestamp(6,new Timestamp(System.currentTimeMillis())); pstmt.setTimestamp(6, new Timestamp(new Date().getTime()));//获取当前系统时间 pstmt.executeUpdate();//执行增删改操作 }catch(SQLException e){ e.printStackTrace(); }finally{ DbUtil.close(conn); DbUtil.close(pstmt); } } </span>
<span style="font-family:KaiTi_GB2312;font-size:18px;">public User findUserById(String userId){ String sql = "select user_id, user_name, password, contact_tel, email, create_date from t_user where user_id=?"; Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null;//定义存放查询结果的结果集 User user=null; try{ conn=DbUtil.getConnection(); pstmt=conn.prepareStatement(sql); pstmt.setString(1,userId); rs=pstmt.executeQuery();//执行查询操作 if(rs.next()){ user=new User(); user.setUserId(rs.getString("user_Id")); user.setUserName(rs.getString("user_name")); user.setPassword(rs.getString("password")); user.setContactTel(rs.getString("contact_Tel")); user.setEmail(rs.getString("email")); user.setCreateDate(rs.getTimestamp("create_date")); } }catch(SQLException e){ e.printStackTrace(); }finally{ //按顺序进行关闭 DbUtil.close(rs); DbUtil.close(pstmt); DbUtil.close(conn); } return user; } </span>