JDBC 查询步骤

来源:互联网 发布:顶尖数据恢复软件官方 编辑:程序博客网 时间:2024/06/16 07:34

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.Driverurl=jdbc\:mysql\://localhost\:3306/classusername=rootpassword=gkzx#初始创建connection的数量initialSize=3#最多创建connection的数量maxActive=15#空闲connection的最大值maxIdle=2#空闲connection的最小值minIdle=1#没有可用connection时,等待最大值maxWait=30000