仅从数据库获取更新的数据

时间:2015-12-14 10:12:38

标签: python sqlite python-2.7 pyodbc

我必须从数据库中获取最近更新的数据。为了解决它,我将最后读取的行号保存到python的shelve中。以下代码适用于select * from rows之类的简单查询。我的代码是:

from pyodbc import connect
from peewee import *
import random
import shelve
import connection


d = shelve.open("data.shelve")
db = SqliteDatabase("data.db")
class Rows(Model):
    valueone = IntegerField()
    valuetwo = IntegerField()

    class Meta:
        database = db

def CreateAndPopulate():
    db.connect()
    db.create_tables([Rows],safe=True)
    with db.atomic():
        for i in range(100):
            row = Rows(valueone=random.randrange(0,100),valuetwo=random.randrange(0,100))
            row.save()
    db.close()

def get_last_primay_key():
    return d.get('max_row',0)

def doWork():
    query = "select * from rows" #could be anything
    conn = connection.Connection("localhost","","SQLite3 ODBC Driver","data.db","","")
    max_key_query = "SELECT MAX(%s) from %s" % ("id", "rows")
    max_primary_key = conn.fetch_one(max_key_query)[0]
    print "max_primary_key " + str(max_primary_key)
    last_primary_key = get_last_primay_key()
    print "last_primary_key " + str(last_primary_key)
    if max_primary_key == last_primary_key:
        print "no new records"
    elif max_primary_key > last_primary_key:
        print "There are some datas"
        optimizedQuery = query + " where id>" + str(last_primary_key) 
        print query
        for data in conn.fetch_all(optimizedQuery):
            print data
        d['max_row'] = max_primary_key
    # print d['max_row']

# CreateAndPopulate() # to populate data
doWork()

虽然代码适用于没有where子句的简单查询,但查询可以是从简单到复杂的任何内容,包含joins和多个where子句。如果是这样,那么我添加where的部分将失败。如何从查询中获取数据库中的最新更新数据?

PS:我无法修改数据库。我只需要从中获取。

1 个答案:

答案 0 :(得分:0)

使用OFFSET子句。例如:

SELECT * FROM [....] WHERE [....] LIMIT -1 OFFSET 1000

在您的查询中,将1000替换为绑定到shelve变量的参数。这将跳过顶部“搁置”数量的行,只抓住更新的行。你可能最终会考虑一个更强大的重构,但祝你好运。