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

2022-05-02 22:42:08 字數 2753 閱讀 3804

import

random

from random import

choice as choice

import

mysql.connector

import

string

defcreate_name():

first_name = ['

趙',"

錢","

孫","

李","

王","林"

] second_name = ["

林","

明","

群","

威","

慶","月"

] last_name = ['

群',"

寧","

國","

龍","

丹","昊"

] name = choice(first_name)+choice(second_name)+choice(last_name)

return

name.rstrip()

defcreate_class():

class = '

0123456

'class_name = '

三年'+choice(class)+'班'

return

class_name.rstrip()

defcreate_gender():

gender=['

男','女'

] gender_set=choice(gender)

return

gender_set.rstrip()

defcreate_age():

age_set=random.randint(18,21)

return

age_set

defcreate_height():

height_set=random.randint(150,190)

return

height_set

defcreate_teacher():

teacher = ['

李明','

王森','

趙剛','林丹'

] teacher_name=choice(teacher)

return

teacher_name.rstrip()

defcreate_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()

defcreate_score():

score_set=random.randint(50,100)

return

score_set

defcreate_studentno():

studentno_set= random.randint(1001,1028)

return

studentno_set

defmain():

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

使用spoon將資料從hive匯入mysql

1.spoon dir來指定匯出的目錄 spoon export connect jdbc mysql ip 埠號 資料庫名 user username password password table table name exprot dir hive中的路徑 2.update mode資料更新插...

php將json格式的資料直接存入mysql資料庫

直接使用php函式json encode,資料存入mysql時會報錯 php imgs str json encode imgs array imgs str addslashes imgs str update query updatearticleset imagelist imgs str w...

php將json格式的資料直接存入mysql資料庫

直接使用php函式json encode,資料存入mysql時會報錯 imgs str json encode imgs array imgs str addslashes imgs str update query updatearticleset imagelist imgs str where...