码迷,mamicode.com
首页 > 数据库 > 详细

将随机生成学生的数据导入Mysql

时间:2020-09-18 01:14:07      阅读:38      评论:0      收藏:0      [点我收藏+]

标签:code   pwd   top   port   ret   生成   NPU   学生   class   

import random
from random import choice as choice
import mysql.connector
import string
def Create_Name():
    first_name = [,"","","","",""]
    second_name = ["","","","","",""]
    last_name = [,"","","","",""]
    name = choice(first_name)+choice(second_name)+choice(last_name)
    return name.rstrip()
def Create_class():
    Class = 0123456 
    Class_name = 三年+choice(Class)+
    return Class_name.rstrip()
def Create_Gender():
    Gender=[,]
    Gender_set=choice(Gender)
    return Gender_set.rstrip()
def Create_Age():
    Age_set=random.randint(18,21)
    return Age_set
def Create_Height():
    Height_set=random.randint(150,190)
    return Height_set
def Create_Teacher():
    Teacher = [李明,王森,赵刚,林丹]
    Teacher_name=choice(Teacher)
    return Teacher_name.rstrip()

def Create_Subject(Teacher_name):
    Teacher_name=Teacher_name
    if Teacher_name == 李明:
        Subject=数学
    elif Teacher_name == 王森:
        Subject=语文
    elif Teacher_name == 赵刚:
        Subject =英语
    elif Teacher_name == 林丹:
        Subject =物理
    return Subject.rstrip()
def Create_Score():
    Score_set=random.randint(50,100)
    return Score_set
def Create_StudentNo():
    StudentNo_set= random.randint(1001,1028)
    return StudentNo_set
def main():
    mydb=mysql.connector.connect(
      host=localhost,
      user=username,
      passwd=pwd,
      database=data
    )
    cursor = mydb.cursor()
    n=int(input("生成数据数:"))
    for i in range(n):
        name = Create_Teacher()
        #sql_Student=‘INSERT INTO Student (Name,Class) values ("%s","%s")‘
        #cursor.execute(sql_Student,(Create_Name(),Create_class()))
        sql_Score = INSERT INTO Score (StudentNo,Subject,Teacher,Score) values ("%s","%s","%s","%s")
        cursor.execute(sql_Score,(Create_StudentNo(),Create_Subject(name),name,Create_Score()))
    mydb.commit()
    cursor.close()
main()

其中碰到了一个坑在

sql_Score = INSERT INTO Score (StudentNo,Subject,Teacher,Score) values ("%s","%s","%s","%s")

这里虽然导入的StudentNo和Score是int型的数据,但是因为MySQL的参数标记与Python格式化字符串中使用的%s看起来相同,但使用是不同的。所以无论是数字(包括整数和浮点数)、字符串、日期时间或其他任意类型,都应该使用%s占位符。

 

 

将随机生成学生的数据导入Mysql

标签:code   pwd   top   port   ret   生成   NPU   学生   class   

原文地址:https://www.cnblogs.com/Mangnolia/p/13667322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!