當前位置: 首頁>>代碼示例>>Python>>正文


Python sqlite3.OperationalError方法代碼示例

本文整理匯總了Python中sqlite3.OperationalError方法的典型用法代碼示例。如果您正苦於以下問題:Python sqlite3.OperationalError方法的具體用法?Python sqlite3.OperationalError怎麽用?Python sqlite3.OperationalError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sqlite3的用法示例。


在下文中一共展示了sqlite3.OperationalError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _DetectApplicationUsageTable

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def _DetectApplicationUsageTable(self, conn):
    """Detect whether the application usage table exists.

    Args:
      conn: sqlite3.Connection object
    Returns:
      True if the table exists, False if not.
    Raises:
      sqlite3.Error: if error occurs
    """
    try:
      conn.execute(APPLICATION_USAGE_TABLE_DETECT)
      exists = True
    except sqlite3.OperationalError, e:
      if e.args[0].startswith('no such table'):
        exists = False
      else:
        raise 
開發者ID:google,項目名稱:macops,代碼行數:20,代碼來源:ApplicationUsage.py

示例2: LogApplicationUsage

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def LogApplicationUsage(self, event, bundle_id, app_version, app_path):
    """Log application usage.

    Args:
      event: str, like "launch" or "quit"
      bundle_id: str
      app_version: str
      app_path: str
    """
    if bundle_id is None and app_version is None and app_path is None:
      return

    try:
      now = int(time.time())
      conn = self._Connect()
      if not self._DetectApplicationUsageTable(conn):
        self._CreateApplicationUsageTable(conn)
      self._InsertApplicationUsage(
          conn,
          event, bundle_id, app_version, app_path, now)
      conn.commit()
    except sqlite3.OperationalError, e:
      logging.error('Error writing %s event to database: %s', event, e)
      self._Close(conn) 
開發者ID:google,項目名稱:macops,代碼行數:26,代碼來源:ApplicationUsage.py

示例3: create_webinfo_db

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def create_webinfo_db(self):
        try:
            cursor = self.conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS webinfo (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                time varchar(255),
                domain varchar(255),
                waf varchar(255) DEFAULT '',
                title varchar(255) DEFAULT '',
                apps varchar(255) DEFAULT '',
                server varchar(255) DEFAULT '',
                address varchar(255) DEFAULT '',
                ipaddr varchar(255) DEFAULT '',
                os varchar(255) DEFAULT '',
                md5 varchar(40) UNIQUE
                )
                """)
        except sqlite3.OperationalError as e:
            pass 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:22,代碼來源:sqldb.py

示例4: sql_query

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
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 
開發者ID:rafasashi,項目名稱:razzy-spinner,代碼行數:20,代碼來源:chat80.py

示例5: extract

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def extract(source, query):
    """Get records from source database.

    Args:
        source: File path to the source database where we want to extract the
        data from.
        query: The query string to be executed in order to retrieve relevant
        attributes as (datetime, url, time) from the source database according
        to the browser chosen.
    """
    try:
        conn = open_db(source)
        cursor = conn.cursor()
        cursor.execute(query)
        history = cursor.fetchall()
        conn.close()
        return history
    except sqlite3.OperationalError as op_e:
        raise Error('Could not perform queries on the source database: '
                    '{}'.format(op_e)) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:22,代碼來源:hist_importer.py

示例6: import_session

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def import_session(cookiefile, sessionfile):
    print("Using cookies from {}.".format(cookiefile))
    conn = connect(cookiefile)
    try:
        cookie_data = conn.execute(
            "SELECT name, value FROM moz_cookies WHERE baseDomain='instagram.com'"
        )
    except OperationalError:
        cookie_data = conn.execute(
            "SELECT name, value FROM moz_cookies WHERE host LIKE '%instagram.com'"
        )
    instaloader = Instaloader(max_connection_attempts=1)
    instaloader.context._session.cookies.update(cookie_data)
    username = instaloader.test_login()
    if not username:
        raise SystemExit("Not logged in. Are you logged in successfully in Firefox?")
    print("Imported session cookie for {}.".format(username))
    instaloader.context.username = username
    instaloader.save_session_to_file(sessionfile) 
開發者ID:instaloader,項目名稱:instaloader,代碼行數:21,代碼來源:615_import_firefox_session.py

示例7: _set_pragmas

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def _set_pragmas(self, conn):
        # `multiversion` is weird. It checks first whether another connection
        # from the BTree cache is available, and then switches to that, which
        # may have the handle of the DB_Env. If that happens, then we get
        # an error stating that you cannot set `multiversion` despite the
        # fact we have not done any operations and it's a brand new conn.
        if self._pragmas:
            cursor = conn.cursor()
            for pragma, value in self._pragmas:
                if pragma == 'multiversion':
                    try:
                        cursor.execute('PRAGMA %s = %s;' % (pragma, value))
                    except berkeleydb.OperationalError:
                        pass
                else:
                    cursor.execute('PRAGMA %s = %s;' % (pragma, value))
            cursor.close() 
開發者ID:danielecook,項目名稱:Quiver-alfred,代碼行數:19,代碼來源:berkeleydb.py

示例8: create_if_required

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def create_if_required(self):
    # called once to create db
      c = self.conn.cursor()
      try:
        c.execute('''create table imgs (
                          id integer primary key autoincrement,
                          filename text
                     )''')
        c.execute('''create table labels (
                          img_id integer,
                          x integer,
                          y integer
                     )''')
      except sqlite3.OperationalError:
        # assume table already exists? clumsy...
        pass 
開發者ID:matpalm,項目名稱:bnn,代碼行數:18,代碼來源:label_db.py

示例9: __init__

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def __init__(self, dbfile):
        if dbfile == ":memory:":
            raise ValueError("We don't support the sqlite :memory: database type. Just use the default volatile in-memory store.")
        self.dbfile = dbfile
        with sqlite3.connect(dbfile) as db:
            db.execute("PRAGMA foreign_keys=ON")
            try:
                db.execute("SELECT COUNT(*) FROM pyro_names").fetchone()
            except sqlite3.OperationalError:
                # the table does not yet exist
                self._create_schema(db)
            else:
                # check if we need to update the existing schema
                try:
                    db.execute("SELECT COUNT(*) FROM pyro_metadata").fetchone()
                except sqlite3.OperationalError:
                    # metadata schema needs to be created and existing data migrated
                    db.execute("ALTER TABLE pyro_names RENAME TO pyro_names_old")
                    self._create_schema(db)
                    db.execute("INSERT INTO pyro_names(name, uri) SELECT name, uri FROM pyro_names_old")
                    db.execute("DROP TABLE pyro_names_old")
            db.commit() 
開發者ID:irmen,項目名稱:Pyro5,代碼行數:24,代碼來源:nameserver.py

示例10: __load_affix

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def __load_affix(self,):
        """
        load affix form data base into self.affixdict, to speed up search
        """
        sql  =  u"select * FROM affix"
        try:
            self.cursor.execute(sql)
        except sqlite.OperationalError:
            print("Fatal Error can't execute query: file: %s"%self.file_path)
            return []
        if self.cursor:
            # get one row 
            for row in   self.cursor:
                   self.affixdict[row["affix"]] = row["flag"]  

            #print "affix", self.affixdict 
開發者ID:linuxscout,項目名稱:mishkal,代碼行數:18,代碼來源:spelldb.py

示例11: get_entry_by_id

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def get_entry_by_id(self, idf):
        """ Get dictionary entry by id from the dictionary
        @param id :word identifier
        @type id: integer
        @return: all attributes
        @rtype: dict
        """
        # lookup for a word
        sql = u"select * FROM %s WHERE id='%s'" % (self.table_name, idf)
        try:
            self.cursor.execute(sql)
            if self.cursor:
                return self.cursor.fetchall()            
        except  sqlite.OperationalError:
            return False
        return False 
開發者ID:linuxscout,項目名稱:mishkal,代碼行數:18,代碼來源:semdictionary.py

示例12: get_attrib_by_id

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def get_attrib_by_id(self, idf, attribute):
        """ Get attribute value by id from the dictionary
        @param id :word identifier
        @type id: integer
        @param attribute :the attribute name
        @type attribute: unicode
        @return: The attribute
        value
        @rtype: mix.
        """
        # if the id exists and the attribute existe return the value, 
        sql = u"select * FROM %s WHERE id='%s'" % (self.table_name, idf)
        try:
            self.cursor.execute(sql)
            if self.cursor:
                for row in self.cursor:
                    return  row[attribute]                        
        except  sqlite.OperationalError:
            return False
        return False 
開發者ID:linuxscout,項目名稱:mishkal,代碼行數:22,代碼來源:semdictionary.py

示例13: get_original

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def get_original(self, primate_word):
        """
        look up for the original verb fo the given word
        @param primate_word: the derived word.
        @type primate_word: unicode.
        @return:  (verb, derivation type) .
        @rtype: tuple of unicode.
        """
        idlist = []
        sql = u"select verb, type FROM derivations WHERE derived = '%s'" % (primate_word)
        try:
            self.cursor.execute(sql)
            if self.cursor:
                for row in self.cursor:
                    idlist.append((row[0],row[1]))
                if idlist:
                    return idlist[0]
            
        except  sqlite.OperationalError:
            print("degat",  primate_word.encode('utf8'))
            return ('','') 
        return ('','') 
開發者ID:linuxscout,項目名稱:mishkal,代碼行數:24,代碼來源:semdictionary.py

示例14: CheckLocking

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
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() 
開發者ID:vmware-archive,項目名稱:vsphere-storage-for-docker,代碼行數:22,代碼來源:transactions.py

示例15: _do_db_query

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import OperationalError [as 別名]
def _do_db_query(self, params):
        '''Queries the database with custom SQL'''
        if not params:
            self._help_db_query()
            return
        try:
            results = self.query(params, include_header=True)
        except sqlite3.OperationalError as e:
            self.error(f"Invalid query. {type(e).__name__} {e}")
            return
        if type(results) == list:
            header = results.pop(0)
            if not results:
                self.output('No data returned.')
            else:
                self.table(results, header=header)
                self.output(f"{len(results)} rows returned")
        else:
            self.output(f"{results} rows affected.") 
開發者ID:lanmaster53,項目名稱:recon-ng,代碼行數:21,代碼來源:framework.py


注:本文中的sqlite3.OperationalError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。