mysql数据处理之插入数据
目的
实现数据插入到mysql,比如我们需要插入1w+数据到数据,可以通过这种方式插入,或者也可以将python 自动化的数据,报存到数据库中。
1、连接数据库
import pymysql
import os
import time
class datas():def __init__(self):host = '127.0.0.1'port = 3306usr = 'root'pwd = '123456'self.data_connect = pymysql.connect(host=host, port=port, database='creat_data', user=usr, password=pwd,charset='utf8')if self.data_connect:print('连接成功')# 官网地址:https://pymysql.readthedocs.io/en/latest/user/examples.html
2、 执行sql语句
def craet_data(self,product_name,client):"""执行sql语句插入数据"""cur = self.data_connect.cursor() # 创建游标,目的执行sql语句sql = f'insert into yjrz_2022(product_name,client) value (%s,%s)'# cur.execute('insert into yjrz_2022(product_name,client) value ("01","02")')#select = cur.execute('select count(id) from yjrz_2022') # 查询记录inset_data = cur.execute(sql,(product_name,client)) # 插入数据# print(cur.fetchall())self.data_connect.commit() # 提交数据cur.close() # 关闭游标# data_connect.close() # 断开是数据库,释放资源通过cmd查询结果;
if __name__ == '__main__':for i in range(1,10):t = datas()t.craet_data('移动','test')