JDBC 查询步骤

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

 
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值