JDBC(Java DataBase Connectivity,java数据库连接)是一种用SQL语句操作数据库的Java API,可对关系数据库进行增删改查等的操作。
DButils是一个封装了对JDBC操作的类库,简化了操作代码。
JDBC查询代码:
public static Account get(String accountId){
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;
}
节约了时间提高了开发效率。