JDBC學習筆記——簡單UerDao
阿新 • • 發佈:2019-01-23
his 實例 bsp 插入數據 統一 jdbcutils div aoe rep
JDBC(Java DataBase Connectivity,java數據庫連接)是一種用於執行SQL語句的Java API,可以為多種關系數據庫提供統一訪問,它由一組用Java語言編寫的類和接口組成。JDBC提供了一種基準,據此可以構建更高級的工具和接口,使數據庫開發人員能夠編寫數據庫應用程序,利用JDBC提供的接口,可以方便得對數據庫進行操作。
1、JDBCUtils(產生Connection,關閉資源)
1 package com.sina.jdbc; 2 3 import java.io.File; 4 import java.io.FileInputStream;View Code5 import java.io.IOException; 6 import java.io.FileNotFoundException; 7 import java.util.Properties; 8 import java.sql.Connection; 9 import java.sql.DriverManager; 10 import java.sql.Statement; 11 import java.sql.ResultSet; 12 import java.sql.SQLException; 13 14 public class JDBCUtils {15 private JDBCUtils(){ 16 17 } 18 19 public static JDBCUtils getInstance(){ 20 if(instance == null){ 21 synchronized(JDBCUtils.class){ 22 if(instance == null){ //二次判空, 防止多線程下多次創建實例對象 23 instance = new JDBCUtils(); 24} 25 } 26 } 27 return instance; 28 } 29 30 public Connection getConnection(){ 31 Connection connection = null; 32 try { 33 connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD); 34 } catch(SQLException e){ 35 e.printStackTrace(); 36 } 37 return connection; 38 } 39 40 public void close(Connection connection, Statement stmt, ResultSet rs){ 41 if(rs != null){ 42 try { 43 rs.close(); 44 } catch(SQLException e){ 45 e.printStackTrace(); 46 } 47 } 48 49 if(stmt != null){ 50 try { 51 stmt.close(); 52 } catch(SQLException e){ 53 e.printStackTrace(); 54 } 55 } 56 57 if(connection != null){ 58 try { 59 connection.close(); 60 } catch(SQLException e){ 61 e.printStackTrace(); 62 } 63 } 64 } 65 66 private static JDBCUtils instance = null; 67 //加載配置文件, 讀取以下信息以建立Connection 68 private static String DRIVER_NAME; 69 private static String URL; 70 private static String USER_NAME; 71 private static String PASSWORD; 72 static { 73 FileInputStream fis = null; 74 try { 75 Properties p = new Properties(); 76 File file = new File("./src/config.properties"); 77 fis = new FileInputStream(file); 78 p.load(fis); 79 DRIVER_NAME = p.getProperty("DRIVER_NAME"); 80 URL = p.getProperty("URL"); 81 USER_NAME = p.getProperty("USER_NAME"); 82 PASSWORD = p.getProperty("PASSWORD"); 83 84 Class.forName(DRIVER_NAME); //加載驅動 85 } catch(ClassNotFoundException e) { 86 System.out.println(DRIVER_NAME + "驅動類找不著."); 87 } catch(FileNotFoundException e) { 88 System.out.println("文件 config.properties 找不到."); 89 } catch(IOException e){ 90 e.printStackTrace(); 91 } finally{ 92 if(fis != null){ 93 try { 94 fis.close(); 95 } catch(IOException e){ 96 e.printStackTrace(); 97 } 98 } 99 } 100 } 101 }
2、UserDao
1 package com.sina.jdbc.dao; 2 3 import com.sina.jdbc.orm.User; 4 5 //UserDao(User數據訪問對象)利用接口實現,屬面向接口編程,方便代碼使用和管理,若實現類被修改,使用接口方法的程序不受影響,不需修改 6 public interface UserDao { 7 void addUser(User user); 8 void deleteUser(User user); 9 void updateUser(User user); 10 User getUser(Integer id); 11 User findUser(String name, String gender); 12 }View Code
3、UserDaoFactory
1 package com.sina.jdbc.dao; 2 3 import java.util.Properties; 4 import java.io.InputStream; 5 import java.io.IOException; 6 7 //使用DAD工廠實現,若要改用其他方式實現的UserDao,則直接修改配置文件即可,程序用到UserDao的地方無需修改 8 public class UserDaoFactory { 9 private UserDaoFactory(){ 10 11 } 12 13 public static UserDaoFactory getInstance(){ 14 if(instance == null){ 15 synchronized(UserDaoFactory.class){ 16 if(instance == null){ 17 instance = new UserDaoFactory(); 18 } 19 } 20 } 21 return instance; 22 } 23 24 public UserDao getUserDao(){ 25 UserDao retVal = null; 26 Properties p = new Properties(); 27 InputStream is = null; 28 try { 29 is = UserDaoFactory.class.getClassLoader().getResourceAsStream("config.properties"); 30 p.load(is); 31 String daoClassName = p.getProperty("daoClassName"); 32 retVal = (UserDao)Class.forName(daoClassName).getConstructor().newInstance(); 33 } catch(Exception e){ 34 throw new ExceptionInInitializerError(); 35 } finally{ 36 if(is != null){ 37 try { 38 is.close(); 39 } catch(IOException e){ 40 e.printStackTrace(); 41 } 42 } 43 } 44 return retVal; 45 } 46 47 private static UserDaoFactory instance = null; 48 }View Code
4、UserDao(增刪改查)
1 package com.sina.jdbc.dao.imp; 2 3 import com.sina.jdbc.dao.UserDao; 4 import com.sina.jdbc.dao.DAOException; 5 import com.sina.jdbc.orm.User; 6 import com.sina.jdbc.JDBCUtils; 7 import java.sql.*; 8 9 public class UserDaoJdbcImp implements UserDao { 10 @Override 11 public void addUser(User user) { 12 Connection connection = null; 13 PreparedStatement pstmt = null; 14 try { 15 connection = JDBCUtils.getInstance().getConnection(); 16 pstmt = connection.prepareStatement("insert into t_user values(?, ?, ?, ?, ?)"); 17 setPstmt(pstmt, user); 18 pstmt.execute(); 19 } catch(SQLException e){ 20 throw new DAOException(e.getMessage(), e); //拋出異常給上級調用者, 讓得知異常發生 21 } finally{ 22 JDBCUtils.getInstance().close(connection, pstmt, null); 23 } 24 } 25 26 @Override 27 public void deleteUser(User user){ 28 Connection connection = null; 29 PreparedStatement pstmt = null; 30 try { 31 connection = JDBCUtils.getInstance().getConnection(); 32 pstmt = connection.prepareStatement("delete from t_user where id = ? and name = ?"); 33 pstmt.setInt(1, user.getId()); 34 pstmt.setString(2, user.getName()); 35 pstmt.execute(); 36 } catch(SQLException e){ 37 throw new DAOException(e.getMessage(), e); 38 } finally{ 39 JDBCUtils.getInstance().close(connection, pstmt, null); 40 } 41 } 42 43 @Override 44 public void updateUser(User user){ 45 Connection connection = null; 46 PreparedStatement pstmt = null; 47 try { 48 connection = JDBCUtils.getInstance().getConnection(); 49 pstmt = connection.prepareStatement("update t_user set id = ?, name = ?, birthday = ?, gender = ?, property = ? where id = ?"); 50 setPstmt(pstmt, user); 51 pstmt.setInt(6, user.getId()); 52 pstmt.execute(); 53 } catch(SQLException e){ 54 throw new DAOException(e.getMessage(), e); 55 } finally{ 56 JDBCUtils.getInstance().close(connection, pstmt, null); 57 } 58 } 59 60 @Override 61 public User getUser(Integer id){ 62 Connection connection = null; 63 PreparedStatement pstmt = null; 64 ResultSet rs = null; 65 User user = null; 66 try { 67 connection = JDBCUtils.getInstance().getConnection(); 68 pstmt = connection.prepareStatement("select id,name,birthday,gender,property from t_user where id = ?"); 69 pstmt.setInt(1, id); 70 rs = pstmt.executeQuery(); 71 user = createUser(rs); 72 } catch(SQLException e){ 73 throw new DAOException(e.getMessage(), e); 74 } finally{ 75 JDBCUtils.getInstance().close(connection, pstmt, rs); 76 } 77 return user; 78 } 79 80 @Override 81 public User findUser(String name, String gender){ 82 Connection connection = null; 83 PreparedStatement pstmt = null; 84 ResultSet rs = null; 85 User user = null; 86 try { 87 connection = JDBCUtils.getInstance().getConnection(); 88 pstmt = connection.prepareStatement("select id,name,birthday,gender,property from t_user where name = ? and gender = ?"); 89 pstmt.setString(1, name); 90 pstmt.setString(2, gender); 91 rs = pstmt.executeQuery(); 92 user = createUser(rs); 93 } catch(SQLException e){ 94 throw new DAOException(e.getMessage(), e); 95 } finally{ 96 JDBCUtils.getInstance().close(connection, pstmt, rs); 97 } 98 return user; 99 } 100 101 private User createUser(ResultSet rs) throws SQLException { 102 User user = null; 103 while(rs.next()){ 104 user = new User(rs.getInt("id"), rs.getString("name"), rs.getDate("birthday"), rs.getString("gender"), rs.getFloat("property")); 105 } 106 return user; 107 } 108 109 private static void setPstmt(PreparedStatement pstmt, User user) throws SQLException { 110 pstmt.setInt(1, user.getId()); 111 pstmt.setString(2, user.getName()); 112 pstmt.setDate(3, new Date(user.getBirthday().getTime())); 113 pstmt.setString(4, user.getGender()); 114 pstmt.setFloat(5, user.getProperty()); 115 } 116 }View Code
5、User
1 package com.sina.jdbc.orm; 2 3 import java.util.Date; 4 5 //ORM(對象關系映射),數據二維表對應Java類,表字段對應類屬性 6 public class User { 7 public User(){ 8 9 } 10 11 public User(Integer id, String name, Date birthday, String gender, Float property){ 12 this.id = id; 13 this.name = name; 14 this.birthday = birthday; 15 this.gender = gender; 16 this.property = property; 17 } 18 19 public void setId(Integer id){ 20 this.id = id; 21 } 22 23 public Integer getId(){ 24 return id; 25 } 26 27 public void setName(String name){ 28 this.name = name; 29 } 30 31 public String getName(){ 32 return name; 33 } 34 35 public void setBirthday(Date birthday){ 36 this.birthday = birthday; 37 } 38 39 public Date getBirthday(){ 40 return birthday; 41 } 42 43 public void setGender(String gender) { 44 this.gender = gender; 45 } 46 47 public String getGender(){ 48 return gender; 49 } 50 51 public void setProperty(Float property){ 52 this.property = property; 53 } 54 55 public Float getProperty(){ 56 return property; 57 } 58 59 private Integer id; //采用包裝類,如果id為主鍵並自增長,在插入數據庫時可不指定id, 60 // 若以PreparedStatement返回主鍵並給相應的User對象賦值,就可以區別哪些個對象已經寫到數據庫中,因為已經保存過的對象會得到返回的主鍵並賦值給id, 61 // 而沒被操作的對象id屬性將為null,而不是數字0,易於區分 62 private String name; 63 private Date birthday; 64 private String gender; 65 private Float property; 66 }View Code
6、DAOException(給上級調用者拋出異常,讓其得知異常產生地點)
1 package com.sina.jdbc.dao; 2 3 public class DAOException extends RuntimeException { 4 public DAOException() { 5 } 6 7 public DAOException(String message) { 8 super(message); 9 } 10 11 public DAOException(String message, Throwable cause) { 12 super(message, cause); 13 } 14 15 public DAOException(Throwable cause) { 16 super(cause); 17 } 18 }View Code
7、Test
1 package com.sina.jdbc; 2 3 import com.sina.jdbc.dao.UserDao; 4 import com.sina.jdbc.dao.UserDaoFactory; 5 import com.sina.jdbc.orm.User; 6 import java.util.Date; 7 8 public class Test { 9 public static void main(String[] args){ 10 UserDao userDao = UserDaoFactory.getInstance().getUserDao(); 11 User user = new User(10, "Tom", new Date(), "男", 230f); 12 userDao.addUser(user); 13 // User user = userDao.findUser("Tom", "男"); 14 // System.out.println(user.getId()+ " " + user.getBirthday()); 15 // userDao.deleteUser(user); 16 } 17 }View Code
以下代碼為簡單的UserDAO,本人為JAVA新人,發布出來方便以後復習。另外,其中可能存在一些不足的地方,如有建議,請告知。
JDBC學習筆記——簡單UerDao