JDBC連接oracle的實例
好久沒寫過jdbc,基本忘干凈了,隨意插一個圖,簡單學習一下。然后干別的。。。。。
使用jdbc操作數據庫步驟是固定的
1.將驅動包導入到數據庫,每一個數據庫的驅動包都不一樣,下面我提供一個Oracle數據庫的驅動包http://download.csdn.net/detail/hncsy403/4530830將它下載后放入web項目中的 web-inf中的lib中
2.選擇項目右鍵,選擇Build Bath,在libraries中add JARs,選擇剛才的jar包
學生類bean
package jdbc.bean; import java.util.Date; public class Student { private int id; private String name; private String password; private String sex; private int age; private Date birthday; private String memo; private String photo; private Date regTime; public int getAge() { return age; } public Date getBirthday() { return birthday; } public int getId() { return id; } public String getMemo() { return memo; } public String getName() { return name; } public String getPassword() { return password; } public String getPhoto() { return photo; } public Date getRegTime() { return regTime; } public String getSex() { return sex; } public void setAge(int age) { this.age = age; } public void setBirthday(Date birthday) { this.birthday = birthday; } public void setId(int id) { this.id = id; } public void setMemo(String memo) { this.memo = memo; } public void setName(String name) { this.name = name; } public void setPassword(String password) { this.password = password; } public void setPhoto(String photo) { this.photo = photo; } public void setRegTime(Date regTime) { this.regTime = regTime; } public void setSex(String sex) { this.sex = sex; } }
工具類:DBUtil
package jdbc.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { private static final String driverClass = "oracle.jdbc.driver.OracleDriver"; private static final String jdbcUrl = "jdbc:oracle:thin:@liumo:1521:ORCL"; private static final String user = "test_lm"; private static final String password = "test_lm"; public static Connection getConn() { // 1.注冊驅動 try { Class.forName(driverClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } // 2.創建Connection(數據庫連接對象) Connection conn = null; try { conn = DriverManager.getConnection(jdbcUrl, user, password); conn.setAutoCommit(false); return conn; } catch (SQLException e) { e.printStackTrace(); } /* * Connection是Statement的工廠,一個Connection可以生產多個Statement。 * Statement是ResultSet的工廠,一個Statement卻只能對應一個ResultSet(它們是一一對應的關系)。 * 所以在一段程序里要用多個ResultSet的時候,必須再Connection中獲得多個Statement,然后一個Statement對應一個ResultSet。 */ return null; } /** * 關閉連接(數據庫連接對象) * @param conn */ public static void close(Connection conn) { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 關閉編譯的 SQL 語句的對象 * @param stmt */ public static void close(Statement stmt) { try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 關閉結果集 * @param rs */ public static void close(ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 提交事務 * @param conn */ public static void commit(Connection conn) { try { if (conn != null) { conn.commit(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 回滾事務 * @param conn */ public static void rollback(Connection conn) { try { if (conn != null) { conn.rollback(); } } catch (SQLException e) { e.printStackTrace(); } } }
實際的dao:StudentDao
package jdbc.dao; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import jdbc.bean.Student; import jdbc.util.DBUtil; public class StudentDao { /** * 保存 * @param student */ public void save(Student student) { Connection conn = DBUtil.getConn(); PreparedStatement pstmt = null; String sql = " insert into t_student(name,password,sex,age,birthday,memo,photo,reg_time) "; sql += " values(?,?,?,?,?,?,?,?) "; try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setString(2, student.getPassword()); pstmt.setString(3, student.getSex()); pstmt.setInt(4, student.getAge()); pstmt.setDate(5, new java.sql.Date(student.getBirthday().getTime())); // 只存年月日這種形式 pstmt.setString(6, student.getMemo()); try { // 構建一個輸入流存blob pstmt.setBlob(7, new FileInputStream(student.getPhoto())); } catch (FileNotFoundException e) { e.printStackTrace(); } pstmt.setTimestamp(8, new java.sql.Timestamp(student.getRegTime().getTime())); // 完整的時間格式 pstmt.executeUpdate(); DBUtil.commit(conn); } catch (SQLException e) { DBUtil.rollback(conn); e.printStackTrace(); } finally { DBUtil.close(pstmt); DBUtil.close(conn); } } /** * 刪除 * @param id */ public void delete(int id) { Connection conn = DBUtil.getConn(); PreparedStatement pstmt = null; String sql = " delete from t_student where id=?"; try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); pstmt.executeUpdate(); DBUtil.commit(conn); } catch (SQLException e) { DBUtil.rollback(conn); e.printStackTrace(); } finally { DBUtil.close(pstmt); DBUtil.close(conn); } } /** * 批量刪除 * @param ids */ public void deleteBatch(int[] ids) { Connection conn = DBUtil.getConn(); PreparedStatement pstmt = null; String sql = " delete from t_student where id=?"; try { pstmt = conn.prepareStatement(sql); for (int id : ids) { pstmt.setInt(1, id); pstmt.addBatch(); } pstmt.executeBatch(); DBUtil.commit(conn); } catch (SQLException e) { DBUtil.rollback(conn); e.printStackTrace(); } finally { DBUtil.close(pstmt); DBUtil.close(conn); } } /** * 修改 * @param student */ public void update(Student student) { Connection conn = DBUtil.getConn(); PreparedStatement pstmt = null; String sql = " update t_student set name=?,password=?,sex=?,age=?,birthday=?,memo=?,photo=?,reg_time=? where id=?"; try { pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setString(2, student.getPassword()); pstmt.setString(3, student.getSex()); pstmt.setInt(4, student.getAge()); pstmt.setDate(5, new java.sql.Date(student.getBirthday().getTime())); // 只存年月日這種形式 pstmt.setString(6, student.getMemo()); try { // 構建一個輸入流存blob pstmt.setBlob(7, new FileInputStream(student.getPhoto())); } catch (FileNotFoundException e) { e.printStackTrace(); } pstmt.setTimestamp(8, new java.sql.Timestamp(student.getRegTime().getTime())); // 完整的時間格式 pstmt.setInt(9, student.getId()); pstmt.executeUpdate(); DBUtil.commit(conn); } catch (SQLException e) { DBUtil.rollback(conn); e.printStackTrace(); } finally { DBUtil.close(pstmt); DBUtil.close(conn); } } /** * 查找 * @param id * @return */ public Student find(int id) { Connection conn = DBUtil.getConn(); PreparedStatement pstmt = null; ResultSet resultSet = null; String sql = " select * from t_student where id=?"; Student student = null; try { pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); resultSet = pstmt.executeQuery(); if (resultSet.next()) { student = new Student(); student.setId(resultSet.getInt("id")); student.setName(resultSet.getString("name")); student.setAge(resultSet.getInt("age")); student.setBirthday(resultSet.getDate("birthday")); student.setMemo(resultSet.getString("memo")); student.setPassword(resultSet.getString("password")); student.setRegTime(resultSet.getTimestamp("reg_time")); student.setSex(resultSet.getString("sex")); InputStream in = resultSet.getBlob("photo").getBinaryStream(); String path = "d:\\ltf.jpg"; try { OutputStream out = new FileOutputStream(path); copy(in, out); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } student.setPhoto(path); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(resultSet); DBUtil.close(pstmt); DBUtil.close(conn); } return student; } private void copy(InputStream in, OutputStream out) { int i = 0; try { while ((i = in.read()) != -1) { out.write(i); } out.flush(); } catch (IOException e) { e.printStackTrace(); } } /** * 查詢多條記錄 * @return */ public List<Student> query() { Connection conn = DBUtil.getConn(); PreparedStatement pstmt = null; ResultSet resultSet = null; String sql = " select * from t_student "; List<Student> studentList = new ArrayList<Student>(); try { pstmt = conn.prepareStatement(sql); resultSet = pstmt.executeQuery(); while (resultSet.next()) { Student student = new Student(); student.setId(resultSet.getInt("id")); student.setName(resultSet.getString("name")); student.setAge(resultSet.getInt("age")); student.setBirthday(resultSet.getDate("birthday")); student.setMemo(resultSet.getString("memo")); student.setPassword(resultSet.getString("password")); student.setRegTime(resultSet.getTimestamp("reg_time")); student.setSex(resultSet.getString("sex")); InputStream in = resultSet.getBlob("photo").getBinaryStream(); String path = "d:\\ltf.jpg"; try { //將數據庫存的圖片放到磁盤的某個位置 OutputStream out = new FileOutputStream(path); copy(in, out); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } student.setPhoto(path); studentList.add(student); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(resultSet); DBUtil.close(pstmt); DBUtil.close(conn); } return studentList; } }
測試類:DaoTest
package jdbc.test; import static org.junit.Assert.fail; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import jdbc.bean.Student; import jdbc.dao.StudentDao; import org.junit.Test; public class DaoTest { @Test public void test() { fail("Not yet implemented"); Student s=new Student(); //s.setId(3); s.setName("zss"); s.setPassword("zss"); s.setSex("女"); s.setAge(21); try { s.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1980-01-01")); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } s.setMemo("我人還不錯"); s.setPhoto("c:\\ltf.jpg"); s.setRegTime(new Date()); StudentDao sd=new StudentDao(); //sd.save(s); //sd.update(s); //sd.delete(1); //sd.deleteBatch(new int[]{2,3}); System.out.println(sd.query().size()); } }
每次SQL操作都需要建立和關閉連接,這勢必會消耗大量的資源開銷,如何避免
分析:可以采用連接池,對連接進行統一維護,不必每次都建立和關閉。事實上這是很多對JDBC進行封裝的工具所采用的。(等看到hibernate,spring連接數據庫和事務的時候在研究一下。)
參考:
通過JDBC進行簡單的增刪改查(以MySQL為例) http://www.cnblogs.com/wuyuegb2312/p/3872607.html
JDBC學習之-如何獲取Connection http://blog.csdn.net/luohuacanyue/article/details/8770450