0002-存入mysql数据库

代码

import pymysql
import string
import random

KEY_VALUE = 20
KEY_NUMBER = 200

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
                       passwd='passwd', db='python_practice')

def all_str():
    return string.ascii_letters + string.digits


def insert_into_db(cur, data):   # 特别愚蠢的写法
    sql_insert_into_table = 'insert into voucher(key_value) VALUE (%s)'
    cur.execute(sql_insert_into_table, data)
    conn.commit()


def query_data(cur):
    sql_query_db = 'select * from voucher WHERE id BETWEEN  20 AND 30'
    cur.execute(sql_query_db)
    for i in cur.fetchall():
        print(i)
    conn.commit()


def insert_datas(cur, list):
    sql_insert_datas = 'insert into voucher(key_value) VALUES (%s)'
    cur.executemany(sql_insert_datas, list)
    conn.commit()


def delete_data(cur):
    sql_delete_data = 'delete from voucher WHERE id = 2'
    cur.execute(sql_delete_data)
    conn.commit()

with conn.cursor() as cur:
    result = []
    for i in range(200):
        st = [random.choice(all_str()) for j in range(20)]
        st = ''.join(st)
        result.append(st)
    insert_datas(cur, result)
    query_data(cur)
    delete_data(cur)



新知识

多条插入时,用executemany语句,不要使用insert_into_db中那样的写法,效率很低
自增的主键:id INT(20) not null AUTO_INCREMENT,primary key (id)

你可能感兴趣的:(0002-存入mysql数据库)