python 批量创建 表 及表数据
作者:互联网
# 导入pymysql
import pymysql
# 创建连接
con = pymysql.connect(host="localhost", user="root", password="123456", database="howk", port=3306)
# 创建游标对象
cur = con.cursor()
# 编写创建表的sql
for num in range(21, 23):
# print (num)
tablename = "user" + str(num)
print(tablename)
# sql = "CREATE TABLE %s (col1 INT PRIMARY KEY NOT NULL,nane varchar(300) )" % tablename
sql = "CREATE TABLE %s (userid int(4) primary key not null auto_increment,name varchar(300) )" % tablename
try:
# 执行创建表的sql
cur.execute(sql)
import time
time.sleep(1)
for i in range(1,10):
sql = 'insert into %s (name) values("name%s")'%(tablename,i)
cur.execute(sql) # 第二个参数可以是元组也可以是列表
con.commit()
print("创建表成功")
except Exception as e:
print(e)
print("创建表失败")
# for num in range(14, 15):
cur.close()
# 关闭数据库连接
con.close()
标签:cur,批量,python,创建,tablename,num,及表,sql,print 来源: https://www.cnblogs.com/ZhiXiaoBbai/p/16285012.html