本文采用的是加载配置文件的形式和数据库进行交互
ps:数据库采用的是postgresql
1、加载配置文件
1 public void configConstant(Constants me) { 2 3 PropKit.use("config.properties"); 4 5 }
2、config.properties配置
1 jdbcUrl = jdbc:postgresql://localhost:5432/liubaohua 2 username = postgres 3 password = postgres 4 driver = org.postgresql.Driver
3、使用C3p0Plugin连接数据库
ps:这里需要导入c3p0-0.9.5.1 、mchange-commons-java-0.2.10 、mysql-connector-java-5.1.20-bin
至于mysql-connector-java-5.1.20-bin什么导入,还不清楚。
1 public void configPlugin(Plugins me) { 2 C3p0Plugin c3p0Plugin = new C3p0Plugin(PropKit.get("jdbcUrl"),PropKit.get("username"),PropKit.get("password"),PropKit.get("driver")); 3 ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin); 4 arp.setShowSql(true); 5 arp.addMapping("post_user","user_id",User.class); 6 me.add(c3p0Plugin); 7 me.add(arp); 8 arp.setDialect(new PostgreSqlDialect()); 9 10 }
4、在Controller中的action方法中调用数据库操作方法
1 public void save() { 2 // 用户删除 3 User.user.deleteById(4); 4 5 // 用户添加 6 new User().set("user_name", "宝华"+new Random().nextInt(100)) 7 .set("user_password", "123") 8 .set("user_class_id", 1) 9 .save(); 10 11 renderText("用户添加成功..."); 12 // 用户查询 13 User user = User.user.findById(2); 14 renderText(user.getStr("user_name")); 15 // 用户修改 16 User.user.findById(1).set("user_name","张无忌").update(); 17 // 查询语句 18 String likeStr = "select * from post_user where user_name like ‘%宝%‘"; 19 List<User> userList = User.user.find(likeStr); 20 String renderStr = ""; 21 for (User user2 : userList) { 22 renderStr += user2.getStr("user_name"); 23 renderStr += "---"; 24 } 25 renderText(renderStr); 26 // 分页查询语句 参数列表(起始页,每页条数,查询字段,表和条件《使用占位符》,"设置占位符") 27 Page<User> userPage = User.user.paginate(1, 8, 28 "select *", "from post_user where user_name like ?", "%华%"); 29 30 renderStr = ""; 31 for (User user2 : userPage.getList()) { 32 renderStr += "-->"; 33 renderStr += user2.getStr("user_name")+"\n"; 34 } 35 renderText("总页数:"+userPage.getTotalPage()+"\t共有:"+userPage.getTotalRow()+"条数据" 36 +"\t共有:"+userPage.getTotalPage()+"页"+"\t当前页:"+userPage.getPageNumber() 37 +"\n"+renderStr); 38 39 }
转载请标明出处@华行天下
时间: 2024-10-14 21:35:38