Python sqlite3 模块,IntegrityError() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sqlite3.IntegrityError()

项目:spider-proxy-pool    作者:SymeonChen    | 项目源码 | 文件源码
def insert(address, port, location='default', protocol='default'):
    uid = str(uuid.uuid5(uuid.NAMESPACE_DNS,address))

    conn = sqlite3.connect(db)
    try:
        conn.execute("INSERT INTO PROXY VALUES (?, ?, ?, ?, ?)",[uid,address,port,location,protocol])
        print('insert: '+str(address))
        pass
    except sqlite3.IntegrityError as e:
        conn.execute("UPDATE PROXY SET ADDRESS = ?, PORT = ?, LOCATION = ?, PROTOCOL = ? WHERE UID=?",[address,port,location,protocol,uid])
        print('update: '+str(address))
        pass    

    except sqlite3.ProgrammingError as e:
        #TODO
        pass
    finally:
        conn.commit()
        conn.close()
项目:whatsapp-rest-webservice    作者:svub    | 项目源码 | 文件源码
def storeSenderKey(self, senderKeyName, senderKeyRecord):
        """
        :type senderKeyName: SenderKeName
        :type senderKeyRecord: SenderKeyRecord
        """
        q = "INSERT INTO sender_keys (group_id, sender_id, record) VALUES(?,?, ?)"
        cursor = self.dbConn.cursor()
        serialized = senderKeyRecord.serialize()
        if sys.version_info < (2,7):
            serialized = buffer(serialized)
        try:
            cursor.execute(q, (senderKeyName.getGroupId(), senderKeyName.getSender().getName(), serialized))
            self.dbConn.commit()
        except sqlite3.IntegrityError as e:
            q = "UPDATE sender_keys set record = ? WHERE group_id = ? and sender_id = ?"
            cursor = self.dbConn.cursor()
            cursor.execute(q, (serialized, senderKeyName.getGroupId(), senderKeyName.getSender().getName()))
            self.dbConn.commit()
项目:Gellish    作者:AndriesSHP    | 项目源码 | 文件源码
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()
#------------------------------------------------ -------------
项目:MensaUniurbBot    作者:Radeox    | 项目源码 | 文件源码
def register_user(chat_id, username, name):
    """
    Register given user to receive news and statistics
    """
    # Open connection to DB
    conn = sqlite3.connect(DB_NAME)
    cursor = conn.cursor()

    try:
        query = ('INSERT INTO user(chat_id, name, username, notification, language) '
                 'VALUES("{0}", "{1}", "{2}", "on", "it_IT.UTF-8")'.format(chat_id, name, username))
        cursor.execute(query)
        conn.commit()
    except sqlite3.IntegrityError:
        return 0
    finally:
        # Close connection to DB
        conn.close()
    return 1
项目:MensaUniurbBot    作者:Radeox    | 项目源码 | 文件源码
def update_user(chat_id, username, full_name):
    """
    Update name and username of missing users
    """
    # Open connection to DB
    conn = sqlite3.connect(DB_NAME)
    cursor = conn.cursor()

    try:
        query = ('UPDATE user '
                 'SET username = "{0}", name = "{1}" '
                 'WHERE chat_id = "{2}"'.format(username, full_name, chat_id))
        cursor.execute(query)
        conn.commit()
    except sqlite3.IntegrityError:
        return 0
    finally:
        # Close connection to DB
        conn.close()
    return 1
