• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sqlite.connect函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sqlite.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _getDb

 def _getDb(self, channel):
     try:
         import sqlite
     except ImportError:
         raise callbacks.Error, 'You need to have PySQLite installed to ' \
                                'use Karma.  Download it at ' \
                                '<http://pysqlite.org/>'
     filename = plugins.makeChannelFilename(self.filename, channel)
     if filename in self.dbs:
         return self.dbs[filename]
     if os.path.exists(filename):
         self.dbs[filename] = sqlite.connect(filename)
         return self.dbs[filename]
     db = sqlite.connect(filename)
     self.dbs[filename] = db
     cursor = db.cursor()
     cursor.execute("""CREATE TABLE karma (
                       id INTEGER PRIMARY KEY,
                       name TEXT,
                       normalized TEXT UNIQUE ON CONFLICT IGNORE,
                       added INTEGER,
                       subtracted INTEGER
                       )""")
     db.commit()
     def p(s1, s2):
         return int(ircutils.nickEqual(s1, s2))
     db.create_function('nickeq', 2, p)
     return db
开发者ID:IT-Syndikat,项目名称:its-supybot-plugins,代码行数:28,代码来源:plugin.py


示例2: makeDb

 def makeDb(self, filename):
     if os.path.exists(filename):
         return sqlite.connect(filename)
     db = sqlite.connect(filename)
     cursor = db.cursor()
     cursor.execute(
         """CREATE TABLE keys (
                       id INTEGER PRIMARY KEY,
                       key TEXT UNIQUE ON CONFLICT IGNORE,
                       locked BOOLEAN
                       )"""
     )
     cursor.execute(
         """CREATE TABLE factoids (
                       id INTEGER PRIMARY KEY,
                       key_id INTEGER,
                       added_by TEXT,
                       added_at TIMESTAMP,
                       fact TEXT
                       )"""
     )
     cursor.execute(
         """CREATE TRIGGER remove_factoids
                       BEFORE DELETE ON keys
                       BEGIN
                         DELETE FROM factoids WHERE key_id = old.id;
                       END
                    """
     )
     db.commit()
     return db
开发者ID:EnderBlue,项目名称:supybot,代码行数:31,代码来源:plugin.py


示例3: _getDb

 def _getDb(self, channel):
     try:
         import sqlite
     except ImportError:
         raise callbacks.Error, 'You need to have PySQLite installed to ' \
                                'use QuoteGrabs.  Download it at ' \
                                '<http://pysqlite.org/>'
     filename = plugins.makeChannelFilename(self.filename, channel)
     def p(s1, s2):
         return int(ircutils.nickEqual(s1, s2))
     if filename in self.dbs:
         return self.dbs[filename]
     if os.path.exists(filename):
         self.dbs[filename] = sqlite.connect(filename,
                                             converters={'bool': bool})
         self.dbs[filename].create_function('nickeq', 2, p)
         return self.dbs[filename]
     db = sqlite.connect(filename, converters={'bool': bool})
     self.dbs[filename] = db
     self.dbs[filename].create_function('nickeq', 2, p)
     cursor = db.cursor()
     cursor.execute("""CREATE TABLE quotegrabs (
                       id INTEGER PRIMARY KEY,
                       nick TEXT,
                       hostmask TEXT,
                       added_by TEXT,
                       added_at TIMESTAMP,
                       quote TEXT
                       );""")
     db.commit()
     return db
开发者ID:jreese,项目名称:supybot-plugins,代码行数:31,代码来源:plugin.py


示例4: _getDb

 def _getDb(self, channel):
     try:
         import sqlite
     except ImportError:
         raise callbacks.Error, 'You need to have PySQLite installed to ' \
                                'use Poll.  Download it at ' \
                                '<http://pysqlite.org/>'
     filename = plugins.makeChannelFilename(self.filename, channel)
     if filename in self.dbs:
         return self.dbs[filename]
     if os.path.exists(filename):
         self.dbs[filename] = sqlite.connect(filename)
         return self.dbs[filename]
     db = sqlite.connect(filename)
     self.dbs[filename] = db
     cursor = db.cursor()
     cursor.execute("""CREATE TABLE polls (
                       id INTEGER PRIMARY KEY,
                       question TEXT UNIQUE ON CONFLICT IGNORE,
                       started_by INTEGER,
                       open INTEGER)""")
     cursor.execute("""CREATE TABLE options (
                       id INTEGER,
                       poll_id INTEGER,
                       option TEXT,
                       UNIQUE (poll_id, id) ON CONFLICT IGNORE)""")
     cursor.execute("""CREATE TABLE votes (
                       user_id INTEGER,
                       poll_id INTEGER,
                       option_id INTEGER,
                       UNIQUE (user_id, poll_id)
                       ON CONFLICT IGNORE)""")
     db.commit()
     return db
