python 实现mysql的建表,插入随机数据

创建表

输入要创建的表明,然后输入字段+类型+一些关键字,字段这里是无限循环,输入end结束

插入数据

插入数据,首先输入想要插入多少条数据,最终程序就会往表中插入多少条随机的数据
用法:

  • 先输入表名
  • 无限循环输入字段名
  • 字段对应的类型,目前只支持int和char两种类型。输入其他值会中断报错。
  • 输入end结束
    输入end结束以后,程序就会自动往数据表中插入生成的随机数据。
import pymysql
import random
import string
 
def varchar(num):
    return "VARCHAR("+str(num)+")"

def createTable(cursor):
    sql = "CREATE TABLE "
    tableName = input("Please input table name: ")
    sql = sql + tableName + "("
    while(1):
        print("\nInput 'end' to end.")
        colName = input("Please input col name and attribute: ")
        if(colName == "end"):
            break
        sql = sql + colName + ", "

    sql = sql[:-2] + ")"
    print("sql: ",sql)

    cursor.execute(sql)
    data = cursor.fetchone()
     
    print ("Result: ", data)

def random_str(randomlength=16):
    """
    生成一个指定长度的随机字符串
    """
    str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]
    random_str = ''.join(str_list)
    return random_str

def random_int(randomlength=16):
    """
    生成一个指定长度的随机数字
    """
    str_list = [random.choice(string.digits) for i in range(randomlength)]
    random_str = ''.join(str_list)
    return random_str

def insertData(cursor,db,n):
    print("\nUsage:")
    print("First, input table name")
    print("Second, input one col name")
    print("Then, input the colname's type. here is two type to choose: 'int' and 'char' ")
    print("These type's length are 6 (default)\n")
    print("Then, input the next colname and its type while the last colname")
    sql = "insert into "
    tableName = input("\nPlease input table name:")
    sql = sql + tableName + "("
    coltype = []
    flag = 1
    while(1):
        print("\nInput 'end' to end.")
        colName = input("Please input col name:")
        if(colName == 'end'):
            break;
        sql = sql + colName + ", "
        ctype = input("Please input col type:")
        if(ctype == 'int'):
            coltype.append(0)
        elif(ctype == 'char'):
            coltype.append(1)
        else:
            flag = 0;
            print("col type error!")
            print("Program exit!!")
            break;
        
    sql = sql[:-2] + ") values("
    tmpsql = sql
    if(flag == 1):
        for k in range(0,n):
            sql = tmpsql
            for i in coltype:
                if(i == 0):
                    sql = sql + random_int(6) + ", "
                else:
                    sql = sql + "'" + random_str(6) + "'" + ", "
            sql = sql[:-2] + ")"
            print("sql: ",sql)
            
            cursor.execute(sql)
            db.commit()
            print ("Success ")    
    else:
        print("Program encounter error!!")

'''
2022.1.14

'''
if __name__ == '__main__':
    # 打开数据库连接
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='1234',
                         database='testdb')
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
  
    while(1):
        print("\nWelcome !!")
        print("1. Create Tbale ")
        print("2. Insert Data ")
        print("0. Exit ")
        num = input("Please input execute code:")
        if(num == '0'):
            print("Program exit !!")
            break;
        if(num == '1'):
            createTable(cursor)
        elif(num == '2'):
            n = input("Please input the number of data: ")
            insertData(cursor,db,int(n))
            print()


    # 关闭数据库连接
    db.close() 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值