【问题标题】:Error when getting values from SQLite table [closed]从 SQLite 表中获取值时出错 [关闭]
【发布时间】:2017-06-27 06:30:40
【问题描述】:

编辑:原来我犯了一个愚蠢的错字,谢谢你的帮助!

我想从一个 sqlite 表中获取值,我使用fetchnone() 来获取最后一行的值。但是调用该函数时出现未知错误

'sqlite3.Cursor' object has no attribute 'fetchnone' 

这是我的重定向功能代码,我不知道错误在哪里

@app.route('/<short_url>')
def redirect(short_url):
    conn = sqlite3.connect('url.db')
    cursor = conn.cursor()

    result_cur = cursor.execute("SELECT URL FROM WEB_URL WHERE S_URL = ?;" ,(short_url,) )
    try:
        redirect_url = result_cur.fetchnone()
        print redirect_url

        conn.close()
        return redirect(redirect_url)   
    except Exception as e:
        error  = e 
        return render_template('index.html' , error = error)

谢谢!

编辑:

我知道这违反了 Stackoverflow 的一些规则,但我想问另一个关于重定向的问题:

我正在尝试构建 URL 缩短器,但在将用户重定向到更长的 URL 时出现错误。我已将 SQLite 用于数据库。 这是我的重定向代码:

@app.route('/<short_url>')
def redirect(short_url):
    conn = sqlite3.connect('url.db')
    cursor = conn.cursor()

    result_cur = cursor.execute("SELECT URL FROM WEB_URL WHERE S_URL = ?;" ,(short_url,) )
    try:
        redirect_url = result_cur.fetchone()[0]
        print redirect_url

        conn.close()
        return redirect(redirect_url , code = 200)  
    except Exception as e:
        error  = e 
        return render_template('index.html' , error = error)

fetchone()[0] 确实返回了正确的长 URL,但在单击生成的短 URL 时出现此错误

 'NoneType' object has no attribute '__getitem__' 

不应该有NoneError,因为我从数据库中获取了一个值。

【问题讨论】:

  • [Clippy] 你的意思是fetchone()
  • 是的,我用过 fetchnone()[0]
  • 你已经获取 none,你想要获取 一个
  • 是的,我注意到了,非常感谢!
  • 请发布一个新问题,而不是编辑这个问题。

标签: python sqlite flask


【解决方案1】:

您有错字:fetchone() 是正确的方法。

参考:https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.fetchone

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2020-01-26
    • 2023-03-28
    相关资源
    最近更新 更多