利用mysql的LAST_INSERT_ID实现一个简单的自增长的id。
mysql建表
CREATE TABLE `sequence` (
`id` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#初始化
INSERT INTO sequence VALUES (0);
#-*- coding: utf8 -*-
import MySQLdb
import settings
def generate():
db_args = settings.DB_ACCOUNT_PASSWORD['farm']
db = MySQLdb.connect(host=db_args[2], user=db_args[0], passwd=db_args[1],
db=db_args[3])
db.autocommit(True)
cursor = db.cursor()
try:
cursor.execute("UPDATE sequence SET id=LAST_INSERT_ID(id+1)")
cursor.execute("SELECT LAST_INSERT_ID()")
uid = str(int(cursor.fetchone()[0]))
except MySQLdb.Error, e:
print 'mysql err'
return None
finally:
cursor.close()
return uid