项目:asyncqlio    作者:SunDwarf    | 项目源码 | 文件源码
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
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def _getValueHist(self, version, pkgarch, checksum):
        data=self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
                           (version, pkgarch, checksum))
        row=data.fetchone()
        if row != None:
            return row[0]
        else:
            #no value found, try to insert
            try:
                self._execute("INSERT INTO %s VALUES (?, ?, ?, (select ifnull(max(value)+1,0) from %s where version=? AND pkgarch=?));"
                           % (self.table,self.table),
                           (version,pkgarch, checksum,version, pkgarch))
            except sqlite3.IntegrityError as exc:
                logger.error(str(exc))

            self.dirty = True

            data=self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
                               (version, pkgarch, checksum))
            row=data.fetchone()
            if row != None:
                return row[0]
            else:
                raise prserv.NotFoundError
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def _importHist(self, version, pkgarch, checksum, value):
        val = None 
        data = self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
                           (version, pkgarch, checksum))
        row = data.fetchone()
        if row != None:
            val=row[0]
        else:
            #no value found, try to insert
            try:
                self._execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
                           (version, pkgarch, checksum, value))
            except sqlite3.IntegrityError as exc:
                logger.error(str(exc))

            self.dirty = True

            data = self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=?;" % self.table,
                           (version, pkgarch, checksum))
            row = data.fetchone()
            if row != None:
                val = row[0]
        return val
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def _importNohist(self, version, pkgarch, checksum, value):
        try:
            #try to insert
            self._execute("INSERT INTO %s VALUES (?, ?, ?, ?);"  % (self.table),
                           (version, pkgarch, checksum,value))
        except sqlite3.IntegrityError as exc:
            #already have the record, try to update
            try:
                self._execute("UPDATE %s SET value=? WHERE version=? AND pkgarch=? AND checksum=? AND value<?"  
                              % (self.table),
                               (value,version,pkgarch,checksum,value))
            except sqlite3.IntegrityError as exc:
                logger.error(str(exc))

        self.dirty = True

        data = self._execute("SELECT value FROM %s WHERE version=? AND pkgarch=? AND checksum=? AND value>=?;" % self.table,
                            (version,pkgarch,checksum,value))
        row=data.fetchone()
        if row != None:
            return row[0]
        else:
            return None
项目:CTFNoteTaker    作者:Pyhscript    | 项目源码 | 文件源码
def deleteNoteADMIN(noteID,user):
    try:
        c = getC()
        conn = getConn()
        if(noteExists(noteID)):
            c.execute("SELECT contributor,note FROM note where noteID = (?)",(noteID,))
            printUser("Deleting Note:",user)
            format_output_multirow(c.fetchall(),user)
            c.execute("DELETE FROM note WHERE noteID = (?);",(noteID,))

            conn.commit()
            printUser("deleted note",user)
        else:
            printUser("No note exists with noteID " + str(noteID))
    except sqlite3.IntegrityError:
        printUser("Strange error in deleting note", user)
        printMaster("Error " + str(traceback.format_exc()))
项目:CTFNoteTaker    作者:Pyhscript    | 项目源码 | 文件源码
def deleteChal(CTF,challenge,user,verbose=False):
    try:
        c = getC()
        conn = getConn()
        chalID = getChalID(CTF,challenge)
        if(verbose):
            #We need a better format method for c.fetchone() for multiple columns 1 row.
            printUser("Deleting the following notes: ")
            c.execute("SELECT contributor,note FROM note WHERE challengeID = (?);",(chalID,))
            format_output_multirow(c.fetchall(),user)

        c.execute("DELETE FROM note WHERE challengeID = (?);",(chalID,))
        c.execute("DELETE FROM challenges WHERE challengeID = (?);",(chalID,))

        conn.commit()
        printUser("deleted challenge: " + challenge + " from CTF " + CTF + ", along with all of its notes.",user)
    except sqlite3.IntegrityError:
        printUser("Strange error in deleting challenge", user)
        printMaster("Error " + str(traceback.format_exc()))
项目:CTFNoteTaker    作者:Pyhscript    | 项目源码 | 文件源码
def deleteNoteREG(noteID,realuser,printuser):
    try:
        c = getC()
        conn = getConn()
        if(noteExists(noteID)):
            c.execute("SELECT contributor,note FROM note where noteID = (?)",(noteID,))
            row = c.fetchone()
            print(str(row))
            contributor = row[0]
            if(realuser.strip()==contributor.strip()):
                printUser("Deleting Note:",printuser)
                c.execute("SELECT contributor,note FROM note where noteID = (?)",(noteID,))
                format_output_multirow(c.fetchall())
                c.execute("DELETE FROM note WHERE noteID = (?)",(noteID,))
                conn.commit()
                printUser("deleted note",printuser)
            else:
                printUser("You did not create this note.",printuser)
        else:
            printUser("No note exists with noteID " + str(noteID),printuser)
    except sqlite3.IntegrityError:
        printUser("Strange error in deleting note",printuser)
        printMaster("Error " + str(traceback.format_exc()))
