之前學習.NET的時候,曾經利用ODBC進行連接數據庫,而在Java中通常采用JDBC連接數據庫,這裡以oracle數據庫為例簡單的總結一下利用JDBC如何連接並操作數據庫。
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; }
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(); } } }}
1、首先找到
D:\oracle\product\10.2.0\db_1\jdbc\lib 找到ojdbc14.jar
2、其次再找到 ojdbc14.jar\oracle\jdbc\driver 下面的oraceldriver這樣就找到了要使用的驅動程序文件
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); } }
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; }