Java基础开发之JDBC操作数据库增删改查,分页查询实例详解
作者:spaceAt 发布时间:2024-01-15 04:16:28
标签:Java,JDBC
对数据库的操作无非就是增删改查,其中数查询操作最为复杂,所以将查询单独讲解,我这里用的Mysql数据库
增删改查操作
分页查询操作
1.查询结果以list返回
2.查询结果以jsonArray返回
3.查询总记录条数
先看一下相关的配置信息
public static final String USER_NAME = "root";
public static final String PWD = "123456789";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/web_demon";
/** 分页查询默认每页记录条数 */
public static final int PAGE_SIZE_DEFAULT = 10;
增删改操作
获取数据库连接对象
/**
* 获取数据库连接
* @return 数据库连接对象
*/
public Connection getConnection(Connection conn) {
if(conn == null){
try {
Class.forName(Config.DRIVER);
conn = DriverManager.getConnection(Config.URL, Config.USER_NAME, Config.PWD);
} catch (Exception e) {
e.printStackTrace();
}
}
return conn;
}
封装增删改操作
/**
* 新增,删除,插入操作
* @param sql 执行的sql语句
* 例如:新增语句 "insert into user (name,sex) values (?,?)";
* 删除语句 "delete from user where id=?";
* 修改语句 "update user set name=?,sex=? where id=? and sex=?";
* @param values 对应的参数值
* @return 影响条数,-1为异常
*/
private int execute(String sql,Object... values){
Connection conn = null;
PreparedStatement pStmt = null;
try {
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//设置参数
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
int i =pStmt.executeUpdate();
return i;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
this.closeConnection(conn);
}
}
return -1;
}
调用方法
//新增
public static void insert(){
String sql = "insert into user (name,sex) values (?,?)";
Object[] values = new Object[]{"李四",0};
int res = baseImp.execute(sql, values);
System.out.println("insert res="+res);
}
//删除
public static void delete(){
String sql = "delete from user where id=?";
Object[] values = new Object[]{2};
int res = baseImp.execute(sql, values);
System.out.println("delete res="+res);
}
//更新
public static void update(){
String sql = "update user set name=?,sex=? where id=? and sex=?";
Object[] values = new Object[]{"张三",1,1,0};
int res = baseImp.execute(sql, values);
System.out.println("update res="+res);
}
查询操作
1.查询结果以list返回
/**
* 查询结果以list返回
* @param pageIndex 页数
* @param pageSize 每页记录条数
* @param attachTableName 在结果集中是否给key值附加表名,例如:user.id,与id
* @param sql 查询语句 例如:"select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id"
* @param values
* @throws SQLException
*/
private List<Map<String, Object>> queryList(int pageIndex,int pageSize,boolean attachTableName,String sql,Object... values) throws SQLException{
Connection conn = null;
PreparedStatement pStmt = null;
List<Map<String, Object>> dataList = null;
//校验参数
if(pageIndex <= 0){
pageIndex = 1;
}
if(pageSize <= 0){
pageSize = Config.PAGE_SIZE_DEFAULT;
}
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//设置参数
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
//设置最大查询到第几条记录
pStmt.setMaxRows(pageIndex*pageSize);
ResultSet rs = pStmt.executeQuery();
//游标移动到要输出的第一条记录
rs.relative((pageIndex-1)*pageSize);
if(rs != null){
try {
dataList = new ArrayList<Map<String,Object>>();
ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息,比如字段数、字段名等
//遍历结果集
while(rs.next()){
Map<String, Object> map = new LinkedHashMap();
for (int i = 1; i <= md.getColumnCount(); i++) {
map.put(attachTableName?(formatTableName(md.getTableName(i))+"."+md.getColumnLabel(i)):(md.getColumnLabel(i)), rs.getObject(i));
}
dataList.add(map);
}
}finally{
if(rs != null){
rs.close();
}
if(pStmt != null){
pStmt.close();
}
if (conn != null) {
this.closeConnection(conn);
}
}
}
return dataList;
}
调用list查询
public static void queryList(){
String sql = "select u.*,d.* from user u,depart d where u.depart_id=d.id";
try {
List<Map<String, Object>> dataList = baseImp.queryForListAttachTableName(2,2,sql, null);
// List<Map<String, Object>> dataList = baseImp.queryForList(2,2,sql, null);
for (Map<String, Object> map : dataList) {
for (String key : map.keySet()) {
System.out.print(key+"="+map.get(key)+" ");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
结果
2.查询结果以jsonArray返回
/**
* 查询结果以ArrayList返回
* @param 在结果集中是否给key值附加表名,例如:user.id,与id
* @param sql 查询语句 例如:"select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id"
* @param values
* @throws SQLException
*/
private JSONArray queryJsonArray(int pageIndex,int pageSize,boolean attachTableName,String sql,Object... values) throws SQLException{
JSONArray jsonArray = null;
Connection conn = null;
PreparedStatement pStmt = null;
//校验参数
if(pageIndex <= 0){
pageIndex = 1;
}
if(pageSize <= 0){
pageSize = Config.PAGE_SIZE_DEFAULT;
}
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//设置参数
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
//设置最大查询到第几条记录
pStmt.setMaxRows(pageIndex*pageSize);
ResultSet rs = pStmt.executeQuery();
//游标移动到要输出的第一条记录
rs.relative((pageIndex-1)*pageSize);
if(rs != null){
try {
jsonArray = new JSONArray();
ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息,比如字段数、字段名等
//遍历结果集
while(rs.next()){
JSONObject jsonObject = new JSONObject();
for (int i = 1; i <= md.getColumnCount(); i++) {
jsonObject.put(attachTableName?(formatTableName(md.getTableName(i))+"."+md.getColumnLabel(i)):(md.getColumnLabel(i)), rs.getObject(i)+"");
}
jsonArray.add(jsonObject);
}
}finally{
if(rs != null){
rs.close();
}
if(pStmt != null){
pStmt.close();
}
if (conn != null) {
this.closeConnection(conn);
}
}
}
return jsonArray;
}
调用jsonArray查询
public static void queryJsonArray(){
// String sql = "select * from user u";
String sql = "select u.*,d.* from user u,depart d where u.depart_id=d.id";
// String sql = "select u.id AS uid,u.name,u.sex,u.depart_id AS departId,d.name from user u,depart d where u.depart_id=d.id";
// String sql = "select u.id,u.name,u.sex,u.depart_id AS departId,d.* from user u,depart d where u.depart_id=d.id";
try {
JSONArray jsonArray = baseImp.queryForJsonArrayAttachTableName(2,2,sql, null);
// JSONArray jsonArray = baseImp.queryForJsonArray(sql, null);
System.out.println(jsonArray.toString());
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Iterator<?> iterator = jsonObject.keys();
Object key = null;
while (iterator.hasNext()) {
key = iterator.next();
System.out.print(key+" "+jsonObject.get(key)+" ");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
结果
[{"user.id":"4","user.name":"王五","user.sex":"0","user.depart_id":"3","depart.id":"3","depart.name":"研发部","depart.desc":"这是研发部"},{"user.id":"5","user.name":"赵六","user.sex":"1","user.depart_id":"1","depart.id":"1","depart.name":"测试部","depart.desc":"这是测试部"}]
user.id 4 user.name 王五 user.sex 0 user.depart_id 3 depart.id 3 depart.name 研发部 depart.desc 这是研发部
user.id 5 user.name 赵六 user.sex 1 user.depart_id 1 depart.id 1 depart.name 测试部 depart.desc 这是测试部
3.查询总记录条数
/**
* 查询记录条数
* @param sql 例如:"select count(*) from user where xxx"
* @param values
* @throws SQLException
*/
public int queryCount(String sql,Object... values) throws SQLException{
int count = -1;
Connection conn = null;
PreparedStatement pStmt = null;
conn = this.getConnection(conn);
pStmt = conn.prepareStatement(sql);
//设置参数
if(pStmt != null && values != null && values.length > 0){
for (int i = 0; i < values.length; i++) {
pStmt.setObject(i+1, values[i]);
}
}
ResultSet rs = pStmt.executeQuery();
if(rs != null){
try {
while(rs.next()){
count = rs.getInt(1);
}
}finally{
if(rs != null){
rs.close();
}
if(pStmt != null){
pStmt.close();
}
if (conn != null) {
this.closeConnection(conn);
}
}
}
return count;
}
调用查询总记录条数
public static void queryCount(){
String sql = "select count(*) from user u";
try {
System.out.println("count="+baseImp.queryCount(sql, null));
} catch (SQLException e) {
e.printStackTrace();
}
}
结果
至此我们介绍完了Java基础开发中JDBC对数据库进行增删改查操作与分页查询,如果想了解更多关于这方面的文章大家可以查看下面的相关链接
来源:https://blog.csdn.net/sapce_fish/article/details/52764678


猜你喜欢
- 在数据库中,UNION和UNION ALL关键字都是将两个结果集合并为一个,但这两者从使用和效率上来说都有所不同。MySQL中的UNIONU
- 看到别人用td和table标签模拟的办法: 设置table的上、左padding
- 官网地址:https://dev.mysql.com/downloads/mysql/我这里是RHEL6.5的系统,因此选择RedHat 6
- 或许马上,或许几年之后,但是有迹象显示IE浏览器占统治地位的时代即将结束。在数据分析公司Net Applications的排名中,IE的市场
- 墙上时钟与单调时钟墙上时钟墙上时钟也称为墙上时间。大多是1970年1月1日(UTC)以来的秒数和毫秒数。墙上时间可以和NTP(Network
- 背景和目的:利用python request 编写脚本测试公司系统的文件上传接口。前端读取文件的大小然后文件分片传给后端,后端将每一片数据重
- 优化是一项复杂的任务,因为它最终需要对整个系统的理解.当用你的系统/应用的小知识做一些局部优化是可能的时候,你越想让你的系统更优化,你必须知
- 本文实例讲述了Python基于checksum计算文件是否相同的方法。分享给大家供大家参考。具体如下:假设有2个二进制文件(0.bin, 1
- 1、安装npm install echarts --save2、vue2中使用Echarts在main.js文件中// 引入echartsi
- 在操作DataFrame时,肯定会经常用到loc,iloc,at等函数,各个函数看起来差不多,但是还是有很多区别的,我们一起来看下吧。首先,
- 一、什么是框架框架的本质就是一个socket服务,可以完成不同主机之间的通信。它是一个半成品的项目,其中可能已经封装好了基本的功能,比如路由
- python sys模块用法sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧!sys模块的
- 优先队列的二叉堆实现在前面的章节里我们学习了“先进先出”(FIFO)的数据结构:队列(Queue)。队列有一种变体叫做“优先队列”(Prio
- 题目描述:给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数样例:给出链表1->2->3->4-&g
- 场景最近在生产环境遇到了下面这样一个场景:后台在字典表中存储了一些之前需要前后端共同维护的枚举值,并提供根据 type/id 获取字典的 A
- 由于是从源码包安装的Mysql,所以系统中是没有红帽常用的servcie mysqld restart这个脚本只好手工重启有人建议Killa
- 模仿学习同事的代码来写的,主要是搞懂python中如何来组织包,如何调用包,如何读取配置文件,连接数据库,设置路由,路由分组。(注:使用的是
- 本来是只用Tenorflow的,但是因为TF有些Numpy特性并不支持,比如对数组使用列表进行切片,所以只能转战Pytorch了(pytor
- // 涉及命名空间 using System; using System.Collections; using System.Compone
- Go提供几种方法检查变量的类型,在字符串格式化标识%T, 反射方式:reflect.TypeOf, reflect.ValueOf.Kind