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


Python sqlite3.connect方法代碼示例

本文整理匯總了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) 
開發者ID:SuzukiHonoka,項目名稱:Starx_Pixiv_Collector,代碼行數:18,代碼來源:start.py

示例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() 
開發者ID:CAMI-challenge,項目名稱:CAMISIM,代碼行數:24,代碼來源:ref_seq.py

示例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() 
開發者ID:sdn-ixp,項目名稱:iSDX,代碼行數:20,代碼來源:rib.py

示例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) 
開發者ID:gotec,項目名稱:git2net,代碼行數:27,代碼來源:extraction.py

示例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() 
開發者ID:DoTheEvo,項目名稱:ANGRYsearch,代碼行數:24,代碼來源:angrysearch_update_database.py

示例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() 
開發者ID:DoTheEvo,項目名稱:ANGRYsearch,代碼行數:24,代碼來源:angrysearch_update_database.py

示例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) 
開發者ID:DoTheEvo,項目名稱:ANGRYsearch,代碼行數:21,代碼來源:angrysearch.py

示例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 
開發者ID:DoTheEvo,項目名稱:ANGRYsearch,代碼行數:20,代碼來源:angrysearch.py

示例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() 
開發者ID:cgrok,項目名稱:clashroyale,代碼行數:19,代碼來源:utils.py

示例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 
開發者ID:rafasashi,項目名稱:razzy-spinner,代碼行數:20,代碼來源:chat80.py

示例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 
開發者ID:latchset,項目名稱:custodia,代碼行數:18,代碼來源:sqlite.py

示例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') 
開發者ID:latchset,項目名稱:custodia,代碼行數:23,代碼來源:sqlite.py

示例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') 
開發者ID:latchset,項目名稱:custodia,代碼行數:18,代碼來源:sqlite.py

示例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 
開發者ID:EvilInsultGenerator,項目名稱:slack-bot,代碼行數:20,代碼來源:eig_plugin.py

示例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() 
開發者ID:gilesknap,項目名稱:gphotos-sync,代碼行數:21,代碼來源:LocalData.py


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