项目:Weather-App    作者:Tomasz-Kluczkowski    | 项目源码 | 文件源码
def insert(self, location):
        """Insert a row into locations.db.

        Args:
            location (str): 

        Returns:
            None
        """
        local_conn = sqlite3.connect(os.path.join(self.data_dirs["Database"],
                                                  "locations.db"))
        local_cur = local_conn.cursor()

        try:
            local_cur.execute("INSERT INTO locations (Location) VALUES (?)",
                              (location, ))
        except sqlite3.IntegrityError:
            pass
        local_cur.execute("UPDATE locations SET Num_of_calls"
                          " = Num_of_calls + 1 WHERE Location=?",
                          (location, ))
        local_conn.commit()
        local_conn.close()
项目:gazee    作者:hubbcaps    | 项目源码 | 文件源码
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
项目:RelayBot2.0    作者:nukeop    | 项目源码 | 文件源码
def add_note(self, steamid, message):
        tokens = message.split()
        if len(tokens)<3:
            return "No content. Note not added."
        else:
            try:
                self.bot.database.insert("notes", "key, content, author", "?, ?, ?",
                                (
                                    tokens[1],
                                    ' '.join(tokens[2:]),
                                    steamid
                                )
                )
                return "Note added."
            except sqlite3.IntegrityError:
                return ("You already made a note with key"
                        " '{}'.".format(tokens[1]))
项目:taktyk    作者:kosior    | 项目源码 | 文件源码
def insert_one(cursor, obj):
        """Insert entry or comment into database"""
        if not obj:
            logging.debug('Entry is empty.')
            return False

        statement = 'INSERT INTO {} VALUES (?,?,?,?,?,?,?,?,?,?,?)'.format(obj.type_)
        params = tuple(obj.__iter__())

        try:
            cursor.execute(statement, params)
        except sqlite3.IntegrityError:
            logging.debug(traceback.format_exc())
            return False
        else:
            set_added_info(obj.type_)
            return True
项目:taktyk    作者:kosior    | 项目源码 | 文件源码
def count_tags(cls, cursor, arg_tag=None):
        tags_dict = {}
        condition, params = cls.get_condition_and_params(arg_tag)
        statement = 'SELECT tags FROM entry {}'.format(condition)
        try:
            tags = cursor.execute(statement, params).fetchall()
        except sqlite3.IntegrityError:
            logging.debug('Fetching tags failed')
            return

        for tags_row in tags:
            tags = set(tags_row[0].strip().split(' '))
            for tag in tags:
                if tag in tags_dict.keys():
                    tags_dict[tag] += 1
                else:
                    tags_dict[tag] = 1

        return sorted(tags_dict.items(), key=lambda x: x[1], reverse=True)
项目:aadbot    作者:a3dev    | 项目源码 | 文件源码
def setSubmission(data, processed = False, failed = True):
    id_value = data['id']
    url = data['url']
    title = data['title']
    created_utc = data['created_utc']
    author = data['author']

    if db_path is None:
        print("ERROR : DB : setSubmission: ", 'db_path is None')
        exit()

    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()

        try:
            #insert into submissions_table
            query = "INSERT INTO " + sub_table + " (id, url, title, created_utc, author) VALUES (?, ?, ?, ?, ?)"
            cursor.execute(query, (id_value, url, title, created_utc, author))

            #insert into submissions_log
            query = "INSERT INTO " + sub_log + " (id, processed, failed) VALUES (?, ?, ?)"
            cursor.execute(query, (id_value, processed, failed))

        except sqlite3.IntegrityError:
            print('ERROR: ID already exists in PRIMARY KEY column : ', id_value)
项目:aadbot    作者:a3dev    | 项目源码 | 文件源码
def setDomains(domainList):
    if db_path is None:
        print("ERROR : DB : setDomains: ", 'db_path is None')
        exit()
    blacklisted = 0

    for domain in domainList:

        try:
            with sqlite3.connect(db_path) as conn:
                cursor = conn.cursor()

                query = "INSERT INTO " + domains_table + " (domain, blacklisted) VALUES (?, ?)"
                cursor.execute(query, (domain, blacklisted,))

        except sqlite3.IntegrityError:
            print('ERROR: Cannot INSERT domain, already exists: ', domain)
