当前位置: 代码迷 >> 综合 >> 用python代码自动随机生成mysql数据中的错误--Cursor is not connected
  详细解决方案

用python代码自动随机生成mysql数据中的错误--Cursor is not connected

热度:75   发布时间:2023-10-23 03:31:25.0

一开始的操作
先在mysql可视化工具里面创建数据库

CREATE TABLE `mydb`.`users` (`user_id` INT NOT NULL AUTO_INCREMENT,`username` VARCHAR(45) NULL,`password` VARCHAR(45) NOT NULL,`realname` VARCHAR(45) NULL,`city` ENUM('010', '021', '0512', '020', '0755', '0511') NULL,`mylike` ENUM('钓鱼', '唱歌', '看书', '跳舞', '打球') NULL,`age` INT NULL,`sex` SET('男', '女') NULL,PRIMARY KEY (`user_id`),UNIQUE INDEX `username_UNIQUE` (`username` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;

随机生成数据的python代码

import random
import mysql.connector as connectorcnx = connector.connect(user='root', password='your password', host='localhost', database='mycms')cursor = cnx.cursor()# 批量插入
# 通过insert into table values(...),(....),(....)格式,只向数据库提交一次插入
users = []
words = list('abcdefghijklmnopqrstuvwxyz')
mylike = ['钓鱼', '唱歌', '看书', '跳舞', '打球']
citys = ['010', '021', '0512', '020', '0755', '0511']def createBatchUsers():sql_list = []sql = "INSERT INTO `mycms`.`users` VALUES"# 批量创建多条数据for i in range(0, 100):username = createUserName()user={
    'user_id': i,"username": username,'realname': "".join(random.choices(words, k=6)),"password": random.randint(111111, 999999),"city": random.choice(citys),"age": random.randint(18, 35),"sex": random.choice(["男", "女"]),"mylike": ",".join(random.choices(mylike, k=random.randint(0, 4))),}values = "(null, '{username}', '{realname}', '{password}', '{city}', '{age}', '{sex}', '{mylike}')".format(**user)sql_list.append(values.format(**user))try:sql += ",".join(sql_list)print(sql)cursor.execute(sql)cnx.commit()except connector.Error as e:print("error:", e)cursor.close()cnx.close()# 批量创建用户的时候,随机产生的用户名可能会发生重复,必须检测是否重复
# 只有检测可用的才会返回
def createUserName():while True:random.shuffle(words)username = ''.join(random.choices(words, k=random.randint(6, 15)))if not checkUser(username) and username not in users:users.append(username)breakprint('>'*5, username)return username# 查询用户名是否存在
def checkUser(username):sql = "select * from users where username='{username}'".format(username=username)print(sql)try:cursor.execute(sql)     # .format(**{"username": username})except connector.Error as e:print(e)res = cursor.fetchone()return resfor i in range(10):createBatchUsers()

运行报错
用python代码自动随机生成mysql数据中的错误--Cursor is not connected
然后我把users表里所有的字段全都改成了VARCHAR(45)

ALTER TABLE `mydb`.`users` 
CHANGE COLUMN `city` `city` VARCHAR(45) NULL DEFAULT NULL ,
CHANGE COLUMN `mylike` `mylike` VARCHAR(45) NULL DEFAULT NULL ,
CHANGE COLUMN `sex` `sex` VARCHAR(45) NULL DEFAULT NULL ;

然后再运行pycharm里的代码就好啦!!!

  相关解决方案