代码之家  ›  专栏  ›  技术社区  ›  Nick Duddy

PyMySQL错误:“str”对象没有属性“to\u sql”

  •  1
  • Nick Duddy  · 技术社区  · 7 年前

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

    我正在尝试将来自一个RSS提要的数据添加到一个远程sql数据库中。我一直在使用 this post this post

    是否有人有可能解决该错误:


    AttributeError回溯(最近的调用 最后)在() 19光标。执行(sql) 20 ---&燃气轮机;21 sql。到sql(df,con=conn,name='rsstracker',如果存在='append',flavor='mysql') 22 23#断开与服务器的连接

    AttributeError:“str”对象没有属性“to\u 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()
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   PRMoureu    7 年前

    线路应为:

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

    但您可能需要使用SQLAlchemy来实现此导出( doc )


    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')