项目:CSC376KnowledgeManagement    作者:WCotterman    | 项目源码 | 文件源码
def register(self, username, pword):
                '''
        Attempts to enter a new username and pword into the USERS table

        :param username: new username, MUST BE UNIQUE
        :param pword: new password

        :return: 0 if username is not unique (can't have duplicate usernames)
                 1 if username is unique and user is put in db
        '''

                try:
                        self.conn.execute("INSERT INTO USERS(username, pword) VALUES(?,?)", (username, pword))
                        self.conn.commit()
                        return 1
                # username is not unique
                except sqlite3.IntegrityError:
                        return 0
项目:CSC376KnowledgeManagement    作者:WCotterman    | 项目源码 | 文件源码
def upload(self, id, fileName, category, keywords):
                '''
        Inserts new file into the FILES table

        :param id: username of user who's uploading file
        :param fileName: name of file
        :param category: category of file
        :param keywords: keywords

        :return: 0 if upload is not successful (can't have duplicate fileNames)
                 1 if upload is successful
        '''

                timestamp = datetime.datetime.now()

                try:
                        self.conn.execute("INSERT INTO FILES VALUES(?,?,?,?,?)", (id, fileName, category, keywords, timestamp))
                        self.conn.commit()
                        return 1

    # fileName not unique
                except sqlite3.IntegrityError:
                        return 0
项目:yowsup    作者:colonyhq    | 项目源码 | 文件源码
def storeSenderKey(self, senderKeyName, senderKeyRecord):
        """
        :type senderKeyName: SenderKeName
        :type senderKeyRecord: SenderKeyRecord
        """
        q = "INSERT INTO sender_keys (group_id, sender_id, record) VALUES(?,?, ?)"
        cursor = self.dbConn.cursor()
        serialized = senderKeyRecord.serialize()
        if sys.version_info < (2,7):
            serialized = buffer(serialized)
        try:
            cursor.execute(q, (senderKeyName.getGroupId(), senderKeyName.getSender().getName(), serialized))
            self.dbConn.commit()
        except sqlite3.IntegrityError as e:
            q = "UPDATE sender_keys set record = ? WHERE group_id = ? and sender_id = ?"
            cursor = self.dbConn.cursor()
            cursor.execute(q, (serialized, senderKeyName.getGroupId(), senderKeyName.getSender().getName()))
            self.dbConn.commit()
项目:monique    作者:monique-dashboards    | 项目源码 | 文件源码
def set(self, owner_id, dashboard_id, old_layout_id, new_layout_id,
            new_layout_def, new_layout_props):
        with cursor() as cur:
            if old_layout_id is None:
                try:
                    cur.execute(*insert('dashboard_layout', dict(
                        owner_id=owner_id,
                        dashboard_id=dashboard_id,
                        layout_def=new_layout_def,
                        layout_props=new_layout_props,
                        layout_id=new_layout_id,
                    )))
                except sqlite3.IntegrityError:
                    return False
                else:
                    return True

            cur.execute("""UPDATE dashboard_layout
                   SET layout_id=?, layout_def=?, layout_props=?
                   WHERE owner_id=? AND dashboard_id=? AND layout_id=?""",
                        [new_layout_id, new_layout_def, new_layout_props,
                         owner_id, dashboard_id, old_layout_id])
            return cur.rowcount == 1
项目:collection    作者:skywind3000    | 项目源码 | 文件源码
def delete_all (self, reset_id = False):
        sql1 = 'DELETE FROM stardict;'
        sql2 = "UPDATE sqlite_sequence SET seq = 0 WHERE name = 'stardict';"
        try:
            self.__conn.execute(sql1)
            if reset_id:
                self.__conn.execute(sql2)
            self.__conn.commit()
        except sqlite3.IntegrityError as e:
            self.out(str(e))
            return False
        except sqlite3.Error as e:
            self.out(str(e))
            return False
        return True

    # ??????
