Oracle的Sequence用爽了,发现MySQL没有Sequence,那么,自己写一个呗。

> 最简单的实现

先建一个表存储当前值:

CREATE TABLE `t_sequence` (
`sequence_name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '序列名称' ,
`value` int(11) NULL DEFAULT NULL COMMENT '当前值' ,
PRIMARY KEY (`sequence_name`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
ROW_FORMAT=COMPACT
;

获取当前值的函数:

CREATE DEFINER = `root`@`localhost` FUNCTION `currval`(sequence_name varchar(64))
RETURNS int(11)
BEGIN
declare current integer;
set current = 0;
select t.value into current from t_sequence t where t.sequence_name = sequence_name;
return current;
end;

获取下一个值:

CREATE DEFINER = `root`@`localhost` FUNCTION `nextval`(sequence_name varchar(64))
RETURNS int(11)
BEGIN
declare current integer;
set current = 0; update t_sequence t set t.value = t.value + 1 where t.sequence_name = sequence_name;
select t.value into current from t_sequence t where t.sequence_name = sequence_name; return current;
end;

写一个多线程程序测试下并发:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class JDBCTools { public static void main(String[] args) throws Exception {
JDBCTools.execute("update t_balance t set t.balance = 300 where t.user_id = 2");
JDBCTools.query("select * from t_balance t");
} public static String HOST = "localhost";
public static String PORT = "3306";
public static String DATABASE_NAME = "demo";
public static String USER_NAME = "root";
public static String PASSWORD = "123456"; /**
* 获取数据库连接
* @return 数据库连接
*/
public static Connection getConn() throws Exception {
Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE_NAME + "?user=" + USER_NAME + "&password=" + PASSWORD + "&useUnicode=true&characterEncoding=UTF8";
Connection connection = DriverManager.getConnection(url);
return connection;
} /**
* 关闭资源
*/
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO 处理异常
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// TODO 处理异常
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO 处理异常
e.printStackTrace();
}
}
} /**
* 查询SQL
* @param sql 查询语句
* @return 数据集合
* @throws SQLException
*/
public static List<Map<String, String>> query(String sql) throws Exception {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Map<String, String>> resultList = null; try {
connection = JDBCTools.getConn(); statement = connection.createStatement();
resultSet = statement.executeQuery(sql); ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
String[] columnNames = new String[columnCount + 1];
for (int i = 1; i <= columnCount; i++) {
columnNames[i] = resultSetMetaData.getColumnName(i);
} resultList = new ArrayList<Map<String, String>>();
Map<String, String> resultMap = new HashMap<String, String>();
resultSet.beforeFirst();
while (resultSet.next()) {
for (int i = 1; i <= columnCount; i++) {
resultMap.put(columnNames[i], resultSet.getString(i));
}
resultList.add(resultMap);
}
// System.out.println("成功查询数据库,查得数据:" + resultList);
} catch(Throwable t) {
// TODO 处理异常
t.printStackTrace();
} finally {
JDBCTools.closeResource(connection, statement, resultSet);
} return resultList;
} /**
* 执行SQL
* @param sql 执行的SQL
* @return 操作条数
*/
public static int execute(String sql) throws Exception {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
int num = 0; try {
connection = JDBCTools.getConn(); statement = connection.createStatement();
num = statement.executeUpdate(sql); } catch(Throwable t) {
// TODO 处理异常
t.printStackTrace();
} finally {
JDBCTools.closeResource(connection, statement, resultSet);
} return num;
} }
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class Call { public static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>(); public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool(); for (int i = 0; i < 100; i++) {
es.execute(new Runnable() { @Override
public void run() {
String key = getSequence();
if (!map.contains(key)) {
System.out.println("put " + key);
map.put(key, key);
} else {
System.out.println(key + " is exists.");
}
}
});
} } public static String getSequence() {
List<Map<String, String>> list = null;
try {
list = JDBCTools.query("select nextval('user_code') as current");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String temp = list.get(0).get("current");
return temp;
} }

> 用排他锁的方式

上面的程序虽然测试并无发现问题(有可能测试程序写得不好),理论上高并发会出现重复值,用排他锁重写了一下,不过效率会比较低:

CREATE DEFINER = `root`@`localhost` FUNCTION `nextval_safe`(sequence_name varchar(64))
RETURNS int(11)
BEGIN
declare current integer;
set current = 0; select t.value into current from t_sequence t where t.sequence_name = sequence_name for update;
update t_sequence t set t.value = t.value + 1 where t.sequence_name = sequence_name;
set current = current + 1; return current;
end;

【MySQL】MySQL的Sequence的更多相关文章

  1. 【转】MySQL中增加sequence管理功能(模拟创建sequence)

    1.oracel可以直接支持sequence,但是mysql不支持sequence,因此我们要通过模拟sequence的方法在mysql中创建sequence.模拟sequence的方法:项目场景:项 ...

  2. MySQL :: MySQL 8.0 Reference Manual :: B.6.4.3 Problems with NULL Values https://dev.mysql.com/doc/refman/8.0/en/problems-with-null.html

    MySQL :: MySQL 8.0 Reference Manual :: B.6.4.3 Problems with NULL Values https://dev.mysql.com/doc/r ...

  3. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

    有时候,当我们使用"mysql"."mysqladmin"."mysqldump"等命令管理数据库时,服务器抛出类似如下错误: 一.错误现场 ...

  4. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

    从供应商手中接手一个云平台(Windwos Azure)上的MySQL数据库,登录数据库时遇到错误: $mysql -uroot -p Enter password: ERROR 2002 (HY00 ...

  5. mac ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib /mysql/mysql.sock' (111)

    之前装了mysql,今天打开mysql的时候报了个Can't connect to local MySQL server through socket '/var/lib /mysql/mysql.s ...

  6. 更换mysql数据目录后出现ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) 的解决办法

    服务器上的mysql默认数据目录为/var/lib/mysql/,同时服务器的/空间不是很大,而近期又有大量的日志需要导入进行分析,时常搞得/的空间捉襟见肘,晚上一狠心就想把mysql的数据目录转移到 ...

  7. 启动mysql错误ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)

    ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ ( ...

  8. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)--MySQL错误

    MySQL错误整理: 错误一: ERROR (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/my ...

  9. Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’解决方法 + Linux启动/停止/重启Mysql数据库的方法

    启动mysql 报错: ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/m ...

  10. Can 't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock '(2) ;

    Can 't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock '(2) ; 如果你在网上search这个 ...

随机推荐

  1. spring da-y02-go1

    使用构造器实例化bean: springday02:(同样导入5个基本jar包)1.复制xml文件到ioc包下2.B类,实现无参构造器3.A类,B是它的成员变量,实现无参和set/get方法4.修改x ...

  2. sql 存储过程 分页

    ALTER PROCEDURE [dbo].[BrokerToLenderDataShow2]@Where VARCHAR(200), --查询条件 不含'where'字符,如id>10 and ...

  3. jquery遍历对象,数组,集合

    1.jquery 遍历对象 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTM ...

  4. Workspace Cloning / Sharing in Jenkins

    http://lwandersonmusings.blogspot.com/2011/06/workspace-cloning-sharing-in-hudson.html   What's insi ...

  5. div内的img下出现几像素的空白间距解决办法

    现象描述: 解决方法: 1.设父元素的font-size:0; 2.设img为display:block; 3.设img为vertical-align:middle;

  6. Java应用程序的打包和发布

    Java应用程序的打包和发布 简化Java应用程序的打包和发布 发布Java应用程序时Java提供了一系列打包和发布工具,可以显著的简化发布过程 该文章提供了打包Java code的几种方法,探讨Ja ...

  7. oracle中的函数

    ORACLE中函数          Oracle已经内建了许多函数,不同的函数有不同的作用和用法,有的函数只能作用在一个记录行上,有的能够作用在多个记录行上,不同的函数可能处理不同的数据类型.常见的 ...

  8. 从Windows 8 安装光盘安装.NET Framework 3.5.1

    在安装一些应用时, 例如安装 Oracle, 可能会缺少了安装 .Net FrameWork 3.5.1 无法继续. 最简单的方法当时是,直接进 控制面板, 在添加删除程序内, 选择增加Windows ...

  9. Python 进阶(五)定制类

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAugAAAF/CAIAAACUs6uhAAAgAElEQVR4nOzdZXubx7ov8PPV9tlrt0 ...

  10. 160906、Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)

    互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,Dubbo是一个分布式服务框架,在这种情况下诞生的.现在核心业务抽取出来,作为独立的服务,使 ...