JDBC代码概述(一)

什么是JDBC

JDBCJava DataBase Connectivity, Java数据库连接) ,是一种用于执行SQL语句的Java API,为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成

Driver的实现

  1. 新建Driver对象,使用DriverManager注册:

    1
    2
    Driver driver = new com.mysql.cj.jdbc.Driver();
    DriverManager.registerDriver(driver);
  2. 只用反射,将driver放入内存,让系统自动注册:在查看Driver的源代码时我们发现,该类内部有一个静态代码块,在代码块中就是在实例化一个驱动并在驱动中心注册.静态代码块会在类进入内存时执行,也就是说,我们只要让该类字节码进入内存,就会自动完成注册,不需要我们手动去new所以我们在代码中直接使用反射,通过Class.forName("com.mysql.jdbc.Driver"),加载该类进入内存即可。

    1
    Class.forName("com.mysql.cj.jdbc.Driver");

使用statement,完成CRUD

增加,删除,更新操作:

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
package com.msb.test1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public class TestJDBC4 {
private static String driver ="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
private static String user="root";
private static String password="root";
public static void main(String[] args) {
//testDelete();
testUpdate();
}
//更新操作 添加相同 只需要更换sql语句就好了
public static void testUpdate(){
Connection connection=null;
Statement statement=null;
try{
Class.forName(driver);
connection =DriverManager.getConnection(url, user,password);
statement = connection.createStatement();
String sql="update dept set dname='总部',loc='北京' where deptno= 30 ";
int rows = statement.executeUpdate(sql);
System.out.println("影响数据行数为:"+rows);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != statement){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//删除操作
public static void testDelete(){
Connection connection=null;
Statement statement=null;
try{
Class.forName(driver);
connection =DriverManager.getConnection(url, user,password);
statement = connection.createStatement();
String sql="delete from dept where deptno =40";
int rows = statement.executeUpdate(sql);
System.out.println("影响数据行数为:"+rows);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != statement){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

查询操作:

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
package com.msb.test1;
import java.sql.*;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public class TestJDBC5 {
private static String driver ="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
private static String user="root";
private static String password="root";
public static void main(String[] args) {
testQuery();
}
public static void testQuery(){
Connection connection = null;
Statement statement=null;
ResultSet resultSet=null;
try{
Class.forName(driver);
connection = DriverManager.getConnection(url, user,password);
statement = connection.createStatement();
String sql="select * from emp";
//返回resultset
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
int empno = resultSet.getInt("empno");
String ename = resultSet.getString("ename");
String job = resultSet.getString("job");
int mgr = resultSet.getInt("mgr");
Date hiredate = resultSet.getDate("hiredate");
double sal= resultSet.getDouble("sal");
double comm= resultSet.getDouble("comm");
int deptno= resultSet.getInt("deptno");
System.out.println(""+empno+" "+ename+" "+job+" "+mgr+" "+hiredate+" "+sal+" "+comm+" "+deptno);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != resultSet){
try {
resultSet.close();
} catch (SQLException e) {e.printStackTrace();
}
}
if(null != statement){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

ResultSet类方法:

方法名 说 明
boolean next() 将光标从当前位置向下移动一行
boolean previous() 游标从当前位置向上移动一行
void close() 关闭ResultSet 对象
int getInt(int colIndex) int形式获取结果集当前行指定列号值
int getInt(String colLabel) int形式获取结果集当前行指定列名值
float getFloat(int colIndex) float形式获取结果集当前行指定列号值
Float getFloat(String colLabel) float形式获取结果集当前行指定列名值
String getString(int colIndex) String 形式获取结果集当前行指定列号值
StringgetString(String colLabel) String形式获取结果集当前行指定列名值

使用预编译语句PrepareStatement完成CRUD

之前会使用sql注入来使用引号来该改变原有sql语句的结构实现密码不对还能查询的结果。使用预编译语句就可以避免。

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
package com.msb.test3;
import com.msb.entity.Emp;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public class TestPreparedSstatement {
private static String driver ="com.mysql.cj.jdbc.Driver";
private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
private static String user="root";
private static String password="root";
public static void main(String[] args) {
//testAdd();
//testUpdate();
//testDelete();
testQuery();
}
public static void testAdd(){
// 向 Emp表中增加一条数据
Connection connection = null;
PreparedStatement preparedStatement=null;
try{
Class.forName(driver);
connection = DriverManager.getConnection(url, user,password);
String sql="insert into emp values(DEFAULT ,?,?,?,?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句
//设置参数
preparedStatement.setString(1,"Mark");
preparedStatement.setString(2,"MANAGER" );
preparedStatement.setInt(3,7839);
preparedStatement.setDate(4,new Date(System.currentTimeMillis()));
preparedStatement.setDouble(5,3000.12);
preparedStatement.setDouble(6,0.0);
preparedStatement.setDouble(7,30);
//执行CURD
int rows =preparedStatement.executeUpdate();// 这里不需要再传入SQL语句
System.out.println(rows);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != preparedStatement){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void testUpdate(){
// 根据工号修改员工表中的数据
Connection connection = null;
PreparedStatement preparedStatement=null;
try{
Class.forName(driver);
connection = DriverManager.getConnection(url, user,password);
String sql="update emp set ename =? ,job=? where empno =?";
preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句
//设置参数
preparedStatement.setString(1,"Jhon");
preparedStatement.setString(2,"ANALYST" );
preparedStatement.setInt(3,7935);
//执行CURD
int rows =preparedStatement.executeUpdate();// 这里不需要再传入SQL语句
System.out.println(rows);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != preparedStatement){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void testDelete(){
// 根据工号删除员工表中的数据
Connection connection = null;
PreparedStatement preparedStatement=null;
try{
Class.forName(driver);
connection = DriverManager.getConnection(url, user,password);
String sql="delete from emp where empno =?";
preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句
//设置参数
preparedStatement.setInt(1,7935);
//执行CURD
int rows =preparedStatement.executeUpdate();// 这里不需要再传入SQL语句
System.out.println(rows);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != preparedStatement){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void testQuery(){
// 查询名字中包含字母A的员工信息
Connection connection = null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
List<Emp> list =null;
try{
Class.forName(driver);
connection = DriverManager.getConnection(url, user,password);
/*
* 1使用PreparedStatement语句对象防止注入攻击
* 2PreparedStatement 可以使用 ? 作为参数的占位符
* 3使用?作为占位符,即使是字符串和日期类型,也不使用单独再添加 ''
* 4connection.createStatement();获得的是普通语句对象 Statement
* 5connection.prepareStatement(sql);可以获得一个预编译语句对象PreparedStatement
* 6如果SQL语句中有?作为参数占位符号,那么要在执行CURD之前先设置参数
* 7通过set***(问号的编号,数据) 方法设置参数
* */
String sql="select * from emp where ename like ? ";
preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句
//设置参数
preparedStatement.setString(1,"%A%");
//执行CURD
resultSet = preparedStatement.executeQuery();// 这里不需要再传入SQL语句
list=new ArrayList<Emp>() ;
while(resultSet.next()){
int empno = resultSet.getInt("empno");
String ename = resultSet.getString("ename");
String job = resultSet.getString("job");
int mgr = resultSet.getInt("mgr");
Date hiredate = resultSet.getDate("hiredate");
double sal= resultSet.getDouble("sal");
double comm= resultSet.getDouble("comm");
int deptno= resultSet.getInt("deptno");
Emp emp =new Emp(empno, ename, job, mgr, hiredate, sal, comm, deptno);
list.add(emp);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != resultSet){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != preparedStatement){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 遍历集合
for (Emp emp : list) {
System.out.println(emp);
}
}
}