项目:pyneng-examples-exercises    作者:natenka    | 项目源码 | 文件源码
def write_rows_to_db(connection, query, data, verbose=False):
    '''
    ??????? ??????? ?????????:
     * connection - ?????????? ? ??
     * query - ??????, ??????? ????? ?????????
     * data - ??????, ??????? ???? ???????? ? ???? ?????? ????????

    ??????? ???????? ???????? ????????? ??????? ?? ?????? data.
    ???? ?????? ??????? ???????? ???????, ????????? ??????????? ? ??.
    ???? ? ???????? ?????? ??????? ???????? ??????, ?????????? ????????????.

    ???? verbose ???????????? ??, ????? ?? ???????? ????????? ?? ???????
    ??? ????????? ?????? ???????.
    '''
    for row in data:
        try:
            with connection:
                connection.execute(query, row)
        except sqlite3.IntegrityError as e:
            if verbose:
                print('??? ?????? ?????? '{}' ???????? ??????'.format(', '.join(row), e))
        else:
            if verbose:
                print('?????? ?????? '{}' ?????? ???????'.format(', '.join(row)))
项目:pyneng-examples-exercises    作者:natenka    | 项目源码 | 文件源码
def write_data_to_db(connection, query, data):
    '''
    ??????? ??????? ?????????:
     * connection - ?????????? ? ??
     * query - ??????, ??????? ????? ?????????
     * data - ??????, ??????? ???? ???????? ? ???? ?????? ????????

    ??????? ???????? ???????? ??? ?????? ?? ?????? data.
    ???? ?????? ??????? ???????? ???????, ????????? ??????????? ? ??
    ? ??????? ?????????? True.
    ???? ? ???????? ?????? ???????? ??????, ?????????? ????????????
    ? ??????? ?????????? False.
    '''
    try:
        with connection:
            connection.executemany(query, data)
    except sqlite3.IntegrityError as e:
        print('Error occured: ', e)
        return False
    else:
        print('?????? ?????? ?????? ???????')
        return True
项目:opserv-backend    作者:OpServ-Monitoring    | 项目源码 | 文件源码
def commit_transaction(self):
        connection = self._connection_helper.retrieve_database_connection()

        try:
            connection.executemany(
                """INSERT INTO {0} ({1}, {2}, {3}, {4}, {5}) VALUES (?, IFNULL(?, "default") ,? ,?, ?)
                """.format(
                    MeasurementsTableManagement.TABLE_NAME(),
                    MeasurementsTableManagement.KEY_COMPONENT_TYPE_FK(),
                    MeasurementsTableManagement.KEY_COMPONENT_ARG_FK(),
                    MeasurementsTableManagement.KEY_METRIC_FK(),
                    MeasurementsTableManagement.KEY_TIMESTAMP(),
                    MeasurementsTableManagement.KEY_VALUE()
                ),
                self.__insertions
            )
            connection.commit()
            connection.close()

        except IntegrityError as err:
            log.error("Error during commit of bulk transaction. Most likely triggered by a duplicate timestamp.")
            log.error(err)
            log.error("Tried to commit these values: %s", str(self.__insertions))

        self.__reset_variables()
项目:synthesizer    作者:irmen    | 项目源码 | 文件源码
def add_tracks(self, tracks):
        before = self.dbconn.execute("SELECT count(*) FROM tracks").fetchone()[0]
        cursor = self.dbconn.cursor()
        for t in tracks:
            try:
                cursor.execute("INSERT INTO tracks(title, artist, album, year, genre, duration, modified, location, hash) VALUES (?,?,?,?,?,?,?,?,?)",
                               (t.title, t.artist, t.album, t.year, t.genre, t.duration, t.modified, t.location, t.hash))
            except sqlite3.IntegrityError as x:
                if str(x) == "UNIQUE constraint failed: tracks.hash":
                    # track already exists with this hash, but update its modification time
                    cursor.execute("UPDATE tracks SET modified=?, year=9999 WHERE hash=?", (t.modified, t.hash))
                else:
                    raise
        after = self.dbconn.execute("SELECT count(*) FROM tracks").fetchone()[0]
        cursor.close()
        self.dbconn.commit()
        amount_new = after - before
        return amount_new
