来源:二弎寿先生 发布时间:2018-11-21 14:04:49 阅读量:1211
一、连接数据库
a.获取数据库驱动
b.从配置文件db.properties中获取mysql
db.properties配置文件
//mysql驱动
driver:com.mysql.jdbc.Driver
//本机mysql的路径
url:jdbc:mysql://localhost:3306/jdbcdemo
//用户名
username:root
//密码
password:123
1
2
3
4
5
6
7
8
二、构建实体类
类名与数据库表名一致,字段名与数据列名一致
package bean;
public class Users {
private String username;
private String password;
private String phone;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
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
三、dbUtils类 :进行数据库的相关操作
package utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import bean.Users;
/**
*
* <p>Title:DbUtil </p>
* <p>Description:数据库工具类 </p>
* <p>Company: </p>
* @author 小桃小涛
* @date 2017年8月23日下午2:28:14
*/
public class DbUtil {
//1.获取数据库驱动
/**
* @description 获取数据库驱动
* @return
*/
public static Connection getConnection(){
Properties ps = new Properties();
Connection conn = null;
FileInputStream inputstream = null;
String driver;
String url;
String username;
String password;
try {
//从配置文件db.properties中获取mysql配置
inputstream = new FileInputStream(new File("D:\\Java Example\\Jdbc\\src\\db.properties"));
ps.load(inputstream);
driver =ps.getProperty("driver");
url =ps.getProperty("url");
username =ps.getProperty("username");
password =ps.getProperty("password");
//System.out.println(driver+" "+url+" "+username+""+password);
//加载驱动
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
//关闭流
if(inputstream!=null){
try {
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return conn;
}
//关闭资源 Object... 不定参数
public static void closeDb(Object... args){
if(args==null){
return;
}
try {
for (int i = 0; i < args.length; i++) {
//判断是不是预处理方法
if(args[i] instanceof PreparedStatement
&&args[i]!=null){
((PreparedStatement)args[i]).close();
}
//判断是不是连接
if(args[i] instanceof Connection
&&args[i]!=null){
((Connection)args[i]).close();
}
//判断是不是结果集
if(args[i] instanceof ResultSet
&&args[i]!=null){
((ResultSet)args[i]).close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
* @Title: update
* @Description: TODO(更新数据)
* @param @param sql语句
* @param @param args
* @param @return 设定文件
* @return int 返回类型
* @throws
*/
public static int update(String sql,String... args){
int row=0;
//获取驱动
Connection connection = getConnection();
PreparedStatement ps =null;
try {
if(sql==null||sql.equals("")){
return row;
}else{
//sql语句预处理
ps =connection.prepareStatement(sql);
//赋值
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
row = ps.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeDb(ps,connection);
}
return row;
}
/**
*
* @Title: getResult
* @Description: TODO(查询数据)
* @param @param cls
* @param @param sql语句
* @param @param args
* @param @return 设定文件
* @return ArrayList<T> 返回类型
* @throws
*/
public static <T>ArrayList<T> getResult(Class<T> cls,String sql,String... args){
ArrayList<T> list = new ArrayList<T>();
Connection connection = getConnection();
PreparedStatement ps = null;
ResultSet resultSet=null;
try {
if(sql==null||sql.equals("")){
return null;
}
ps =connection.prepareStatement(sql);
if(args!=null){
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1, args[i]);
}
//执行查询方法
resultSet = ps.executeQuery();
//获取结果集结构
ResultSetMetaData metaData = resultSet.getMetaData();
//获取列数
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
T t = (T)cls.newInstance();
for (int i = 0; i < columnCount; i++) {
Object val = resultSet.getObject(i+1);
String name =metaData.getColumnLabel(i+1);
Field Field = cls.getDeclaredField(name);
//暴力反射
if(!Modifier.isPublic(Field.getModifiers())){
Field.setAccessible(true);
Field.set(t,val);
}
}
list.add(t);
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} finally{
closeDb(ps,connection,resultSet);
}
return list;
}
public static void main(String[] args) {
/*String sql="UPDATE users SET username =? WHERE password=?";
int update = update(sql,"event","123","123456789");
int update = update(sql,"aaa","123");
System.out.println(update);*/
String sql="SELECT username,password,phone From users";
ArrayList<Users> result = getResult(Users.class,sql);
for (Users users : result) {
System.out.println(users.getUsername()+"\t"+users.getPassword()+"\t"+users.getPhone());
}
}
}
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
在上述对数据库进行增删改查的过程中,可以发现其共性部分,即通用的流程:
(1)创建Connection对象、SQL查询命令字符串;
(2)对Connection对象传入SQL查询命令,获得PreparedStatement对象;
(3)对PreparedStatement对象执行executeUpdate()或executeQurey()获得结果;
(4)先后关闭PreparedStatement对象和Connection对象。
可见,使用JDBC时,最常打交道的是Connection、PreparedStatement这两个类,以及select中的ResultSet类。
---------------------