使用指令碼向資料庫構造測試資料
阿新 • • 發佈:2019-01-31
1.sql語句的使用
2.sql語句變數的格式化輸出
sql='''insert into student values(null,'%s',%s,%s,'%s',%s,%s);'''%(name,sage,ssex,hometown,high,class_id)注意一點,在sql語句中格式化輸出,如果漢字的話%S也不要加引號,與其他的格式化輸出不同。切記
3.radom隨機模組的使用
4.初始化資料庫使用
truncate table 表名
不能使用delete from 表名。如果這樣的話Id會在上次的基礎上增加。
# -*- coding:utf-8 -*- import random importMySQLdb # 開啟資料庫連線 db=MySQLdb.connect(host="127.0.0.1",user="root",passwd="123456",db="cs",charset="utf8") # 使用cursor()方法獲取操作遊標 cursor = db.cursor() list_Xing=['趙','錢','孫','李','周','吳','鄭','王','馮','陳','褚','衛','蔣','沈','韓','楊','張','李'] list_Ming=['豫','章','故','郡','洪','都','新','府','星','分','翼','軫','地','接','衡','餞','子'] list_Hometown=['北京','河北','河南','天津','海南','蘭州','內蒙古','甘肅','西藏','新疆','東北'] #初始化測試資料 # sql1='delete from student;'不能使用delete from 表名。如果這樣的話Id會在上次的基礎上增加。 sql1='truncate table student;' try: cursor.execute(sql1) db.commit() except: db.rollback() n=0 while n<20: n=n+1 name = random.choice(list_Xing) + random.choice(list_Ming) + random.choice(list_Ming) sage=random.randint(15,25) ssex=random.randint(1,2) hometown=random.choice(list_Hometown) high=random.randint(155,190) class_id=random.randint(1,6) # print name sql='''insert into student values(null,'%s',%s,%s,'%s',%s,%s);'''%(name,sage,ssex,hometown,high,class_id) print sql # sql1 = "insert into student values(null,'{0}',18,1,'北京',175,2);".format(name) try: cursor.execute(sql) except: db.rollback() try: # 提交到資料庫執行 db.commit() except: # Rollback in case there is any error 發生錯誤時回滾 db.rollback()
# -*- coding:utf-8 -*-
import random
import MySQLdb
# 開啟資料庫連線
db=MySQLdb.connect(host="127.0.0.1",user="root",passwd="123456",db="cs",charset="utf8")
# 使用cursor()方法獲取操作遊標
cursor = db.cursor()
list_Xing=['趙','錢','孫','李','周','吳','鄭','王','馮','陳','褚','衛','蔣','沈','韓','楊','張','李']
list_Ming=['豫','章','故','郡','洪','都','新','府','星','分','翼','軫','地','接','衡','餞','子']
list_Hometown=['北京','河北','河南','天津','海南','蘭州','內蒙古','甘肅','西藏','新疆','東北']
#初始化測試資料
# sql1='delete from student;'不能使用delete from 表名。如果這樣的話Id會在上次的基礎上增加。
sql1='truncate table student;'
try:
cursor.execute(sql1)
db.commit()
except:
db.rollback()
n=0
while n<20:
n=n+1
name = random.choice(list_Xing) + random.choice(list_Ming) + random.choice(list_Ming)
sage=random.randint(15,25)
ssex=random.randint(1,2)
hometown=random.choice(list_Hometown)
high=random.randint(155,190)
class_id=random.randint(1,6)
# print name
sql='''insert into student values(null,'%s',%s,%s,'%s',%s,%s);'''%(name,sage,ssex,hometown,high,class_id)
print sql
# sql1 = "insert into student values(null,'{0}',18,1,'北京',175,2);".format(name)
try:
cursor.execute(sql)
except:
db.rollback()
try:
# 提交到資料庫執行
db.commit()
except:
# Rollback in case there is any error 發生錯誤時回滾
db.rollback()