开发者ID:Latinx,项目名称:supybot,代码行数:34,代码来源:plugin.py


示例5: db1

def db1():
    import sqlite
    conn = sqlite.connect('languagedb') # create file if it doesn't exist
    conn.execute("create table if not exists language_strings(id, language, string)") #create table
    data = []

    for x in xrange (0,1000):
        str1 = (u'STRING#' + str(x))
        data += [(x, u'ENG', str1)] # data for table

    #print data
    conn.executemany("insert into language_strings(id, language, string) values (?,?,?)", data) #record to DB
    conn.commit() # save
    conn.close() # close

    conn = sqlite.connect('languagedb') # open DB
    for row in conn.execute("select * from language_strings"): # regular request
        print row[0], row[1], row[2]
        print '==='

        #conn.row_factory = sqlite3.Row # create the fabric f ROW
        #cur = conn.cursor() # create a cursore
        #cur.execute("select * from person")
        #for row in cur:
        #    print row['firstname'], row[1]
    conn.close()  # close DB
开发者ID:Betrezen,项目名称:Projects,代码行数:26,代码来源:csv_sqlite_compare2.py


示例6: _getDb

 def _getDb(self, channel):
     try:
         import sqlite
     except ImportError:
         raise callbacks.Error, \
               'You need to have PySQLite installed to use this ' \
               'plugin.  Download it at <http://pysqlite.org/>'
     if channel in self.dbs:
         return self.dbs[channel]
     filename = plugins.makeChannelFilename(self.filename, channel)
     if os.path.exists(filename):
         self.dbs[channel] = sqlite.connect(filename)
         return self.dbs[channel]
     db = sqlite.connect(filename)
     self.dbs[channel] = db
     cursor = db.cursor()
     cursor.execute("""CREATE TABLE factoids (
                       key TEXT PRIMARY KEY,
                       created_by INTEGER,
                       created_at TIMESTAMP,
                       modified_by INTEGER,
                       modified_at TIMESTAMP,
                       locked_at TIMESTAMP,
                       locked_by INTEGER,
                       last_requested_by TEXT,
                       last_requested_at TIMESTAMP,
                       fact TEXT,
                       requested_count INTEGER
                       )""")
     db.commit()
     return db
开发者ID:Kefkius,项目名称:mazabot,代码行数:31,代码来源:plugin.py


示例7: create_sqlite

    def create_sqlite(self, file_path, sql_file, autocommit=0):
        if os.path.exists(file_path):
            print >>sys.stderr, "sqlite db already exists", os.path.abspath(file_path)
            return False
        db_dir = os.path.dirname(os.path.abspath(file_path))
        if not os.path.exists(db_dir):
            os.makedirs(db_dir)

        self.sdb = sqlite.connect(file_path, isolation_level=None)    # auto-commit
        self.cur = self.sdb.cursor()
        
        f = open(sql_file)
        sql_create_tables = f.read()
        f.close()
        
        sql_statements = sql_create_tables.split(';')
        for sql in sql_statements:
            self.cur.execute(sql)
        
        self._commit()
        self.sdb.close()
        
        self.sdb = sqlite.connect(file_path)    # auto-commit
        self.cur = self.sdb.cursor()
        
        return True
开发者ID:gvsurenderreddy,项目名称:smoothit-client,代码行数:26,代码来源:bsddb2sqlite.py


示例8: TEST

