gpt4 book ai didi

python - 错误 : 'str' object has no attribute 'to_sql'

转载 作者:行者123 更新时间:2023-11-28 23:11:01 28 4
gpt4 key购买 nike

我是编码新手,这是我的第一个项目。到目前为止,我已经通过谷歌搜索、教程和堆栈拼凑了我的所有内容。

我正在尝试将数据从抓取的 RSS 提要的 pandas df 添加到远程 sql 数据库。我一直在使用 this post 的组合和 this post修复我的错误,但答案似乎不适用于我的问题。

有没有人有解决错误的潜在方法:


AttributeError Traceback (most recent call last) in () 19 cursor.execute(sql) 20 ---> 21 sql.to_sql(df, con=conn, name='rsstracker', if_exists='append', flavor='mysql') 22 23 # disconnect from server

AttributeError: 'str' object has no attribute 'to_sql'

import pandas as pd
from pandas.io import sql
import feedparser
import time

rawrss = ['http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml',
'https://www.yahoo.com/news/rss/',
'http://www.huffingtonpost.co.uk/feeds/index.xml',
'http://feeds.feedburner.com/TechCrunch/',
]

posts = []
for url in rawrss:
feed = feedparser.parse(url)
for post in feed.entries:
posts.append((post.title, post.link, post.summary))
df = pd.DataFrame(posts, columns=['title', 'link', 'summary']) # pass data to init

import pymysql

# Open database connection
db = pymysql.connect(host="host", port=##, user="username", password="password", db="sql#######" )

# prepare a cursor object using cursor() method
cursor = db.cursor()


# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS rsstracker")

# Create table as per requirement
sql = """CREATE TABLE rsstracker(
article_title varchar(255),
article_url varchar(1000),
article_summary varchar(1000))"""

cursor.execute(sql)

sql.to_sql(df, con=conn, name='rsstracker', if_exists='append', flavor='mysql')

# disconnect from server
db.close()

最佳答案

该行应该是:

df.to_sql(con=db, name='rsstracker', if_exists='append', flavor='mysql')

但您可能需要使用 SQLAlchemy 才能进行此导出 (doc)


您可以尝试将 SQLAlchemy 与 pymysql 一起使用,如下所示:

import pymysql
from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://<username>:<password>@<host>[:<port>]/<dbname>')
engine.execute("DROP TABLE IF EXISTS rsstracker")
engine.execute("""CREATE TABLE rsstracker(
article_title varchar(255),
article_url varchar(1000),
article_summary varchar(1000))""")


df.to_sql(con=engine, name='rsstracker', if_exists='append', , flavor='mysql')

关于python - 错误 : 'str' object has no attribute 'to_sql' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45969398/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com