Sqlite3无法从数据库中读取

时间:2016-05-30 10:05:10

标签: python mysql database sqlite

我有一个包含两列的数据库。一个是主键自动增量,另一个是url列。第一个被命名为' id'第二个被命名为' longurls'。我已经运行了以下代码来检索一个' id'记录longurls =' X'价值。

import sqlite3
long_url = 'http://www.google.com'
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("SELECT id FROM stuff WHERE longurls=?",(long_url,))
k = c.fetchall()
for stuff in k:
    id = stuff[0]
print (id)

This is a picture showing the url exists in database。只有'没有'打印

2 个答案:

答案 0 :(得分:0)

我还没有在Python中使用sqlite,但是对我来说看起来很奇怪的代码是

for stuff in k:
    id = stuff[0]
print (id)

如果在循环外定义id,会发生什么?

id = 0
for stuff in k:
    id = stuff[0]
print (id)

如果您可以返回ID列表,则需要进一步修改

答案 1 :(得分:0)

import sqlite3 as lite
import sys

long_url = 'http://www.google.com'

con = lite.connect('database.db')

with con:    

    cur = con.cursor()    
    cur.execute("SELECT * FROM stuff WHERE longurls=?",(long_url,))
    rows = cur.fetchall()
    for row in rows:
        print row