python字典存入csv和mysql
存入csv
from config.globalparameter import execl_save import pandas as pd title = ['这是一个标题', '标题 2'] price = [23.45, 22.00] deal = [5, 100] location = ['广东 广州', '北京'] province = ['广东', '北京'] city = ['广州', '北京'] shop = ['门店', '门店 2'] result = [1, 0] # 构建商品信息字典 product = { 'title': title, 'price': price, 'deal': deal, 'location': location, 'province': province, 'city': city, 'shop': shop, 'isPostFree': result } df = pd.DataFrame(product) df.to_csv(execl_save, index=False, encoding='gbk')
存入mysql
pip3 install pymysql
pip3 install pyquery
导入
from pyquery import PyQuery as pq
数据库连接情况(数据库的表和字段要先建好)
# 数据库中要插入的表 MYSQL_TABLE = 'goods' # MySQL 数据库连接配置,根据自己的本地数据库修改 db_config = { 'host': 'localhost', 'port': 3306, 'user': 'root', 'password': 'm*******', 'database': 'may2024', 'charset': 'utf8mb4', } # 创建 MySQL 连接对象 conn = pymysql.connect(**db_config) cursor = conn.cursor()
# 构建商品信息字典 product = { 'title': title, 'price': price, 'deal': deal, 'location': location, 'province': province, 'city': city, 'shop': shop, 'isPostFree': result } try: sql = "INSERT INTO {}(price, deal, title, shop, location, province, city, isPostFree) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)".format(MYSQL_TABLE) print("sql语句为: " + sql) cursor.execute(sql, (product['price'], product['deal'], product['title'], product['shop'], product['location'], product['province'], product['city'], product['isPostFree'])) conn.commit() # cursor.close() # conn.close() print('存储到MySQL成功: ', product) except Exception as e: print('存储到MYsql出错: ', product, e)