项目:douyuTanmuGet    作者:lidingke    | 项目源码 | 文件源码
def save2sql(self):
        for star in self.hotStarData:
            conn = sqlite3.connect(self.dbName)
            cursor = conn.cursor()
            nowTime = str(int(time.time()))
            sqlTableName = 'pTV' + star['roomid']
            try:
                strEx='create table if not exists '+sqlTableName+' (time int(10) primary key, name varchar(10),\
                title varchar(20), number varchar(10), roomid varchar(10))'
                cursor.execute(strEx)
                strEx = "insert into " + sqlTableName + "(time, name, title, number, roomid) values ("\
                + nowTime+ ",' " + star['name'] + " ' , ' " + star['title'] + " ' , ' " + star['number'] + " ' , ' " + star['roomid'] +" ' )"

                #print(strEx)
                cursor.execute(strEx)
            except sqlite3.OperationalError as e:
                print(self.dbName,e)
            except sqlite3.IntegrityError as e :
                strEx = "insert into " + sqlTableName + "( number ) values (" + star['number'] + ")"
                print(strEx)
                cursor.execute(strEx)
            #except sqlite3.OperationalError as e:
            cursor.close()
            conn.commit()
            conn.close()
项目:douyuTanmuGet    作者:lidingke    | 项目源码 | 文件源码
def save2sql(self):
        for star in self.hotStarData:
            conn = sqlite3.connect(self.dbName)
            cursor = conn.cursor()
            nowTime = str(int(time.time()))
            sqlTableName = self.platform +'TV' + star['roomid']
            try:
                strEx='create table if not exists '+sqlTableName+' (time int(10) primary key, name varchar(10),\
                title varchar(20), number varchar(10), roomid varchar(10))'
                cursor.execute(strEx)
                strEx = "insert into " + sqlTableName + "(time, name, title, number, roomid) values ("\
                + nowTime+ ",' " + star['name'] + " ' , ' " + star['title'] + " ' , ' " + str(star['number']) + " ' , ' " + star['roomid'] +" ' )"

                #print(strEx)
                cursor.execute(strEx)
            except sqlite3.OperationalError as e:
                print(self.dbName,e)
            except sqlite3.IntegrityError as e :
                strEx = "insert into " + sqlTableName + "( number ) values (" + star['number'] + ")"
                print(strEx)
                cursor.execute(strEx)
            #except sqlite3.OperationalError as e:
            cursor.close()
            conn.commit()
            conn.close()
项目:urlmark    作者:NoviceLive    | 项目源码 | 文件源码
def handle(cursor, filenames, parser):
    for filename in filenames:
        with open(filename) as stream:
            for line in stream:
                try:
                    name, link = parser(line)
                except ValueError:
                    pass
                else:
                    if link.strip() == '#':
                        continue
                    sql = 'insert into aliases values (?, ?)'
                    args = (name, link)
                    try:
                        cursor.execute(sql, args)
                    except IntegrityError:
                        pass
                    else:
                        print('Inserted', name, link)
项目:prov2bigchaindb    作者:DLR-SC    | 项目源码 | 文件源码
def test_live_write_account(self):
        db = local_stores.SqliteStore()
        db.clean_tables()
        db.write_account(self.account_id, self.public_key, self.private_key)
        with self.assertRaises(sqlite3.IntegrityError):
            db.write_account(self.account_id, self.public_key, self.private_key)
        db.clean_tables()
项目:originate    作者:keypusher    | 项目源码 | 文件源码
def upsert_connection(remote_connection):
    # Connecting to the database file

    conn = sqlite3.connect(db_file)
    c = conn.cursor()

    remote=remote_connection
    print("Adding: %s" % remote_connection)
    try:
        try:
            # insert a new row
            c.execute("INSERT INTO connections VALUES (?, ?, ?, ?, ?)", 
               [remote.ip, 
                remote.country, 
                remote.continent, 
                remote.tz, 
                remote.divisions])


        except sqlite3.IntegrityError:
            # update existing row
            c.execute('''UPDATE connections SET country = :country, continent = :continent, timezone = :timezone, divisions = :divisions
                      WHERE ip = :ip''', {
                        'ip': remote.ip,
                        'country': remote.country,
                        'continent': remote.continent,
                        'timezone': remote.tz,
                        'divisions': remote.divisions
                      }
            )
            print('IP already exists: {}, updating...'.format(remote.ip))

        conn.commit()
    finally:    
        conn.close()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def CheckContextManagerRollback(self):
        """Is a rollback called in the context manager?"""
        global did_rollback
        self.assertEqual(did_rollback, False)
        try:
            with self.con:
                self.con.execute("insert into test(c) values (4)")
                self.con.execute("insert into test(c) values (4)")
        except sqlite.IntegrityError:
            pass
        self.assertEqual(did_rollback, True)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def CheckIntegrityError(self):
        self.assertTrue(issubclass(sqlite.IntegrityError, sqlite.DatabaseError),
                        "IntegrityError is not a subclass of DatabaseError")
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def CheckExceptions(self):
        # Optional DB-API extension.
        self.assertEqual(self.cx.Warning, sqlite.Warning)
        self.assertEqual(self.cx.Error, sqlite.Error)
        self.assertEqual(self.cx.InterfaceError, sqlite.InterfaceError)
        self.assertEqual(self.cx.DatabaseError, sqlite.DatabaseError)
        self.assertEqual(self.cx.DataError, sqlite.DataError)
        self.assertEqual(self.cx.OperationalError, sqlite.OperationalError)
        self.assertEqual(self.cx.IntegrityError, sqlite.IntegrityError)
        self.assertEqual(self.cx.InternalError, sqlite.InternalError)
        self.assertEqual(self.cx.ProgrammingError, sqlite.ProgrammingError)
        self.assertEqual(self.cx.NotSupportedError, sqlite.NotSupportedError)
