数据库分表

1.新建数据库表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE TABLE `t_link_stats_today` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`gid` varchar(32) DEFAULT 'default' COMMENT '分组标识',
`full_short_url` varchar(128) DEFAULT NULL COMMENT '短链接',
`date` date DEFAULT NULL COMMENT '日期',
`today_pv` int(11) DEFAULT '0' COMMENT '今日PV',
`today_uv` int(11) DEFAULT '0' COMMENT '今日UV',
`today_uip` int(11) DEFAULT '0' COMMENT '今日IP数',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`del_flag` tinyint(1) DEFAULT NULL COMMENT '删除标识 0:未删除 1:已删除',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_unique_full-short-url` (`full_short_url`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

2.准备好测试类

1
2
3
4
5
6
7
8
9
public class hahaTest {

public static final String SQL = "//TODO";
public static void main(String[] args) {
for (int i = 0; i < 16; i++) { //这里的for循环代表要分15个表
System.out.printf((SQL) + "%n",i);
}
}
}

3.将数据库建表语句粘贴到测试类中并添加%d参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class hahaTest {

public static final String SQL = "CREATE TABLE `t_link_stats_today_%d` (\n" +
" `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',\n" +
" `gid` varchar(32) DEFAULT 'default' COMMENT '分组标识',\n" +
" `full_short_url` varchar(128) DEFAULT NULL COMMENT '短链接',\n" +
" `date` date DEFAULT NULL COMMENT '日期',\n" +
" `today_pv` int(11) DEFAULT '0' COMMENT '今日PV',\n" +
" `today_uv` int(11) DEFAULT '0' COMMENT '今日UV',\n" +
" `today_uip` int(11) DEFAULT '0' COMMENT '今日IP数',\n" +
" `create_time` datetime DEFAULT NULL COMMENT '创建时间',\n" +
" `update_time` datetime DEFAULT NULL COMMENT '修改时间',\n" +
" `del_flag` tinyint(1) DEFAULT NULL COMMENT '删除标识 0:未删除 1:已删除',\n" +
" PRIMARY KEY (`id`),\n" +
" UNIQUE KEY `idx_unique_full-short-url` (`full_short_url`) USING BTREE\n" +
") ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;";
public static void main(String[] args) {
for (int i = 0; i < 16; i++) {
System.out.printf((SQL) + "%n",i);
}
}
}

4.将控制台输出的结果粘贴到Navicat的命令列界面并执行

5.使用ShardingSphere在项目中配置分表规则