def TEST(output=log):
    LOGGING_STATUS[DEV_SELECT] = 1
    LOGGING_STATUS[DEV_UPDATE] = 1

    print "------ TESTING MySQLdb ---------"
    rdb = MySQLdb.connect(host="localhost", user="root", passwd="", db="testdb")
    ndb = MySQLdb.connect(host="localhost", user="trakken", passwd="trakpas", db="testdb")
    cursor = rdb.cursor()

    output("drop table agents")
    try:
        cursor.execute("drop table agents")  # clean out the table
    except:
        pass
    output("creating table")

    SQL = """

    create table agents (
       agent_id integer not null primary key auto_increment,
       login varchar(200) not null,
       unique (login),
       ext_email varchar(200) not null,
       hashed_pw varchar(20) not null,
       name varchar(200),
       auth_level integer default 0,
       ticket_count integer default 0)
       """

    cursor.execute(SQL)
    db = odb_mysql.Database(ndb)
    TEST_DATABASE(rdb, db, output=output)

    print "------ TESTING sqlite ----------"
    rdb = sqlite.connect("/tmp/test.db", autocommit=1)
    cursor = rdb.cursor()
    try:
        cursor.execute("drop table agents")
    except:
        pass
    SQL = """
    create table agents (
       agent_id integer primary key,
       login varchar(200) not null,
       ext_email varchar(200) not null,
       hashed_pw varchar(20),
       name varchar(200),
       auth_level integer default 0,
       ticket_count integer default 0)"""
    cursor.execute(SQL)
    rdb = sqlite.connect("/tmp/test.db", autocommit=1)
    ndb = sqlite.connect("/tmp/test.db", autocommit=1)

    db = odb_sqlite.Database(ndb)
    TEST_DATABASE(rdb, db, output=output, is_mysql=0)
开发者ID:litalidev,项目名称:clearsilver,代码行数:55,代码来源:odb_test.py


示例9: opendb

 def opendb(self):
     """
     Öffnet eine DB Schnittstelle
     Benötigt für sqlite
     """
     if self.backend == "sqlite":
         if not os.path.exists(config.index_file):
             # Erstellt die Tabelle
             file(config.index_file, "w")
             self.con = sqlite.connect(config.index_file)
             self.cur = self.con.cursor()
             self.cur.execute('CREATE TABLE pds(file VARCHAR(100), keywords VARCHAR(50))')
         else:
             self.con = sqlite.connect(config.index_file)
             self.cur = self.con.cursor()
开发者ID:BackupTheBerlios,项目名称:pds-svn,代码行数:15,代码来源:backends.py


示例10: insert_to_db

def insert_to_db(bug_number,link,summary,description):


    if check_requirements(bug_number)==1:

        con = sqlite.connect('testdata/tests.db')

        cur=con.cursor()

        cur.execute("select * from tests where bug_number='%s'"%(bug_number))

        if cur.rowcount==0:
            cur.execute("insert into tests(bug_number,link,summary,description) values('%s','%s','%s','%s')"%(bug_number,link,summary,description))
            con.commit()
        else:
            print ""
            print "Regression test for bug %s is already registered."%(bug_number)
            print ""

        con.close()

    else:

        print ""
        print "It seems there is no module %s at bugs package.\nUnable to complete the regression test registration."%(bug_number)
        print ""
开发者ID:italiangrid,项目名称:WMS-Test-Suite,代码行数:26,代码来源:register_regTest.py


示例11: _loadDB

 def _loadDB(self, db):
     try:
         self.store = sqlite.connect(db=db)
         #self.store.autocommit = 0
     except:
         import traceback
         raise KhashmirDBExcept, "Couldn't open DB", traceback.exc_traceback
开发者ID:csm,项目名称:khashmir,代码行数:7,代码来源:khashmir.py


示例12: connect_by_uri

def connect_by_uri(uri):
    puri = urisup.uri_help_split(uri)
    opts = __dict_from_query(puri[QUERY])
    con = sqlite.connect(puri[PATH], client_encoding='utf8')
    if "timeout_ms" in opts:
        con.db.sqlite_busy_timeout(int(opts["timeout_ms"]))
    return con
开发者ID:Eyepea,项目名称:xivo-gallifrey,代码行数:7,代码来源:backsqlite.py


示例13: run_viewer

