从SQLite表

时间:2017-06-27 06:30:41

标签: python sqlite flask

编辑:原来我犯了一个愚蠢的拼写错误,谢谢你的帮忙!

我想从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]会返回正确的长网址,但点击生成的短网址后,我收到此错误

 'NoneType' object has no attribute '__getitem__' 

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

1 个答案:

答案 0 :(得分:3)

你有拼写错误: fetchone()是正确的方法。

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

相关问题