项目:saffron    作者:Lamden    | 项目源码 | 文件源码
def insert_account(name, address):
    assert name, address
    try:
        cursor.execute('INSERT INTO accounts(name, address) VALUES (?, ?)', (name, address))
        connection.commit()
    except sqlite3.IntegrityError as e:
        return 'Account exists'
项目:vsphere-storage-for-docker    作者:vmware    | 项目源码 | 文件源码
def CheckContextManagerRollback(self):
        """Is a rollback called in the context manager?"""
        global did_rollback
        self.assertEqual(did_rollback, False)
        try:
            with self.con:
                self.con.execute("insert into test(c) values (4)")
                self.con.execute("insert into test(c) values (4)")
        except sqlite.IntegrityError:
            pass
        self.assertEqual(did_rollback, True)
项目:vsphere-storage-for-docker    作者:vmware    | 项目源码 | 文件源码
def CheckIntegrityError(self):
        self.assertTrue(issubclass(sqlite.IntegrityError, sqlite.DatabaseError),
                        "IntegrityError is not a subclass of DatabaseError")
项目:vsphere-storage-for-docker    作者:vmware    | 项目源码 | 文件源码
def CheckExceptions(self):
        # Optional DB-API extension.
        self.assertEqual(self.cx.Warning, sqlite.Warning)
        self.assertEqual(self.cx.Error, sqlite.Error)
        self.assertEqual(self.cx.InterfaceError, sqlite.InterfaceError)
        self.assertEqual(self.cx.DatabaseError, sqlite.DatabaseError)
        self.assertEqual(self.cx.DataError, sqlite.DataError)
        self.assertEqual(self.cx.OperationalError, sqlite.OperationalError)
        self.assertEqual(self.cx.IntegrityError, sqlite.IntegrityError)
        self.assertEqual(self.cx.InternalError, sqlite.InternalError)
        self.assertEqual(self.cx.ProgrammingError, sqlite.ProgrammingError)
        self.assertEqual(self.cx.NotSupportedError, sqlite.NotSupportedError)
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def CheckContextManagerRollback(self):
        """Is a rollback called in the context manager?"""
        global did_rollback
        self.assertEqual(did_rollback, False)
        try:
            with self.con:
                self.con.execute("insert into test(c) values (4)")
                self.con.execute("insert into test(c) values (4)")
        except sqlite.IntegrityError:
            pass
        self.assertEqual(did_rollback, True)
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def CheckIntegrityError(self):
        self.assertTrue(issubclass(sqlite.IntegrityError, sqlite.DatabaseError),
                        "IntegrityError is not a subclass of DatabaseError")
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def CheckExceptions(self):
        # Optional DB-API extension.
        self.assertEqual(self.cx.Warning, sqlite.Warning)
        self.assertEqual(self.cx.Error, sqlite.Error)
        self.assertEqual(self.cx.InterfaceError, sqlite.InterfaceError)
        self.assertEqual(self.cx.DatabaseError, sqlite.DatabaseError)
        self.assertEqual(self.cx.DataError, sqlite.DataError)
        self.assertEqual(self.cx.OperationalError, sqlite.OperationalError)
        self.assertEqual(self.cx.IntegrityError, sqlite.IntegrityError)
        self.assertEqual(self.cx.InternalError, sqlite.InternalError)
        self.assertEqual(self.cx.ProgrammingError, sqlite.ProgrammingError)
        self.assertEqual(self.cx.NotSupportedError, sqlite.NotSupportedError)
