mysql - 为什么运行第二次会出错?
PHP中文网
PHP中文网 2017-04-17 11:57:19
[MySQL讨论组]

p2.py代码如下:

import random
import string

def gen_activation_code(id,length = 12):
    '''
        产生激活码
    '''

    prefix = hex(int(id))[2:] + 'h'
    #print(prefix)
    foo = hex(int(id))
    #print(foo)
    #print foo[0],foo[1]
    length = length - len(prefix)
    chars = string.ascii_letters + string.digits
    activation_code = prefix + ''.join([random.choice(chars) for i in range(length)])
    return activation_code

def hex_to_dec(hex_num):
    return int(hex_num.upper(),16)


if __name__  == '__main__':
    for i in range(10,300,15):
        code = gen_activation_code(i)
        id_hex = code.split('h')[0]
        id = hex_to_dec(id_hex)
        #print type(id)
        print code,id

p3.py代码如下:

import MySQLdb
import p2

con = MySQLdb.connect('127.0.0.1','root','newpassword','testdb')

with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS Code2(ID INT  PRIMARY KEY,ACTIVATION VARCHAR(20))")
    for i in range(100,500,100):
        co = p2.gen_activation_code(i)
        id_hex = co.split('h')[0]
        id = p2.hex_to_dec(id_hex)
        cur.execute("insert into Code2(ID,ACTIVATION) VALUES(%s,%s)",(id,co))

con.commit()
cur.close()


这两段代码的主要目的就是产生很多随机码然后保存到MySQL中,可是我发现,程序第一遍运行没问题,再多运行一次,就会报错:


根据报错的信息,反应时主键键值不唯一,有重复而导致无法插入数据库。
而当我将表的名字改过之后(code改为code1),又可以运行,当运行第二遍又会有同样的错误产生,求解答。

PHP中文网
PHP中文网

认证0级讲师

全部回复(1)
PHP中文网

主键不唯一就是主键不唯一啊 ,有啥好解释的。。。。

第一遍生成了 100、200、300、400,4个主键,和4个随机字符串,插入到数据库中

第二遍运行是同样的结果,只是随机串不同,可你数据库里已经有了这4个主键, 还怎么插?

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号