JDBC 查询步骤
1、读取配置文件:
//注意此代码是写在一个静态代码块中,以确保数据库在加载该类中的实例之前就已经加载完成
private static DataSource dataSource;
static { Properties props = new Properties(); try { props.load(DbUtil.class.getClassLoader().getResourceAsStream( "dbcp.properties"));//数据库的数据配置文件路径 dataSource = BasicDataSourceFactory.createDataSource(props); } catch (Exception e) { e.printStackTrace(); } }
2、获取JDBC的链接
private static ThreadLocal<Connection> connLocal = new ThreadLocal<Connection>();
public synchronized static Connection getConnection() throws Exception { Connection conn = connLocal.get(); if (conn == null) { conn = dataSource.getConnection(); connLocal.set(conn); } return conn; }
3、执行数据的操作
//数据的删除操作
private static final String ADD_NEW_USER="insert into d_user values(?,?)"; public void intoNew(User u) throws Exception{ Connection conn=DbUtil.getConnection(); PreparedStatement pst=conn.prepareStatement(ADD_NEW_USER); pst.setString(1, u.getUsername()); pst.setString(2, u.getPassword()); pst.executeUpdate();
//数据的查询和遍历操作
privatestaticfinal String FIND_COURSE="select *from d_cate where parent_id>0";
public List<Cate> findCourse() throws Exception {
Connection conn=DbUtil.getConnection();
System.out.println(conn);
PreparedStatement pst=conn.prepareStatement(FIND_COURSE);
ResultSet rs=pst.executeQuery();
List<Cate> list=new ArrayList<Cate>();
while(rs.next()){
Cate c=new Cate();
c.setId(rs.getInt("id"));
c.setName(rs.getString("name"));
c.setFileName(rs.getString("filename"));
c.setParentId(rs.getInt("parent_id"));
list.add(c);
}
return list;
}
//数据的更新操作
privatefinalstatic String DELETE_APP="delete from d_application where id=?";
publicvoid delete(int id) throws Exception{
Connection conn=DbUtil.getConnection();
PreparedStatement pst=conn.prepareStatement(DELETE_APP);
pst.setInt(1, id);
pst.executeUpdate();
}
4、数据库连接需要的perporties文件配置
// mySql
driverClassName=com.mysql.jdbc.Driver url=jdbc\:mysql\://localhost\:3306/class username=root password=gkzx #初始创建connection的数量 initialSize=3 #最多创建connection的数量 maxActive=15 #空闲connection的最大值 maxIdle=2 #空闲connection的最小值 minIdle=1 #没有可用connection时,等待最大值 maxWait=30000