python 往MySQL批量插入數據


在工作用有時候需要批量造測試數據;手工造太麻煩了,可以通過python批量插入表數據

 

'''批量插入sql語句'''
import pymysql,string,random,time
def connet_mysql():
    try:
        db=pymysql.connect(host='192.168.31.103',user='root',password='123456',
                           db='test',port=3306)
    except Exception as e:
        print('數據庫連接失敗',e)
    return db

def insert_data(id,username,password):
    db=connet_mysql()
    cursor=db.cursor()
    sql_1='insert into user_test(id,user,password)values (%s,%s,%s)'
    sql_2='select * from user_test'
    params=(id,username,password)
    cursor.execute(sql_1,params)
    cursor.execute(sql_2)
    db.commit()
    all=cursor.fetchall()#通過游標,獲取查詢內容
    print(all)

def info():
    str_1d=string.digits
    str_2a=string.ascii_letters
    str_3=str_1d+str_2a
    for i in range(501,601):
        id=i
        username='user'+str(i)
        password=''.join(random.sample(str_3,6))
        insert_data(id,username,password)
if __name__ == '__main__':
    info()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM