python——Faker库生成测试数据写入数据库

安装Faker

pip install Faker
from faker import Faker
import pandas as pd
from urllib import parse
import pymysql


class CreateData(object):
    def __init__(self):
        # 选择中文
        fake = Faker('zh_CN')
        self.data_total = [
            [
                fake.name(),
                fake.job(),
                fake.company(),
                fake.phone_number(),
                fake.company_email(),
                fake.address(),
                fake.date_time(tzinfo=None)
            ]
            for x in range(100)
        ]
        print(self.data_total)

    def deal_excel(self):
        """创建数据写入excel"""
        df = pd.DataFrame(self.data_total,
                          columns=['name', 'job', 'company',
                                   'phone_number', 'company_email',
                                   'address', 'date_time'])
        # 写入excel
        df.to_excel("data_total.xlsx", index=False)
        print('写入成功!!')

    def deal_txt(self):
        """创建数据写入txt文件"""
        with open('data_total.txt', 'w', errors='ignore', encoding='utf-8') as output:
            output.write('name,job,company,phone_number.company_email.address.date_time\n')
            for row in self.data_total:
                rowtxt = '{},{},{},{}'.format(row[0], row[1], row[2], row[3])
                output.write(rowtxt)
                output.write('\n')
            output.close()
        print("Processing completed to txt")

    def deal_mysql(self):
        """创建数据写入mysql"""
        # 数据库配置
        db = pymysql.connect(host="127.0.0.1",
                             port=3306,
                             user="root",
                             password="123456",
                             db="lp_cs",
                             charset="utf8")
        # 获取操作游标
        cursor = db.cursor()
        # 创建表
        sql = '''
            create table test_data(
                name varchar(20) not null comment '姓名',
                job varchar(20) not null comment '工作',
                company varchar(64) not null comment '单位',
                phone_number varchar(30) not null  comment '电话号码',
                company_email varchar(64) comment '公司邮箱',
                address varchar(64) comment '地址',
                date_time datetime comment '时间'
            )
        '''
        # 执行sql
        cursor.execute(sql)

        for val in self.data_total:
            sql = "insert into test_data" \
                  "(name,job,company,phone_number,company_email,address,date_time) value ('%s','%s','%s','%s','%s','%s','%s')" % (
                val[0], val[1], val[2], val[3], val[4], val[5], val[6])
            try:
                # 执行sql语句
                cursor.execute(sql)
                # 执行sql语句
                db.commit()
                print("insert ok")
            except:
                # 发生错误时回滚
                db.rollback()
            # 关闭数据库连接


if __name__ == '__main__':
    data = CreateData()
    data.deal_excel()
    data.deal_txt()
    data.deal_mysql()

txt:
python——Faker库生成测试数据写入数据库_第1张图片
excel:
python——Faker库生成测试数据写入数据库_第2张图片
mysql
python——Faker库生成测试数据写入数据库_第3张图片

你可能感兴趣的:(#,python,练习,python,sql)