项目:CTF-Tools    作者:sciencemanx    | 项目源码 | 文件源码
def add_exploit(name, kind, code, uid = None):
    if len(name) == 0 or len(kind) == 0:
        return
    uid = uid or str(binascii.b2a_hex(os.urandom(8)), encoding='utf-8')
    exploit = Exploit(uid, name, kind, code)
    print('created exploit: {}'.format(exploit))
    exploits[uid] = exploit
    cur = db.cursor()
    try:
        cur.execute('INSERT INTO exploits VALUES (?, ?, ?, ?)',
                     (uid, name, kind, code))
    except sqlite3.IntegrityError:
        print('exploit already in db -- this is ok')
    else:
        db.commit()
项目:CTF-Tools    作者:sciencemanx    | 项目源码 | 文件源码
def add_ip(ip):
    cur = db.cursor()
    try:
        cur.execute('INSERT INTO ips VALUES (?)', (ip,))
    except sqlite3.IntegrityError:
        print('already had ip in table -- this is ok')
    else:
        db.commit()
    if ip not in ips:
        ips.append(ip)
项目:Gellish    作者:AndriesSHP    | 项目源码 | 文件源码
def InsertRowInTable(self, table_name, row):
        """Insert one row in table_name into GellishDB'."""

        # Insert row of data in table table_name
        command = "INSERT OR REPLACE INTO %s VALUES (?%s)" % (table_name,54*",?")
        try:
            self.db_cursor.execute(command, row)
        except sqlite3.IntegrityError:
            print('ERROR: IdeaUID %i already exists. Insertion ignored.' % (row[15]))

        # Save (commit) the addition
        self.db_connect.commit()
#-------------------------------------------------------------
项目:kripodb    作者:3D-e-Chem    | 项目源码 | 文件源码
def test_duplicate(self, filled_fragmentsdb, myshelve):
        with pytest.raises(sqlite3.IntegrityError):
            filled_fragmentsdb.add_fragments_from_shelve(myshelve)
项目:SciData_08-17-2017    作者:kitestring    | 项目源码 | 文件源码
def load_Data(self, df, table_name):
        #executemany - I couldn't for the life of me get executemany to work...?
        # http://jpython.blogspot.com/2013/11/python-sqlite-example-executemany.html
        data, columns = self.createListOfTuples(df, table_name)

        for row in data:
            try:
                self.conn.execute("INSERT INTO %s %s VALUES %s" % (table_name, columns, row))
            except sqlite3.IntegrityError:
                print("Record Overwritten\n\tTable: %s\n\tID: %s\n" % (table_name, row[0]))
                self.conn.execute("DELETE FROM %s WHERE id = '%s'" % (table_name, row[0]))
                self.conn.execute("INSERT INTO %s %s VALUES %s" % (table_name, columns, row))
项目:raiden    作者:raiden-network    | 项目源码 | 文件源码
def test_write_read_events(tmpdir, in_memory_database):
    log = init_database(tmpdir, in_memory_database)
    event = EventTransferSentFailed(1, 'whatever')
    with pytest.raises(sqlite3.IntegrityError):
        log.storage.write_state_events(1, [(None, 1, 1, log.serializer.serialize(event))])
    assert(len(get_all_state_events(log)) == 0)

    log.storage.write_state_change('statechangedata')
    log.storage.write_state_events(1, [(None, 1, 1, log.serializer.serialize(event))])
    logged_events = get_all_state_events(log)
    assert(len(logged_events) == 1)
    assert(logged_events[0].identifier == 1)
    assert(logged_events[0].state_change_id == 1)
    assert(isinstance(logged_events[0].event_object, EventTransferSentFailed))
项目:mopidy-jukebox    作者:palfrey    | 项目源码 | 文件源码
def post(self):
        url = self.get_body_argument("url")
        if not validators.url(url):
            self.set_status(400, "bad URL")
            return
        with self._connect() as connection:
            try:
                createSource(connection, url)
            except sqlite3.IntegrityError:
                self.set_status(400, "duplicate URL")
                return
        self.set_status(201)