本文整理汇总了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')
示例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')
示例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()
示例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
示例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
示例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)
示例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
示例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()
示例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
)
)
示例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))
示例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)
示例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)
示例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
示例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"))
示例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