jdbc - 可变参数的通用增删查改

  1. 1. 通用的查询修改方法,减少写重复的代码

通用的查询修改方法,减少写重复的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.lan.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BaseDao {

//protected 访问控制符 受保护的
protected Connection conn =null;
protected PreparedStatement ps = null;
protected ResultSet rs = null;


/**
* 方法功能:通用增删改方法
*/
public int executeUpdate(String sql, Object...x) {
int n = 0;
try {
// a.获取数据库连接
conn = JDBCUtil.getConnection();
// b.sql传入方法返回执行对象
ps = conn.prepareStatement(sql);
//新增的sql语句 有占位符
if(null!=x) {
//拿到可变参数
for(int i = 0;i<x.length;i++) {
//System.out.println(x[i]);
ps.setObject(i+1, x[i]);
}
}
n = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(null, null, conn);
}
return n;

}


/**
* 方法功能:通用查询 查询所有 查询一个 模糊查询
*/
public ResultSet executeQuery(String sql, Object...x) {
try {
// a.获取数据库连接
conn = JDBCUtil.getConnection();
// b.sql传入方法返回执行对象
ps = conn.prepareStatement(sql);
//新增的sql语句 有占位符
if(null!=x) {
//拿到可变参数中的2个值
for(int i = 0;i<x.length;i++) {
//System.out.println(x[i]);
ps.setObject(i+1, x[i]);
}
}
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return rs;

}

}