python mysql操作问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python mysql操作问题相关的知识,希望对你有一定的参考价值。
我用python从mysql中读取出两个表的内容代码如下:
import MySQLdb
conn = MySQLdb.connect(host="x.x.x.x",user="xxx",passwd="xxx",db="xxxx" ,charset="UTF8")
cursor=conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
def fuc1(self):
cursor.execute("select * from table1")
rows= cursor.fetchall()
a=
for row in rows:
a["me"]=row["Fm"]
print a
def fuc2(self):
b=
cursor.execute("select * from table2")
rows= cursor.fetchall()
for row in rows:
b["pa"]=row["Fp"]
print b
a和b的输出都是字典。我想把这两个字典合成一个应该怎么做?
dict2 = self.fun2()
def newdict(self):
dict =
for k,v in dict1.items():
dict[k] = v
for k1,v1 in dict2.items():
dict[k1] = v1
return dict追问
谢谢回答! 这样之后合并的是a字典和b字典的最后一个值,并没有把a和b字典所有的值都合并出来
这是为什么呢?
谢谢回答! 这样之后合并的是a字典和b字典的最后一个值,并没有把a和b字典所有的值都合并出来
这是为什么呢
插入错误 Python MySQL 连接器:执行操作失败
【中文标题】插入错误 Python MySQL 连接器:执行操作失败【英文标题】:INSERT Error Python MySQL Connector: Failed executing the operation 【发布时间】:2021-12-05 02:45:27 【问题描述】:我正在使用 products.json 页面抓取 shopify 商店。尝试使用 Python 连接器将抓取的产品插入我的 MySQL 数据库,但遇到以下错误:
出了点问题:执行操作失败; b'
Name
'
代码如下:
import json
import pandas as pd
import mysql.connector
import ScraperConfig as conf
class myScraper():
def __init__(self, baseurl):
self.baseurl = baseurl
def downloadjson(self, page):
r = requests.get(self.baseurl + f'products.json?limit=250&page=page', timeout=5)
if r.status_code != 200:
print('Bad status code', r.status_code)
if len(r.json()['products']) > 0:
data = r.json()['products']
return data
else:
return
def parsejson(self, jsondata):
products = []
for prod in jsondata:
vendor = prod['vendor']
name = prod['title']
handle = prod['handle']
createdDateTime = prod['created_at']
description = prod['body_html']
productType = prod['product_type']
for images in prod['images']:
vendorProductId = images['product_id']
try:
imageURL = images['src']
except:
imageURL = 'None'
for variant in prod['variants']:
item =
'name': name,
'handle': handle,
'description': description,
'productVariantId': variant['id'],
'createdDateTime': createdDateTime,
'productType': productType,
'vendorProductId': vendorProductId,
'imageURL': imageURL,
'price': variant['price'],
'salePrice': variant['compare_at_price'],
'available': variant['available'],
'updatedDateTime': variant['updated_at'],
'vendor': vendor
products.append(item)
return products
def main():
scrape = Scraper('https://www.someshopifysite.com/')
results = []
for page in range(1,2):
data = scrape.downloadjson(page)
print('Getting page: ', page)
try:
results.append(scrape.parsejson(data))
except:
print(f'Completed, total pages = page - 1')
break
return results
if __name__ == '__main__':
db = mysql.connector.connect(
user=conf.user,
host=conf.host,
passwd=conf.passwd,
database=conf.database)
cursor = db.cursor()
products = main()
totals = [item for i in products for item in i]
for p in totals:
sql = """INSERT INTO `table` (`Name`, `Handle`, `Descritpion`, `VariantId`, `CreatedDateTime`, `ProductType`, `VendorProductId`, `ImageURL`, `Price`, `SalePrice`, `Available`, `UpdatedDateTime`, `Vendor`)
VALUES (%(`Name`)s, %(`Handle`)s, %(`Descritpion`)s, %(`VariantId`)s, %(`CreatedDateTime`)s, %(`ProductType`)s, %(`VendorProductId`)s, %(`ImageURL`)s, %(`Price`)s, %(`SalePrice`)s, %(`Available`)s, %(`UpdatedDateTime`)s, %(`Vendor`)s)"""
try:
cursor.executemany(sql, totals)
print('Committed to DB')
except mysql.connector.Error as err:
print("Something went wrong: ".format(err))
db.commit() ```
【问题讨论】:
【参考方案1】:从查询的以下和所有类似部分中删除反引号:
%(`Name`)s
通常我会删除反引号,除了引用映射到关键字的列名。
【讨论】:
试过了。不幸的是没有骰子。错误:出了点问题:执行操作失败; b'名字'以上是关于python mysql操作问题的主要内容,如果未能解决你的问题,请参考以下文章
48-mysql-Navicat数据库查询题目讲解(多表操作)python操作MySQLsql注入问题pymysql模块增删改查数据操作