我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sqlite3.OperationalError()。
def do_full_login(account): lock_network.acquire() time.sleep(locktime) lock_network.release() if account['type'] == 'ptc': login_ptc(account) elif account['type'] == 'google': login_google(account) new_session(account) else: lprint('[{}] Error: Login type should be either ptc or google.'.format(account['num'])) sys.exit() cursor_accs = db_accs.cursor() while True: try: cursor_accs.execute("INSERT OR REPLACE INTO accounts VALUES(?,?,?,?,?,?,?)", [account['user'], account['access_token'], account['access_expire_timestamp'], account['api_url'], 0, '0', '0']) db_accs.commit() return except sqlite3.OperationalError as e: lprint('[-] Sqlite operational error: {}, account: {} Retrying...'.format(e, account['user'])) except sqlite3.InterfaceError as e: lprint('[-] Sqlite interface error: {}, account: {} Retrying...'.format(e, account['user']))
def update_data(): timenow = int(round(time.time(),0)) cursor_data = db_data.cursor() for l in range(0,len(data_buffer)): [pokeid, spawnid, latitude, longitude, expiretime, addinfo] = data_buffer.pop() db_repeat = True while db_repeat: try: cursor_data.execute("INSERT OR REPLACE INTO spawns VALUES(?,?,?,?,?,?,?,?)", [spawnid, round(latitude, 5), round(longitude, 5), addinfo, pokeid, expiretime, timenow, wID]) db_repeat = False except sqlite3.OperationalError as e: lprint('[-] Sqlite operational error: {} Retrying...'.format(e)) while True: try: db_data.commit() return except sqlite3.OperationalError as e: lprint('[-] Sqlite operational error: {} Retrying...'.format(e))
def mget(self, keys): # type: (List[str]) -> List[Optional[bytes]] rows = [] if self.support_mget: try: with self.conn as conn: for somekeys in grouper(self.sqlite_limit_variable_number, keys): keylist = list(somekeys) questionmarks = ','.join(['?'] * len(keylist)) sql = self.kv_mget % questionmarks for row in conn.execute(sql, keylist): rows.append(row) resultdict = dict(rows) # type: Dict[str, bytes] rget = resultdict.get return [rget(k) for k in keys] except sqlite3.OperationalError: self.support_mget = False return [self.__get(k) for k in keys]
def __init__(self, path, threaded=True, timeout=None): """ >>> lock = SQLiteLockFile('somefile') >>> lock = SQLiteLockFile('somefile', threaded=False) """ LockBase.__init__(self, path, threaded, timeout) self.lock_file = unicode(self.lock_file) self.unique_name = unicode(self.unique_name) if SQLiteLockFile.testdb is None: import tempfile _fd, testdb = tempfile.mkstemp() os.close(_fd) os.unlink(testdb) del _fd, tempfile SQLiteLockFile.testdb = testdb import sqlite3 self.connection = sqlite3.connect(SQLiteLockFile.testdb) c = self.connection.cursor() try: c.execute("create table locks" "(" " lock_file varchar(32)," " unique_name varchar(32)" ")") except sqlite3.OperationalError: pass else: self.connection.commit() import atexit atexit.register(os.unlink, SQLiteLockFile.testdb)
def CheckLocking(self): """ This tests the improved concurrency with pysqlite 2.3.4. You needed to roll back con2 before you could commit con1. """ if sqlite.sqlite_version_info < (3, 2, 2): # This will fail (hang) on earlier versions of sqlite. # Determine exact version it was fixed. 3.2.1 hangs. return self.cur1.execute("create table test(i)") self.cur1.execute("insert into test(i) values (5)") try: self.cur2.execute("insert into test(i) values (5)") self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass except: self.fail("should have raised an OperationalError") # NO self.con2.rollback() HERE!!! self.con1.commit()
def getTableVersion(self, table_name): """if not self.table_names: # Get existing table names res = self.cur.execute("SELECT name FROM sqlite_master WHERE type='table'") self.table_names = [row["name"] for row in res] if table_name not in self.table_names: return False else:""" if not self.db_keyvalues: # Get db keyvalues try: res = self.cur.execute("SELECT * FROM keyvalue WHERE json_id=0") # json_id = 0 is internal keyvalues except sqlite3.OperationalError, err: # Table not exist self.log.debug("Query error: %s" % err) return False for row in res: self.db_keyvalues[row["key"]] = row["value"] return self.db_keyvalues.get("table.%s.version" % table_name, 0) # Check Db tables # Return: <list> Changed table names
def init_db(): try: # bangumi.db conn = sqlite3.connect(DB_PATH) conn.execute(CREATE_TABLE_BANGUMI) conn.execute(CREATE_TABLE_FOLLOWED) conn.execute(CREATE_TABLE_DOWNLOAD) conn.execute(CREATE_TABLE_FOLLOWED_FILTER) conn.execute(CREATE_TABLE_SUBTITLE) conn.commit() conn.close() # script.db conn = sqlite3.connect(SCRIPT_DB_PATH) conn.execute(CREATE_TABLE_SCRIPT) conn.commit() conn.close() except sqlite3.OperationalError: print_error('Open database file failed, path %s is not writable.' % BGMI_PATH)
def build_search_table(db_path: PathInfo, included_fieldnames: Sequence[Text]): """ Builds virtual table for full-text search in sqlite databases. Accepts path to the sqlite file and subset of its fieldnames to be included in the virtual table. """ table = 'search_table' with sqlite3.connect(db_path) as sink_conn: column_str = ', '.join(included_fieldnames) create_table_query = f'''CREATE VIRTUAL TABLE search_table USING fts5({column_str});''' try: sink_conn.execute(create_table_query) except sqlite3.OperationalError as excep: table_exists_text = f'table {table}already exists' if table_exists_text in str(excep): print(f'{table_exists_text}.') sql_placeholder = ('?, ' * len(included_fieldnames))[:-2] record_yielder = db_ops.yield_source_records(source_db_paths={'all_merged': db_path}, source_fieldnames=included_fieldnames, ) virtual_insert_query = f'''INSERT INTO search_table ({column_str}) VALUES ({sql_placeholder})''' sink_conn.executemany(virtual_insert_query, tuple(record_yielder))
def establish_benchmark(profile_dbs): incr = helpers.incrementer() profile_records_dict = odict() for profile_name, profile_path in profile_dbs.items(): conn = sqlite3.connect(profile_path) conn.row_factory = sqlite3.Row cur = conn.cursor() query = '''SELECT * FROM moz_places''' try: cur.execute(query) except sqlite3.OperationalError: pass else: profile_records_dict.update({profile_name: [dict(row) for row in cur]}) finally: conn.close() merged_as_dict = odict({ info['url_hash']: odict(info) for profile_info in profile_records_dict.values() for info in profile_info }) return merged_as_dict
def __init__(self): """ Creates the StorPerfConfig.db and configuration tables on demand """ self.logger = logging.getLogger(__name__) self.logger.debug("Connecting to " + ConfigurationDB.db_name) with db_mutex: db = sqlite3.connect(ConfigurationDB.db_name) cursor = db.cursor() try: cursor.execute('''CREATE TABLE configuration (configuration_name text, key text, value text)''') self.logger.debug("Created configuration table") except OperationalError: self.logger.debug("Configuration table exists") cursor.execute('SELECT * FROM configuration') db.commit() db.close()
def InsertRowsInTable(self, table_name, rows): """Insert a number of rows in table_name in GellishDB. """ # Insert a number of rows of data in table table_name command = "INSERT OR REPLACE INTO %s VALUES (?%s)" % (table_name,54*",?") try: self.db_cursor.executemany(command, rows) except (sqlite3.IntegrityError, sqlite3.OperationalError): for row in rows: try: self.db_cursor.execute(command, row) except sqlite3.IntegrityError: print('** Error: IdeaUID %i already exists. Insertion ignored.' % (row[15])) except sqlite3.OperationalError: print("** Error: Row could not be interpreted and is skipped: %s " % row) # Save (commit) the additions self.db_connect.commit() #------------------------------------------------ -------------
def __init__(self, path, threaded=True): LockBase.__init__(self, path, threaded) self.lock_file = self.lock_file self.unique_name = self.unique_name import sqlite3 self.connection = sqlite3.connect(SQLiteFileLock.testdb) cursor = self.connection.cursor() try: cursor.execute("create table locks" "(" " lock_file varchar(32)," " unique_name varchar(32)" ")") except sqlite3.OperationalError: pass else: self.connection.commit() import atexit atexit.register(os.unlink, SQLiteFileLock.testdb)
def do_query(self, params): '''Queries the database''' if not params: self.help_query() return with sqlite3.connect(os.path.join(self.workspace, 'data.db')) as conn: with closing(conn.cursor()) as cur: self.debug('QUERY => %s' % (params)) try: cur.execute(params) except sqlite3.OperationalError as e: self.error('Invalid query. %s %s' % (type(e).__name__, e.message)) return if cur.rowcount == -1 and cur.description: tdata = cur.fetchall() if not tdata: self.output('No data returned.') else: header = tuple([x[0] for x in cur.description]) self.table(tdata, header=header) self.output('%d rows returned' % (len(tdata))) else: conn.commit() self.output('%d rows affected.' % (cur.rowcount))
def execute(self, sql: str, params: typing.Union[typing.Mapping, typing.Iterable] = None): """ Executes SQL in the current transaction. """ # lock to ensure nothing else is using the connection at once logger.debug("Running SQL {} with params {}".format(sql, params)) async with self._lock: async with threadpool(): for stmt in separate_statements(sql): try: if params is None: res = self.connection.execute(stmt) else: res = self.connection.execute(stmt, params) except sqlite3.IntegrityError as e: raise IntegrityError(*e.args) except sqlite3.OperationalError as e: raise DatabaseException(*e.args) return res
def cursor(self, sql: str, params: typing.Union[typing.Mapping, typing.Iterable] = None) \ -> 'Sqlite3ResultSet': """ Gets a cursor for the specified SQL. """ logger.debug("Running SQL {} with params {}".format(sql, params)) async with self._lock: async with threadpool(): for stmt in separate_statements(sql): cur = self.connection.cursor() try: if params is None: cur.execute(stmt) else: cur.execute(stmt, params) except sqlite3.OperationalError as e: raise DatabaseException(*e.args) return Sqlite3ResultSet(cur)
def __init__(self, shell=None, config=None, **traits): """Create a new history manager associated with a shell instance. """ # We need a pointer back to the shell for various tasks. super(HistoryManager, self).__init__(shell=shell, config=config, **traits) self.save_flag = threading.Event() self.db_input_cache_lock = threading.Lock() self.db_output_cache_lock = threading.Lock() try: self.new_session() except OperationalError: self.log.error("Failed to create history session in %s. History will not be saved.", self.hist_file, exc_info=True) self.hist_file = ':memory:' if self.enabled and self.hist_file != ':memory:': self.save_thread = HistorySavingThread(self) self.save_thread.start()
def _sql(self): con = getattr(self._local, 'con', None) if con is None: con = self._local.con = sqlite3.connect( op.join(self._directory, DBNAME), timeout=self._timeout, isolation_level=None, ) # Some SQLite pragmas work on a per-connection basis so query the # Settings table and reset the pragmas. The Settings table may not # exist so catch and ignore the OperationalError that may occur. try: select = 'SELECT key, value FROM Settings' settings = con.execute(select).fetchall() except sqlite3.OperationalError: pass else: for key, value in settings: if key.startswith('sqlite_'): self.reset(key, value, update=False) return con.execute
def _transact(self, filename=None): sql = self._sql filenames = [] _disk_remove = self._disk.remove try: sql('BEGIN IMMEDIATE') except sqlite3.OperationalError: if filename is not None: _disk_remove(filename) raise Timeout try: yield sql, filenames.append except BaseException: sql('ROLLBACK') raise else: sql('COMMIT') for filename in filenames: if filename is not None: _disk_remove(filename)
def test_pragma(cache): local = mock.Mock() con = mock.Mock() execute = mock.Mock() cursor = mock.Mock() fetchall = mock.Mock() local.con = con con.execute = execute execute.return_value = cursor cursor.fetchall = fetchall fetchall.side_effect = [sqlite3.OperationalError, None] size = 2 ** 28 with mock.patch.object(cache, '_local', local): assert cache.reset('sqlite_mmap_size', size) == size
def test_pragma_error(cache): local = mock.Mock() con = mock.Mock() execute = mock.Mock() cursor = mock.Mock() fetchall = mock.Mock() local.con = con con.execute = execute execute.return_value = cursor cursor.fetchall = fetchall fetchall.side_effect = [sqlite3.OperationalError] * 60000 size = 2 ** 28 with mock.patch('time.sleep', lambda num: 0): with mock.patch.object(cache, '_local', local): cache.reset('sqlite_mmap_size', size)
def bond(self, id=None): """ Creates or uses a file to store data :param id: the unique identifier of the related space :type id: str """ if id: self.id = id handle = self.get_db() try: handle.execute("CREATE TABLE store \ (id INTEGER PRIMARY KEY, \ context TEXT, \ key TEXT UNIQUE, \ value TEXT)") except sqlite3.OperationalError as feedback: logging.debug(feedback)
def execute_file(curernt_version, data): if curernt_version >= data["version"]: cbpi.app.logger.info("SKIP DB FILE: %s" % data["file"]) return try: with sqlite3.connect("craftbeerpi.db") as conn: with open('./update/%s' % data["file"], 'r') as f: d = f.read() sqlCommands = d.split(";") cur = conn.cursor() for s in sqlCommands: cur.execute(s) cur.execute("INSERT INTO schema_info (version,filename) values (?,?)", (data["version"], data["file"])) conn.commit() except sqlite3.OperationalError as err: print "EXCEPT" print err
def _get_from_db(self, sql): if not self.conn: debug("Not connected yet.") self._connect_to_db() try: debug("Execute SQL: {}", sql) cur = self.conn.cursor() cur.execute(sql) return cur.fetchall() except sqlite3.OperationalError: critical("Getting data from db failed: {}", sql) except: tb = "" if traceback: tb = traceback.format_exc() critical("Getting data from db failed: {}, {}", sys.exc_info(), tb)
def sql_query(dbname, query): """ Execute an SQL query over a database. :param dbname: filename of persistent store :type schema: str :param query: SQL query :type rel_name: str """ import sqlite3 try: path = nltk.data.find(dbname) connection = sqlite3.connect(str(path)) cur = connection.cursor() return cur.execute(query) except (ValueError, sqlite3.OperationalError): import warnings warnings.warn("Make sure the database file %s is installed and uncompressed." % dbname) raise
def get_command(self, app, _install=True): """ >>> """ rows = [] table = 'packages' columns = 'repository, package, sequence' query = 'SELECT {0} from {1} WHERE name = \"{2}\" ORDER BY sequence' query_sql = query.format(columns, table, app) try: self.cursor.execute(query_sql) # fetch data data = self.cursor.fetchall() if data: for item in data: if item[0] == "pacman": arg = "-S " if _install else "-R " rows.append("sudo pacman " + arg + item[1]) elif item[0] == "yaourt": parm = self.get_config("noconfirm") noconfirm = " --noconfirm" if parm == "True" else "" arg = "-S " if _install else "-R " rows.append("yaourt " + arg + item[1] + noconfirm) else: table = 'alias' columns = 'command' query = 'SELECT {0} from {1} WHERE name = \"{2}\"' query_sql = query.format(columns, table, app) self.cursor.execute(query_sql) # fetch data data = self.cursor.fetchall() for item in data: rows.append(item[0]) except sqlite3.OperationalError: print("Error connecting to database!.") return rows
def search_packages(self): rows = [] query = 'SELECT name from packages' try: self.cursor.execute(query) # fetch data data = self.cursor.fetchall() for item in data: rows.append(item[0]) rows = list(set(rows)) except sqlite3.OperationalError: print("Error connecting to database!.") return rows
def set_settings(id, noti=None, lat=None, lng=None, rad=None, ign=None, nick=None, silence=None): if noti is None: noti = user_settings[id]["noti"] if lat is None or lng is None: lat = user_settings[id]["lat"] lng = user_settings[id]["lng"] if rad is None: rad = user_settings[id]["radius"] if ign is None: ign = user_settings[id]["ignored"] if nick is None: nick = user_settings[id]["nick"] if silence is None: if "silence" in user_settings[id]: silence = user_settings[id]["silence"] else: silence = "" user_settings[id] = {'id': id, "noti": noti, "lat": lat, "lng": lng, "radius": rad, "ignored": ign, "nick": nick, "silence": silence} cursor_telebot = db_telebot.cursor() while True: try: cursor_telebot.execute("INSERT OR REPLACE INTO users VALUES(?,?,?,?,?,?,?,?)", [id, noti, round(lat, 5), round(lng, 5), rad, ','.join(map(str, ign)), nick, silence]) db_telebot.commit() return user_settings[id] except sqlite3.OperationalError: pass
def load_all_settings(): cursor_telebot = db_telebot.cursor() while True: try: for row in cursor_telebot.execute('SELECT id, notify, latitude, longitude, radius, ignored, nick, silence FROM users'): user_settings[row[0]] = {'id': row[0], 'noti': row[1], 'lat': row[2], 'lng': row[3], 'radius': row[4], 'ignored': [] if row[5].encode("ascii", "ignore") == "" else map(int, row[5].encode("ascii", "ignore").split(",")), 'nick': row[6], 'silence': "" if row[7] is None else row[7]} return except sqlite3.OperationalError: pass
def get_active_pokemon(): timenow = int(round(time.time(), 0)) cursor_data = db_data.cursor() while True: try: return cursor_data.execute('SELECT spawnid, latitude, longitude, spawntype, pokeid, expiretime FROM spawns WHERE (expiretime > ?) AND (fromtime >= 0)', (timenow,)).fetchall() except sqlite3.OperationalError: pass
def do_login(account): lprint('[{}] Login for {} account: {}'.format(account['num'], account['type'], account['user'])) timenow = get_time() cursor_accs = db_accs.cursor() db_repeat = True while db_repeat: try: acc_saved = cursor_accs.execute("SELECT access_token,access_expire_timestamp,api_url,auth_ticket__expire_timestamp_ms,auth_ticket__start,auth_ticket__end from accounts WHERE user = ?",[account['user']]).fetchone() db_repeat = False except sqlite3.OperationalError as e: lprint('[-] Sqlite operational error: {}, account: {} Retrying...'.format(e, account['user'])) except sqlite3.InterfaceError as e: lprint('[-] Sqlite interface error: {}, account: {} Retrying...'.format(e, account['user'])) if acc_saved is not None and timenow < acc_saved[1]: new_session(account) account['access_expire_timestamp'] = acc_saved[1] account['access_token'] = acc_saved[0] lprint('[{}] Reused RPC Session Token: {}'.format(account['num'], account['access_token'])) else: do_full_login(account) lprint('[{}] New RPC Session Token: {}'.format(account['num'], account['access_token'])) acc_saved = None location = LAT_C, LNG_C if acc_saved is not None and timenow < acc_saved[3]: account['api_url'] = acc_saved[2] account['auth_ticket'] = {'expire_timestamp_ms': acc_saved[3], 'start': acc_saved[4], 'end': acc_saved[5]} lprint('[{}] Reused API endpoint: {}'.format(account['num'], account['api_url'])) else: set_api_endpoint(location, account) lprint('[{}] New API endpoint: {}'.format(account['num'], account['api_url'])) if acc_tos: accept_tos(location, account) account['captcha_needed'] = False
def cache_get(key): # type: (str, str) -> dict or None try: cursor = _get_connection_cursor() cursor.execute("SELECT * FROM %s WHERE key = ?" % cache_table, [key]) return cursor.fetchone() except OperationalError: return None
def _open_database(self): """Opens a connection to the databse.""" log.debug("Opening sqlite database {0}".format(self._db_file)) self._conn = sqlite3.connect(self._db_file) try: log.debug("Checking if database is populated.") self._conn.execute("select * from airing_anime_list limit 1"); self._conn.row_factory = sqlite3.Row except sqlite3.OperationalError: log.debug("Database needs populated.") self._conn.row_factory = sqlite3.Row self._populate_database() log.debug("database connection established.")
def getCursor(self): if (self.conn is None): #print self.sqlite_file try: self.conn = sqlite3.connect(self.sqlite_file) except sqlite3.OperationalError as e: print e except: print sys.exc_info()[0] return self.conn.cursor()
def createTable(self, table_name): try: self._c.execute('CREATE TABLE {tn} (id INTEGER PRIMARY KEY)' .format(tn=table_name)) except sqlite3.OperationalError: return False else: return True
def addColumn(self, table_name, column_name, column_type): try: self._c.execute('ALTER TABLE {tn} ADD COLUMN {cn} {ct}' .format(tn=table_name, cn=column_name, ct=column_type)) except sqlite3.OperationalError: return False else: return True
def CheckRaiseTimeout(self): if sqlite.sqlite_version_info < (3, 2, 2): # This will fail (hang) on earlier versions of sqlite. # Determine exact version it was fixed. 3.2.1 hangs. return self.cur1.execute("create table test(i)") self.cur1.execute("insert into test(i) values (5)") try: self.cur2.execute("insert into test(i) values (5)") self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass except: self.fail("should have raised an OperationalError")