本文整理汇总了Python中sqlite3.connect方法的典型用法代码示例。如果您正苦于以下问题:Python sqlite3.connect方法的具体用法?Python sqlite3.connect怎么用?Python sqlite3.connect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlite3
的用法示例。
在下文中一共展示了sqlite3.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ip_latency_test
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def ip_latency_test(ip, port=443):
tag = 'IP_Latency_TEST'
print_with_tag(tag, ['Prepare IP latency test for ip', ip, 'Port', str(port)])
s_test = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_test.settimeout(10)
s_start = time.time()
try:
s_test.connect((ip, port))
s_test.shutdown(socket.SHUT_RD)
except Exception as e:
print_with_tag(tag, ['Error:', e])
return None
s_stop = time.time()
s_runtime = '%.2f' % (1000 * (s_stop - s_start))
print_with_tag(tag, [ip, 'Latency:', s_runtime])
return float(s_runtime)
示例2: getGenomeWgsCount
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def getGenomeWgsCount(self, ncbid, threshold):
"""
Gets the number of genomes/wgs available in the directory.
@param threshold: it returns max. threshold genomes/wgs (after this threshold is reached, it returns)
@param dir: directory that contains genomes/wgs in the form: "ncbid.[0-9]*.f[an][sa]"
@return: the number of genomes/wgs from different species that are subclades of the input ncbid
"""
try:
conn = sqlite3.connect(os.path.normpath(self._databaseFile))
cursor = conn.cursor()
speciesIdsList = []
self._collectSpecies(speciesIdsList, cursor, ncbid, threshold)
return len(speciesIdsList)
except Exception:
print "Failed to create connection to a database:", self._databaseFile
raise
finally:
cursor.close()
conn.close()
示例3: __init__
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def __init__(self,ip,name):
with lock:
# Create a database in RAM
self.db = sqlite3.connect('/home/vagrant/iSDX/xrs/ribs/'+ip+'.db',check_same_thread=False)
self.db.row_factory = sqlite3.Row
self.name = name
qs = ', '.join(['?']*len(labels))
self.insertStmt = 'insert into %s values (%s)' % (self.name, qs)
stmt = (
'create table if not exists '+self.name+
' ('+ ', '.join([l+' '+t for l,t in zip(labels, types)])+')'
)
cursor = self.db.cursor()
cursor.execute(stmt)
self.db.commit()
示例4: _process_repo_serial
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def _process_repo_serial(git_repo_dir, sqlite_db_file, commits, extraction_settings):
""" Processes all commits in a given git repository in a serial manner.
Args:
git_repo_dir: path to the git repository that is mined
sqlite_db_file: path (including database name) where the sqlite database will be created
commits: list of commits that have to be processed
extraction_settings: settings for the extraction
Returns:
sqlite database will be written at specified location
"""
git_repo = pydriller.GitRepository(git_repo_dir)
con = sqlite3.connect(sqlite_db_file)
for commit in tqdm(commits, desc='Serial'):
args = {'git_repo_dir': git_repo_dir, 'commit_hash': commit.hash, 'extraction_settings': extraction_settings}
result = _process_commit(args)
if not result['edits'].empty:
result['edits'].to_sql('edits', con, if_exists='append', index=False)
if not result['commit'].empty:
result['commit'].to_sql('commits', con, if_exists='append', index=False)
示例5: new_database
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def new_database(table):
temp_db_path = TEMP_PATH + '/angry_database.db'
if os.path.exists(temp_db_path):
os.remove(temp_db_path)
con = sqlite3.connect(temp_db_path, check_same_thread=False)
cur = con.cursor()
if fts5_pragma_check():
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts5(directory, path, size, date)''')
cur.execute('''PRAGMA user_version = 4;''')
else:
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts4(directory, path, size, date)''')
cur.execute('''PRAGMA user_version = 3;''')
cur.executemany('''INSERT INTO angry_table VALUES (?, ?, ?, ?)''', table)
con.commit()
replace_old_db_with_new()
示例6: new_database_lite
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def new_database_lite(table):
temp_db_path = TEMP_PATH + '/angry_database.db'
if os.path.exists(temp_db_path):
os.remove(temp_db_path)
con = sqlite3.connect(temp_db_path, check_same_thread=False)
cur = con.cursor()
if fts5_pragma_check():
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts5(directory, path)''')
cur.execute('''PRAGMA user_version = 4;''')
else:
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts4(directory, path)''')
cur.execute('''PRAGMA user_version = 3;''')
cur.executemany('''INSERT INTO angry_table VALUES (?, ?)''', table)
con.commit()
replace_old_db_with_new()
示例7: replace_old_db_with_new
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def replace_old_db_with_new(self):
global con
global DATABASE_PATH
temp_db_path = TEMP_PATH + '/angry_database.db'
dir_path = os.path.dirname(DATABASE_PATH)
if not os.path.exists(temp_db_path):
return
if not os.path.exists(dir_path):
os.makedirs(dir_path)
if con:
con.close()
shutil.move(temp_db_path, DATABASE_PATH)
con = sqlite3.connect(DATABASE_PATH, check_same_thread=False)
con.create_function("regexp", 2, regexp)
示例8: contextMenuEvent
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def contextMenuEvent(self, event):
right_click_menu = Qw.QMenu(self)
act_open = right_click_menu.addAction('Open')
act_open.triggered.connect(self.parent().parent().right_clk_open)
act_open_path = right_click_menu.addAction('Open Path')
act_open_path.triggered.connect(self.parent().parent().right_clk_path)
right_click_menu.addSeparator()
act_copy_path = right_click_menu.addAction('Copy Path')
act_copy_path.triggered.connect(self.parent().parent().right_clk_copy)
right_click_menu.exec_(event.globalPos())
# THE PRIMARY GUI DEFINING INTERFACE WIDGET, THE WIDGET WITHIN THE MAINWINDOW
示例9: connection
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def connection(self, commit_on_success=False):
with self._lock:
if self._bulk_commit:
if self._pending_connection is None:
self._pending_connection = sqlite.connect(self.filename)
con = self._pending_connection
else:
con = sqlite.connect(self.filename)
try:
if self.fast_save:
con.execute("PRAGMA synchronous = 0;")
yield con
if commit_on_success and self.can_commit:
con.commit()
finally:
if not self._bulk_commit:
con.close()
示例10: sql_query
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [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
示例11: get
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def get(self, key):
self.logger.debug("Fetching key %s", key)
query = "SELECT value from %s WHERE key=?" % self.table
try:
conn = sqlite3.connect(self.dburi)
c = conn.cursor()
r = c.execute(query, (key,))
value = r.fetchall()
except sqlite3.Error:
self.logger.exception("Error fetching key %s", key)
raise CSStoreError('Error occurred while trying to get key')
self.logger.debug("Fetched key %s got result: %r", key, value)
if len(value) > 0:
return value[0][0]
else:
return None
示例12: set
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [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')
示例13: span
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [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')
示例14: sqlite_get_user_lang
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def sqlite_get_user_lang(user):
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "eig_bot.db")
conn = sqlite3.connect(db_path)
sql = "SELECT lang FROM users WHERE user='"+user+"';";
c = conn.cursor()
c.execute(sql)
data=c.fetchone()
if not data:
sql = "INSERT INTO users(user, lang) VALUES ('"+user+"', 'en');"
c.execute(sql)
conn.commit()
conn.close()
return 'en'
else :
lang = data[0]
conn.close()
return lang
示例15: check_schema_version
# 需要导入模块: import sqlite3 [as 别名]
# 或者: from sqlite3 import connect [as 别名]
def check_schema_version(self):
query = "SELECT Version FROM Globals WHERE Id IS 1"
self.cur.execute(query)
version = float(self.cur.fetchone()[0])
if version > self.VERSION:
raise ValueError("Database version is newer than gphotos-sync")
elif version < self.VERSION:
log.warning(
"Database schema out of date. Flushing index ...\n"
"A backup of the previous DB has been created"
)
self.con.commit()
self.con.close()
self.backup_sql_file()
self.con = lite.connect(str(self.db_file))
self.con.row_factory = lite.Row
self.cur = self.con.cursor()
self.cur2 = self.con.cursor()
self.clean_db()