def run_viewer(options,args):
	import sqlite
	time_format = options.tformat
	sql = "select * from msglog where rowid>"
	sql += "(select max(rowid) from msglog) - %s" % (options.tail,)
	run = 1
	last_id = 0
	failures = 0
	DB = sqlite.connect(options.db)
	cursor = DB.cursor()
	while run:
		if not os.path.exists(options.db):
			# Must do this because removing watched msglog
			#   causes all cpu to be used and machine crash.
			raise IOError('Database does not exist.  Exiting.')
		try:
			try:
				cursor.execute(sql)
				failures = 0
			except sqlite.OperationalError,e:
				if failures >= 10:
					print 'Got OperationalError 10+ times: %r' % e
				failures += 1
			except sqlite.DatabaseError,e:
				print 'Got DatabaseError "%s".  Retrying in 5 seconds.' % e
				time.sleep(5)
				reload(sqlite)
				continue
			for row in cursor:
				print_row(row,time_format)
				last_id = row[0]
			run = options.follow
			sql = 'select * from msglog where rowid>%s' % (last_id)
开发者ID:mcruse,项目名称:monotone,代码行数:33,代码来源:messages.py


示例14: connect

 def connect(self, dbname=None, dbhost=None, dbuser=None, dbpasswd=None, timeout=15, oldstyle=False):
     """ connect to the database. """
     self.dbname = dbname or self.config['dbname']
     self.dbhost = dbhost or self.config['dbhost']
     self.dbuser = dbuser or self.config['dbuser']
     self.dbpasswd = dbpasswd or self.config['dbpasswd']
     self.timeout = timeout
     self.oldstyle = oldstyle or self.config['dboldstyle']
     if self.dbtype == 'mysql':
         import MySQLdb
         self.connection = MySQLdb.connect(db=self.dbname, host=self.dbhost, user=self.dbuser, passwd=self.dbpasswd, connect_timeout=self.timeout, charset='utf8')
     elif 'sqlite' in self.dbtype:
         try:
             import sqlite
             self.connection = sqlite.connect(self.datadir + os.sep + self.dbname)
         except ImportError:
             import sqlite3
             self.connection = sqlite3.connect(self.datadir + os.sep + self.dbname, check_same_thread=False)
     elif self.dbtype == 'postgres':
         import psycopg2
         rlog(1000, 'db', 'NOTE THAT POSTGRES IS NOT FULLY SUPPORTED')
         self.connection = psycopg2.connect(database=self.dbname, host=self.dbhost, user=self.dbuser, password=self.dbpasswd)
     else:
         rlog(100, 'db', 'unknown database type %s' % self.dbtype)
         return 0
     rlog(10, 'db', "%s database ok" % self.dbname)
     return 1
开发者ID:code2u,项目名称:jsb,代码行数:27,代码来源:db.py


示例15: create

    def create(self, admin_passwd, admin_email):
        """Create the contest. This also opens it.
        
        @param admin_passwd: Password for 'admin' account
        @param admin_email:  Emailid of 'admin' account
        """
        if True in [x.isspace() for x in self.name]:
            raise ValueError, 'contest_name must not contain any white space'
        
        # Create directories
        dirs = [self.directory]             # Top-level
        dirs.extend(self.dirs.values())     # others ..
        [os.mkdir(dr) for dr in dirs]

        # Init DB
        dbpath = join(self.dirs['repos'], self.name) # Only one database
        db = sqlite.connect(dbpath, autocommit=True)
        cursor = db.cursor()
        queries = _get_queries(file(join(paths.DATA_DIR, 'contest-sqlite.sql')))
        [cursor.execute(query) for query in queries]
        cursor.close()
        db.close()


        # Open the contest and add admin account to db
        self.open()
        # We use *_sync method as we don't use Twisted's reactor yet!!
        self.dbproxy.add_user_sync('admin', admin_passwd, 'Contest Admin', 
                              admin_email, USER_ADMIN)
开发者ID:BackupTheBerlios,项目名称:codehack-svn,代码行数:29,代码来源:contest.py


示例16: drop_g

def drop_g():
    con = sqlite.connect("g.sqlite")
    cur = con.cursor()
    cur.execute("drop table if exists hash_dir;")
    cur.close()
    con.commit()
    con.close()
开发者ID:mchirico,项目名称:chirico,代码行数:7,代码来源:build_g.py


