Skip to content

Commit

Permalink
Merge branch 'jdbc-advanced' into development
Browse files Browse the repository at this point in the history
完成JDBC进阶课程的代码及介绍.
  • Loading branch information
osxcn committed Aug 20, 2017
2 parents 001d051 + 010632c commit 126565f
Show file tree
Hide file tree
Showing 8 changed files with 389 additions and 155 deletions.
49 changes: 46 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
* [1.6.2 常用JDBC URL](#162-常用jdbc-url)
* [1.7 构建步骤](#17-构建步骤)
* [1.8 JDBC高级功能](#18-jdbc高级功能)
* [1.8.1 游标](#181-游标)
* [1.8.2 流方式](#182-流方式)
* [1.8.3 批处理](#183-批处理)
* [1.8.4 字符集设置](#184-字符集设置)
* [2. 数据库连接池](#2-数据库连接池)
* []()
* [3. SQL注入与防范](#3-sql注入与防范)
Expand Down Expand Up @@ -151,6 +155,8 @@ jdbc:microsoft:sqlserver://<ip>:<port>;DatabaseName=database
4. 获取执行结果
5. 清理环境

[构建实例:JDBC基础-HelloJDBC](/src/main/java/com/micro/profession/jdbc/practice/HelloJDBC.java)

### 1.8 JDBC高级功能
#### 1.8.1 游标
游标提供一种客户端能够部分读取服务器端结果集的功能支持,允许分批读取SQL查询的结果。
Expand All @@ -164,12 +170,49 @@ jdbc:mysql://&lt;ip&gt;:&lt;port&gt;/&lt;database&gt;<a href="#db_url"><strong>?
&emsp;&emsp;`PreparedStatement`继承自`Statement`接口,可以使用`PreparedStatement`接口来替代`Statement`接口,`PreparedStatement`接口相比`Statement`接口要求程序员在生成`PreparedStatement`的时候就要传入SQL语句,这个SQL语句是一个`参数格式化`的SQL,也就是说,SQL的`WHERE`过滤条件的参数都是通过`?`的形式来表示的,后续是通过`PreparedStatement``setString``setInt`方法来设置这些参数,然后进行执行。
&emsp;&emsp;`PreparedStatement`有个`setFetchSize`接口,这个接口可以实现游标的功能。通过`setFetchSize`,就可以设置客户端JDBC每次从服务器端取回的记录的数量。

#### 1.8.2
应用场景:查询时返回记录过多。

[构建实例:JDBC进阶-游标-HelloJDBC_cursor](/src/main/java/com/micro/profession/jdbc/practice/HelloJDBC_cursor.java)

#### 1.8.2 流方式
流方式就是将大字段的内容以二进制的方式按照区间进行划分,划分为多个区间,每次读取一个区间中的内容,在处理结束后再读取下一个区间。

应用场景:读取大字段数据。

[构建实例:JDBC进阶-流方式-LiuFang](/src/main/java/com/micro/profession/jdbc/practice/LiuFang.java)

#### 1.8.3
#### 1.8.3 批处理
批处理就是通过发送一次SQL可以插入多条数据,即将多条SQL一次性进行发送。

#### 1.8.4
批处理使用涉及到`Statement`的三个函数:
* addBatch() 把SQL打包成一个执行单元(Batch)
* executeBatch() 执行SQL
* clearBatch() 清空Batch中的SQL语句,准备下次执行

注:`PreparedStatement`同样可以使用这三个函数

应用场景:大量数据插入操作。

[构建实例:JDBC进阶-批处理-BatchTest](/src/main/java/com/micro/profession/jdbc/practice/BatchTest.java)

#### 1.8.4 字符集设置
1. 获取数据库编码设置
```mysql
show variables like '%character%';
```
2. 编码级别
* 实例级别:character_set_server
* 数据库级别:character_set_database
* 表级别:DEFAULT CHARSET=utf8
* 列级别:CHARACTER SET utf8
`
编码级别优先顺序:Server < Database < Table < Column
`
3. JDBC设置

`DB_URL` = `DB_URL` + `characterEncoding=utf8`

注:为了保证中文不出错,无论是数据库的还是JDBC的,建议设置为`utf8`

## 2. 数据库连接池

Expand Down
1 change: 1 addition & 0 deletions file/write.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
testread
74 changes: 37 additions & 37 deletions sql/1. jdbc基础/cloud_study_jdbc-basic.sql
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
/*
Navicat Premium Data Transfer
Source Server : local
Source Server Type : MySQL
Source Server Version : 50635
Source Host : localhost:3306
Source Schema : cloud_study
Target Server Type : MySQL
Target Server Version : 50635
File Encoding : 65001
Date: 15/08/2017 21:07:48
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'ZhangSan');
INSERT INTO `user` VALUES (2, 'LiSi');
INSERT INTO `user` VALUES (3, 'ZhaoWu');

SET FOREIGN_KEY_CHECKS = 1;
/*
Navicat Premium Data Transfer
Source Server : local
Source Server Type : MySQL
Source Server Version : 50635
Source Host : localhost:3306
Source Schema : cloud_study
Target Server Type : MySQL
Target Server Version : 50635
File Encoding : 65001
Date: 15/08/2017 21:07:48
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'ZhangSan');
INSERT INTO `user` VALUES (2, 'LiSi');
INSERT INTO `user` VALUES (3, 'ZhaoWu');

SET FOREIGN_KEY_CHECKS = 1;
51 changes: 51 additions & 0 deletions sql/2. jdbc进阶/cloud_study_liufang.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Navicat Premium Data Transfer
Source Server : local
Source Server Type : MySQL
Source Server Version : 50635
Source Host : localhost:3306
Source Schema : cloud_study
Target Server Type : MySQL
Target Server Version : 50635
File Encoding : 65001
Date: 20/08/2017 22:01:32
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`corp` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'ZhangSan', 'Netease');

-- ----------------------------
-- Table structure for user_note
-- ----------------------------
DROP TABLE IF EXISTS `user_note`;
CREATE TABLE `user_note` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`blog` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user_note
-- ----------------------------
INSERT INTO `user_note` VALUES (1, 'testread');

SET FOREIGN_KEY_CHECKS = 1;
60 changes: 60 additions & 0 deletions src/main/java/com/micro/profession/jdbc/practice/BatchTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.micro.profession.jdbc.practice;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

public class BatchTest {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static String DB_URL = "jdbc:mysql://localhost/cloud_study";
static final String USER = "root";
static final String PASSWORD = "root";

public static void insertUsers(Set<String> users)
throws ClassNotFoundException {
Connection conn = null;
Statement stmt = null;

//1. 加载数据库驱动
Class.forName(JDBC_DRIVER);
//2. 建立数据库连接
try {
// 获得数据库连接
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
//3. 执行SQL语句
stmt = conn.createStatement();
for(String user : users) {
stmt.addBatch("insert into user(userName) values ('" + user
+ "')");
}
stmt.executeBatch();
stmt.clearBatch();
} catch (SQLException e) {
// 异常处理
e.printStackTrace();
} finally {
//5. 清理环境
try {
if(conn != null)
conn.close();
if(stmt != null)
stmt.close();
} catch (SQLException e) {
// ignore
}
}
}

public static void main(String[] args) throws ClassNotFoundException {
Set<String> users = new HashSet<String>();
users.add("GuoYi");
users.add("ZhangSi");
users.add("LiSan");
insertUsers(users);
}

}
112 changes: 56 additions & 56 deletions src/main/java/com/micro/profession/jdbc/practice/HelloJDBC.java
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
package com.micro.profession.jdbc.practice;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class HelloJDBC {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static String DB_URL = "jdbc:mysql://localhost/cloud_study";
static final String USER = "root";
static final String PASSWORD = "root";

public static void helloword() throws ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

//1. 加载数据库驱动
Class.forName(JDBC_DRIVER);
//2. 建立数据库连接
try {
// 获得数据库连接
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
//3. 执行SQL语句
stmt = conn.createStatement();
rs = stmt.executeQuery("select userName from user");
//4. 获取执行结果
while(rs.next()) {
System.out.println("hello " + rs.getString("userName"));
}
} catch (SQLException e) {
// 异常处理
e.printStackTrace();
} finally {
//5. 清理环境
try {
if(conn != null)
conn.close();
if(stmt != null)
stmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
// ignore
}
}
}

public static void main(String[] args) throws ClassNotFoundException {
helloword();
}

}
package com.micro.profession.jdbc.practice;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class HelloJDBC {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static String DB_URL = "jdbc:mysql://localhost/cloud_study";
static final String USER = "root";
static final String PASSWORD = "root";

public static void helloword() throws ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

//1. 加载数据库驱动
Class.forName(JDBC_DRIVER);
//2. 建立数据库连接
try {
// 获得数据库连接
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
//3. 执行SQL语句
stmt = conn.createStatement();
rs = stmt.executeQuery("select userName from user");
//4. 获取执行结果
while(rs.next()) {
System.out.println("hello " + rs.getString("userName"));
}
} catch (SQLException e) {
// 异常处理
e.printStackTrace();
} finally {
//5. 清理环境
try {
if(conn != null)
conn.close();
if(stmt != null)
stmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
// ignore
}
}
}

public static void main(String[] args) throws ClassNotFoundException {
helloword();
}

}
Loading

0 comments on commit 126565f

Please sign in to comment.