任务如下:
创建一个表,里面有10000万测试数据,可以最好写成脚本,一遍不断的修改
思路:
1、使用excel的编辑功能,弄10000行insert into的语句
2、整理一个初步的excel,写脚本读取excel,使用excel来来控制建表和测试数据。
方法:
采用第二条
步骤:
1、编辑excel,第一行:字段名,第二行:字段类型;第三行:字段长度;第四行:not null
Python读取excel创建10000行mysql测试表
2、第二步编写Python代码,读取excel,完成数据的读取和插入操作


import pymysql

import xlrd

import traceback
#读取文件
data=xlrd.open_workbook('data.xlsx')
#通过索引顺序获取
table=data.sheets()[0]
#获取行数
nrows=table.nrows
#获取列数
ncols=table.ncols

table_cell_date=[]

create_sql_part=''
sql_insert=''
#获取第一行的数据
rows_first_name = table.row_values(0)
#循环第一行,获取第二行,第三行对应的类型及其字段长度
for i in  range(len(rows_first_name)):
    table_name=table.row(0)[i].value
    table_type=table.row(1)[i].value
    tbale_type_length=table.row(2)[i].value
    table_not_null=table.row(3)[i].value
    create_sql_part=create_sql_part+"`"+table_name+"` "+table_type+"("+str(int(tbale_type_length))+") "+table_not_null+","
    sql_insert=sql_insert+table_name+","
create_sql="CREATE TABLE IF NOT EXISTS TEST_DB ("+create_sql_part.rstrip(',')+")"
print("create_sql===="+create_sql)
#打开数据库连接
db =pymysql.connect("192.168.66.102","geexek","neusoft","TESTDB",charset='utf8')
#使用 cursor()方法创建游标对象cursor
cursor=db.cursor()

#使用execte()方法执行sql,如果表存在则删除
cursor.execute(create_sql)



sql_insert_db=""
sql_insert_db_part=""
#获取从第五行到最后一行的数据,然后构建插入语句,然后到数据库中。
for i in range(4,nrows):
    cells_date = table.row_values(i)
    for j in range(len(cells_date)):
        ctype=table.cell(i, j).ctype
        cell=table.cell_value(i, j)
        if ctype == 2 and cell % 1 == 0:
            cell_value=int(cell)
        else:
            cell_value="'"+str(cell)+"'"
        sql_insert_db_part=sql_insert_db_part+str(cell_value)+","
    sql_insert_db=sql_insert_db+"("+sql_insert_db_part.rstrip(',')+"),"
    sql_insert_db_part=""
sql_insert_head = "INSERT INTO TEST_DB (" + sql_insert.rstrip(',') + ") VALUES "+sql_insert_db.rstrip(',')

print("sql_insert_head="+sql_insert_head)
try:
    #执行sql语句
    # 读取数据,然后循环插入
    for k in range(1000):
        cursor.execute(sql_insert_head)
        #提交到数据库执行
        db.commit()
except:
    #如果发生错误则回滚
    traceback.print_exc()
    db.rollback()
finally:
    #关闭数据库连接
    db.close()

第三步、查看数据库执行结果
Python读取excel创建10000行mysql测试表

相关文章:

  • 2021-04-16
  • 2021-11-14
  • 2022-12-23
  • 2022-02-08
  • 2021-08-11
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2021-12-03
  • 2021-10-09
  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案