示例17: __init__

    def __init__(self, filename):
        import sqlite

        self.con = sqlite.connect(filename)
        self.cur = self.con.cursor()

        # create hits table if it does not exist
        self.cur.execute("SELECT name FROM sqlite_master WHERE type = 'table'")
        tables = self.cur.fetchall()

        if ("hits",) not in tables:
            self.cur.execute(
                """
                CREATE TABLE hits (
                    query TEXT,
                    subject TEXT,
                    percid NUMBER,
                    alignlen INT,
                    mismatches INT,
                    gaps INT,
                    qstart INT,
                    qend INT,
                    sstart INT,
                    send INT,
                    evalue NUMBER,
                    bitscore NUMBER
                )
                """
            )
开发者ID:Open-Technology,项目名称:Computational-Biology,代码行数:29,代码来源:blast.py


示例18: setDb

 def setDb(self):
     import sqlite, os
     dbfile = os.path.join(os.curdir, pluginConf.database())
     try:
         os.remove(dbfile)
     except:
         pass
     db = sqlite.connect(dbfile)
     cursor = db.cursor()
     cursor.execute('CREATE TABLE bans ('
             'id INTEGER PRIMARY KEY,'
             'channel VARCHAR(30) NOT NULL,'
             'mask VARCHAR(100) NOT NULL,'
             'operator VARCHAR(30) NOT NULL,'
             'time VARCHAR(300) NOT NULL,'
             'removal DATETIME,'
             'removal_op VARCHAR(30),'
             'log TEXT)')
     cursor.execute('CREATE TABLE comments ('
             'ban_id INTEGER,'
             'who VARCHAR(100) NOT NULL,'
             'comment MEDIUMTEXT NOT NULL,'
             'time VARCHAR(300) NOT NULL)')
     cursor.execute('CREATE TABLE sessions ('
             'session_id VARCHAR(50) PRIMARY KEY,'
             'user MEDIUMTEXT NOT NULL,'
             'time INT NOT NULL)')
     cursor.execute('CREATE TABLE users ('
             'username VARCHAR(50) PRIMARY KEY,'
             'salt VARCHAR(8),'
             'password VARCHAR(50))')
     db.commit()
     cursor.close()
     db.close()
开发者ID:bnrubin,项目名称:Bantracker,代码行数:34,代码来源:test.py


示例19: __init__

	def __init__(self, dbpath):
		"""
		コンストラクタ。
		@param string dbpath SQLiteのDBファイルのパス
		"""
		self.__con = sqlite.connect(dbpath)
		self.__cur = self.__con.cursor()
开发者ID:djsas,项目名称:SQLiteManager,代码行数:7,代码来源:SQLiteManager.py


示例20: handle_url

def handle_url(bot, user, channel, url, msg):
    if not config:
        return
    ret = None
    urlid = "%s|%s" % (channel, url)
    con = sqlite.connect(os.path.join(sys.path[0], "urls.sqlite"))
    cur = con.cursor()
    cur.execute("SELECT * FROM urls WHERE id=%s", (urlid,))
    if cur.rowcount:
        id, userhost, url, channel, timestamp = cur.fetchone()
        pastetime = datetime.datetime.fromtimestamp(timestamp)
        now = datetime.datetime.now()
        age = now - pastetime
        agestr = ""
        if age.days > 0:
            agestr += "%d days " % age.days
        secs = age.seconds
        hours, minutes, seconds = secs // 3600, secs // 60 % 60, secs % 60
        if hours > 0:
            agestr += "%d h " % hours
        if minutes > 0:
            agestr += "%d m " % minutes
        if seconds > 0:
            agestr += "%d s" % seconds
        # don't alert for the same person
        if getNick(user) != getNick(userhost) and channel not in config.get("channels", []):
            ret = bot.say(channel, "%s: wanha. (by %s %s ago)" % (getNick(user), getNick(userhost), agestr))
    else:
        cur.execute("INSERT INTO urls VALUES(%s, %s, %s, %s, %d)", (urlid, user, url, channel, int(time.time())))
    con.commit()
    cur.close()
    con.close()
    return ret
开发者ID:HaleBob,项目名称:pyfibot,代码行数:33,代码来源:module_sqlitewanha.py



注:本文中的sqlite.connect函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sqlite3._connect函数代码示例发布时间:2022-05-27
下一篇:
Python sqlaload.upsert函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap