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


Python sqlite3.IntegrityError方法代碼示例

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


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

示例1: set

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def set(self, key, value, replace=False):
        self.logger.debug("Setting key %s to value %s (replace=%s)",
                          key, value, replace)
        if key.endswith('/'):
            raise ValueError('Invalid Key name, cannot end in "/"')
        if replace:
            query = "INSERT OR REPLACE into %s VALUES (?, ?)"
        else:
            query = "INSERT into %s VALUES (?, ?)"
        setdata = query % (self.table,)
        try:
            conn = sqlite3.connect(self.dburi)
            with conn:
                c = conn.cursor()
                self._create(c)
                c.execute(setdata, (key, value))
        except sqlite3.IntegrityError as err:
            raise CSStoreExists(str(err))
        except sqlite3.Error:
            self.logger.exception("Error storing key %s", key)
            raise CSStoreError('Error occurred while trying to store key') 
開發者ID:latchset,項目名稱:custodia,代碼行數:23,代碼來源:sqlite.py

示例2: span

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def span(self, key):
        name = key.rstrip('/')
        self.logger.debug("Creating container %s", name)
        query = "INSERT into %s VALUES (?, '')"
        setdata = query % (self.table,)
        try:
            conn = sqlite3.connect(self.dburi)
            with conn:
                c = conn.cursor()
                self._create(c)
                c.execute(setdata, (name,))
        except sqlite3.IntegrityError as err:
            raise CSStoreExists(str(err))
        except sqlite3.Error:
            self.logger.exception("Error creating key %s", name)
            raise CSStoreError('Error occurred while trying to span container') 
開發者ID:latchset,項目名稱:custodia,代碼行數:18,代碼來源:sqlite.py

示例3: sql_add

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def sql_add(elem, name, columns, db_name):
    conn = sqlite3.connect(db_name)
    c = conn.cursor()
    if isinstance(elem, list):
        # It is assumed that the length of list and of columns will
        # always match
        q = ("INSERT INTO " + str(name) + " (" + ",".join(columns)
             + ") VALUES ('" + "','".join(elem) + "')")
    else:
        q = "INSERT INTO " + str(name) + columns + " VALUES " + elem
    # print q
    try:
        c.execute(q)
        conn.commit()
    except sqlite3.IntegrityError:
        print("Already In Database", elem)
    c.close()
    conn.close() 
開發者ID:phageParser,項目名稱:phageParser,代碼行數:20,代碼來源:jointable.py

示例4: insert_table

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def insert_table(self, table_name, column_name_value_dict, max_retries=5):
        sqlstr, value_tuple = generate_insert_sqlstr_value_tuple(table_name=table_name, item=column_name_value_dict)
        cursor = self.conn.cursor()
        try:
            cursor.execute(sqlstr, value_tuple)
            self.conn.commit()
        except sqlite3.IntegrityError:
            logging.error("Duplicated")
            print ("Duplicated")
        except sqlite3.OperationalError:
            remaining_retries = max_retries - 1
            if remaining_retries > 0:
                sleep(randint(self.MIN_SLEEP, self.MAX_SLEEP))
                logging.error("database is locked, retrying...")
                print ("Retrying: %s, %s" % (sqlstr, value_tuple))
                self.insert_table(table_name=table_name, column_name_value_dict=column_name_value_dict,
                                  max_retries=remaining_retries)
            else:
                logging.error("database is locked, max-retry reached")
                raise 
開發者ID:osssanitizer,項目名稱:osspolice,代碼行數:22,代碼來源:sqlite_util.py

示例5: update_table

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def update_table(self, table_name, set_name_value_dict, where_name_value_dict, max_retries=5):
        # This is not single process and multi-thread program, so we are not using threading locks.
        sqlstr, value_tuple = generate_update_sqlstr_value_tuple(
            table_name=table_name, set_name_value_dict=set_name_value_dict,
            where_name_value_dict=where_name_value_dict)
        cursor = self.conn.cursor()
        try:
            cursor.execute(sqlstr, value_tuple)
            self.conn.commit()
        except sqlite3.IntegrityError:
            logging.error("Update Error")
            print ("Update Error")
        except sqlite3.OperationalError:
            remaining_retries = max_retries - 1
            if remaining_retries > 0:
                sleep(randint(self.MIN_SLEEP, self.MAX_SLEEP))
                logging.error("database is locked, retrying...")
                print ("Retrying: %s, %s" % (sqlstr, value_tuple))
                self.update_table(table_name=table_name, set_name_value_dict=set_name_value_dict,
                                  where_name_value_dict=where_name_value_dict, max_retries=remaining_retries)
            else:
                logging.error("database is locked, max-retry reached")
                raise 
開發者ID:osssanitizer,項目名稱:osspolice,代碼行數:25,代碼來源:sqlite_util.py

示例6: addData

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def addData(self,data,table):
    try:
      #None is for the primary key which auto increments
      if type(data) is list or type(data) is tuple:
        self.c.execute('INSERT INTO %s VALUES (%s)'%(table,('?,'*len(data))[:-1]),data)
      elif type(data) is dict:
        keys = list(data.keys())
        #keys = data.keys()
        try:
          values = [data[k] for k in keys]
          #values = list(data.values())
          #values = data.values()
        except KeyError:
          raise DataBaseInvalidInput('sanitized column names don\'t match given column names')
        self.c.execute('INSERT INTO %s (%s) VALUES (%s)'%(table , ','.join(keys) , ','.join(['?']*len(data))) , values)
      else:
        raise Exception('invalid input type: %s'%type(data))
      id = self.c.lastrowid
      #remember to commit changes so we don't lock the db!
      self.conn.commit()
      return id
    except sqlite3.IntegrityError as e:
      raise DataBaseIntegrityError('%s' %e) 
開發者ID:schollz,項目名稱:extract_recipe,代碼行數:25,代碼來源:dbcommands.py

示例7: user

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def user(conn, config, User):
    try:
        time_ms = round(time.time()*1000)
        cursor = conn.cursor()
        user = [int(User.id), User.id, User.name, User.username, User.bio, User.location, User.url,User.join_date, User.join_time, User.tweets, User.following, User.followers, User.likes, User.media_count, User.is_private, User.is_verified, User.avatar, User.background_image]

        hex_dig = hashlib.sha256(','.join(str(v) for v in user).encode()).hexdigest()
        entry = tuple(user) + (hex_dig,time_ms,)
        old_hash = get_hash_id(conn, User.id)

        if old_hash == -1 or old_hash != hex_dig:
            query = f"INSERT INTO users VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
            cursor.execute(query, entry)
        else:
            pass

        if config.Followers or config.Following:
            table = uTable(config.Followers)
            query = f"INSERT INTO {table} VALUES(?,?)"
            cursor.execute(query, (config.User_id, int(User.id)))

        conn.commit()
    except sqlite3.IntegrityError:
        pass 
開發者ID:twintproject,項目名稱:twint,代碼行數:26,代碼來源:db.py

示例8: insert

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def insert(self, ip_address, log_msg, country=""):
        """
        Inserts a row into sqlite

        Args:
            ip_address: IP address to be inserted into sqlite
            log_msg: Reason as to why the IP is banned
            country: Country of where the IP is from
        """
        cursor = None

        try:
            cursor = self.sqlite_connection.cursor()
            cursor.execute(
                "INSERT INTO banned_ip(ip, time_banned, server_name, log_msg, country) VALUES (?, ?, ?, ?, ?)",
                (ip_address, time.time(), "Server-1", log_msg, country)
            )

            self.sqlite_connection.commit()
        except sqlite3.IntegrityError:
            print("IP already in the database")
        finally:
            if cursor is not None:
                cursor.close() 
開發者ID:Jason2605,項目名稱:PyFilter,代碼行數:26,代碼來源:database.py

示例9: insert_many

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def insert_many(conn, items, table_name):
    table_name = scrub(table_name)
    sql = "INSERT INTO {} ('name', 'price', 'quantity') VALUES (?, ?, ?)".format(
        table_name
    )
    entries = list()
    for x in items:
        entries.append((x["name"], x["price"], x["quantity"]))
    try:
        conn.executemany(sql, entries)
        conn.commit()
    except IntegrityError as e:
        print(
            '{}: at least one in {} was already stored in table "{}"'.format(
                e, [x["name"] for x in items], table_name
            )
        ) 
開發者ID:jackdbd,項目名稱:design-patterns,代碼行數:19,代碼來源:sqlite_backend.py

示例10: insertHaveMask

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def insertHaveMask(self, channel, infohash, peer_id, havemask, timestamp = None):
        query = QUERIES['SELECT METADATA']
        if timestamp is None:
            timestamp = int(time.time())
        channel = bin2str(channel)
        infohash = bin2str(infohash)
        peer_id = bin2str(peer_id)
        res = self._db.fetchall(query, (infohash, channel))
        if len(res) != 1:
            raise MetadataDBException('No entry in the MetadataDB for %s, %s' % (channel[-10:], infohash))
        metadata_fk = res[0][0]
        insertQuery = QUERIES['INSERT HAVE MASK']
        try:
            self._db.execute_write(insertQuery, (metadata_fk,
             peer_id,
             havemask,
             timestamp))
        except sqlite3.IntegrityError as e:
            raise MetadataDBException(str(e)) 
開發者ID:alesnav,項目名稱:p2ptv-pi,代碼行數:21,代碼來源:MetadataDBHandler.py

示例11: CheckLastRowIDInsertOR

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def CheckLastRowIDInsertOR(self):
        results = []
        for statement in ('FAIL', 'ABORT', 'ROLLBACK'):
            sql = 'INSERT OR {} INTO test(unique_test) VALUES (?)'
            with self.subTest(statement='INSERT OR {}'.format(statement)):
                self.cu.execute(sql.format(statement), (statement,))
                results.append((statement, self.cu.lastrowid))
                with self.assertRaises(sqlite.IntegrityError):
                    self.cu.execute(sql.format(statement), (statement,))
                results.append((statement, self.cu.lastrowid))
        expected = [
            ('FAIL', 2), ('FAIL', 2),
            ('ABORT', 3), ('ABORT', 3),
            ('ROLLBACK', 4), ('ROLLBACK', 4),
        ]
        self.assertEqual(results, expected) 
開發者ID:CedricGuillemet,項目名稱:Imogen,代碼行數:18,代碼來源:dbapi.py

示例12: insert_or_update

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def insert_or_update(self, table_name: str, data: Dict[str, Any]):
        try:
            await self.insert(table_name, data)
        except sqlite3.IntegrityError as e:
            # Hack to get primary key out of error message
            # Error : ` UNIQUE constraint failed: myTable.id `
            e = repr(e)
            replaces = "'`()"
            for s in replaces:
                e = e.replace(s, "")
            _key = e.split("UNIQUE constraint failed:")[-1]
            _key = _key.split(table_name + ".")[-1]

            _keyval = data.pop(_key)
            conditions = [[[_key, "=", _keyval]]]
            await self.update(table_name, data, conditions) 
開發者ID:intel,項目名稱:dffml,代碼行數:18,代碼來源:sqlite.py

示例13: add_user

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def add_user(user, password, ut):
    hashed_pass = hash_pass(password)

    # Here we set the db file path.
    db = Path(os.path.join(gazee.DATA_DIR, gazee.DB_NAME))

    # Here we make the inital DB connection that we will be using throughout this function.
    connection = sqlite3.connect(str(db))
    c = connection.cursor()
    try:
        c.execute('INSERT INTO {tn} ({un}, {pw}, {ut}) VALUES (?,?,?)'.format(tn=gazee.USERS, un=gazee.USERNAME, pw=gazee.PASSWORD, ut=gazee.TYPE), (user, hashed_pass, ut,))
    except sqlite3.IntegrityError:
        logging.info("User %s Already Exists" % user)
        return False
    finally:
        connection.commit()
        connection.close()

    logging.info("User %s Added" % (user))
    return True 
開發者ID:hubbcaps,項目名稱:gazee,代碼行數:22,代碼來源:authmech.py

示例14: _save_to_db

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def _save_to_db(self,clean_article):
        
        conn = sqlite3.connect(self.db)
        with conn:
            cur = conn.cursor()   
            try:
                cur.execute("INSERT INTO articles (Id,category,title,body)\
                    VALUES(?, ?, ?,?)",(None,clean_article['category'],clean_article['title'],clean_article['body']))
            except sqlite3.IntegrityError:
                self.stats['not_insert_db'] += 1
                print 'Record already inserted with title %s ' %(clean_article['title'].encode("utf-8")) 
開發者ID:skillachie,項目名稱:news-corpus-builder,代碼行數:13,代碼來源:news_corpus_generator.py

示例15: put_row

# 需要導入模塊: import sqlite3 [as 別名]
# 或者: from sqlite3 import IntegrityError [as 別名]
def put_row(self, row: DbRow, update=False, album=False):
        try:
            if update:
                if album:
                    # noinspection PyUnresolvedReferences
                    query = "UPDATE {0} Set {1} WHERE RemoteId = '{2}'".format(
                        row.table, row.update, row.RemoteId
                    )
                else:
                    # noinspection PyUnresolvedReferences
                    query = "UPDATE {0} Set {1} WHERE RemoteId = '{2}'".format(
                        row.table, row.update, row.RemoteId
                    )
            else:
                # EXISTS - allows for no action when trying to re-insert
                # noinspection PyUnresolvedReferences
                query = (
                    "INSERT INTO {0} ({1}) SELECT {2} "
                    "WHERE NOT EXISTS (SELECT * FROM SyncFiles "
                    "WHERE RemoteId = '{3}')".format(
                        row.table, row.columns, row.params, row.RemoteId
                    )
                )
            self.cur.execute(query, row.dict)
            row_id = self.cur.lastrowid
        except lite.IntegrityError:
            log.error("SQL constraint issue with {}".format(row.dict))
            raise
        return row_id

    # noinspection SqlResolve 
開發者ID:gilesknap,項目名稱:gphotos-sync,代碼行數:33,代碼來源:LocalData.py


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