DButils與JDBC
阿新 • • 發佈:2018-12-11
JDBC(Java DataBase Connectivity,java資料庫連線)是一種用SQL語句操作資料庫的Java API,可對關係資料庫進行增刪改查等的操作。
DButils是一個封裝了對JDBC操作的類庫,簡化了操作程式碼。
JDBC查詢程式碼:
public static Account get(String id){ String sql = "SELECT * FROM account WHERE accountId=?"; Connection conn = DButil.getConnection(); try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1,accountId); ResultSet rs = ps.executeQuery(); while (rs.next()){ Account account = new Account(); account.setAccountId(rs.getString("accountId")); account.setPassword(rs.getString("password")); account.setName(rs.getString("name")); account.setPhone(rs.getString("phone")); account.setCountry(rs.getString("country")); account.setRole(rs.getByte("role")); return account; } } catch (SQLException e) { e.printStackTrace(); } return null; }
DButils查詢程式碼:
public static Account get(String id){ String sql = "select * from account where id=?"; Connection conn = DButil.getConnection(); QueryRunner qr = new QueryRunner(); Object params[] = {id}; try { return qr.query(conn,sql,new BeanHandler<Account>(Account.class),params); } catch (SQLException e) { e.printStackTrace(); } return null; }
節約了時間提高了開發效率。