1. 程式人生 > 實用技巧 >將隨機生成學生的資料匯入Mysql

將隨機生成學生的資料匯入Mysql

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佔位符。