sqlite3.OperationalError:数据库被锁定 - 如何避免这种情况?

时间:2016-07-30 06:45:20

标签: python sqlite

我使用的是开源的python代码,它基本上会拉入实体的位置,并将这些详细信息实时保存到数据库中。我们称它为扫描程序扫描程序。它保存的DB文件是一个sqlite文件:db.sqlite。

当发生这种情况时,我所讨论的代码是每隔45秒搜索一次db文件,执行select语句来查找某个值。这将工作几次,但在与扫描程序同时运行几分钟后,它们会遇到数据库锁定错误:

  

sqlite3.OperationalError:数据库被锁定

那么我可以对我的代码做些什么来确保不会发生这种锁定。我无法更改扫描程序访问数据库的方式。只有我的程序。

这里的任何帮助都会很棒。我已经看到提到的超时以及线程,但我也不确定。

    from datetime import datetime
    import sqlite3
    import time
    import json

    import tweepy

    def get_api(cfg):
      auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
      auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
      return tweepy.API(auth)


      # Fill in the values noted in previous step here
    cfg = { 
        "consumer_key"        : "X",
        "consumer_secret"     : "X",
        "access_token"        : "X",
        "access_token_secret" : "X" 
        }



    with open('locales/pokemon.en.json') as f:
        pokemon_names = json.load(f)




    currentid = 1
    pokemonid = 96 #test



    while 1==1:

        conn = sqlite3.connect('db.sqlite')
        print "Opened database successfully";

        print "Scanning DB....";
        time.sleep(1)
        cur = conn.execute("SELECT * FROM sightings WHERE pokemon_id = ? and id > ?", (pokemonid, currentid))
        row = cur.fetchone()

        if row is None:
            print "No Pokemon Found \n "
            time.sleep(1)


        while row is not None:

            #get pokemon name
            name = pokemon_names[str(pokemonid)]


            #create expiry time
            datestr = datetime.fromtimestamp(row[3])
            dateoutput = datestr.strftime("%H:%M:%S")

            #create location
            location = "https://www.google.com/maps/place/%s,%s" % (row[5], row[6]) 

            #inform user
            print "%s found! - Building tweet! \n" % (name)
            time.sleep(1)

            #create tweet
            buildtweet = "a wild %s spawned in #Dublin - It will expire at %s. %s #PokemonGo \n "%(name, dateoutput, location)
            #print tweet


            #log
            print buildtweet
            currentid = row[0]
            time.sleep(1)


            #send tweet
            api = get_api(cfg)
            tweet = buildtweet
            try:
                status = api.update_status(status=tweet)
                print "sent!"
            except:
                pass
                print "this tweet failed  \n"
            time.sleep(30)

            row = cur.fetchone()

        cur.close()
        conn.close()


        print "Waiting..... \n "
        time.sleep(45)

    conn.close()

0 个答案:

没有答案