本文整理汇总了Python中sqlite3.dbapi2.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __conectar
def __conectar(self):
"""Método privado, que nos servirá para conectarnos a la base de datos."""
# Comprobamos si ya existe la base de datos
# para simplemente, conectarnos.
if os.path.exists(self.__fichero):
return sqlite.connect(self.__fichero)
# En caso de que no exista, creamos la base de datos.
else:
conexion = sqlite.connect(self.__fichero)
cursor = conexion.cursor()
# Creamos la tabla CLIENTES
TABLA = """
CREATE TABLE CLIENTES (
ID INTEGER PRIMARY KEY,
NOMBRE VARCHAR(20),
APELLIDOS VARCHAR(40),
EMAIL VARCHAR(30),
TELEFONO VARCHAR(12),
EMPRESA VARCHAR(30),
CIFONIF VARCHAR(30),
);"""
# ejecutamos la sentencia
cursor.execute(TABLA)
# MUY IMPORTANTE:
conexion.commit()
# devolvemos la conexión
return conexion
开发者ID:AdaLovelance,项目名称:kaotika,代码行数:32,代码来源:clientes_modelo.py
示例2: __init__
def __init__(self, api_key='', debug=False, lang='fr'):
self.api_key = self.ADDON.getSetting('api_tmdb')
self.debug = debug
self.lang = lang
self.poster = 'https://image.tmdb.org/t/p/%s' % self.ADDON.getSetting('poster_tmdb')
self.fanart = 'https://image.tmdb.org/t/p/%s' % self.ADDON.getSetting('backdrop_tmdb')
#self.cache = cConfig().getFileCache()
try:
#if not os.path.exists(self.cache):
if not xbmcvfs.exists(self.CACHE):
#f = open(self.cache,'w')
#f.close()
self.db = sqlite.connect(self.REALCACHE)
self.db.row_factory = sqlite.Row
self.dbcur = self.db.cursor()
self.__createdb()
except:
VSlog('erreur: Impossible d ecrire sur %s' % self.REALCACHE )
pass
try:
self.db = sqlite.connect(self.REALCACHE)
self.db.row_factory = sqlite.Row
self.dbcur = self.db.cursor()
except:
VSlog('erreur: Impossible de ce connecter sur %s' % self.REALCACHE )
pass
开发者ID:LordVenom,项目名称:venom-xbmc-addons,代码行数:29,代码来源:tmdb.py
示例3: makeSQliteTables
def makeSQliteTables():
#2008-05-29 [email protected]
#This is pretty tricky...
#We first set up the SQLite and MySQL connector statements
#And then we grab all the counties from the county table
#on coolprime and push into a SQLite db. Once we have the
#counties we iterate through each county and grab the column
#headers so we can build a 'create xxxxx_county_reports' statement
#based on the structure of the table on coolprime. This way we
#can mod the table structure at will and this code will adapt.
#Sweet!
#
#SQLite
global beachreports
if(DEBUG == 0):
beachreports = sqlite.connect(":memory:", isolation_level=None)
else:
beachreports = sqlite.connect("./beachreports.db", isolation_level=None)
cur1 = beachreports.cursor()
cur2 = beachreports.cursor()
cur1.execute('create table counties (id integer primary key, county varchar(25))')
cur1.execute('create table subscribers (id integer primary key, email varchar(25), county varchar(25))')
#MySQL
global db
db = MySQLdb.connect(host=dbHost, user=dbUser, passwd=dbPass,db=dbDB)
cursor1 = db.cursor()
cursor2 = db.cursor()
countyQuery = "SELECT county from counties ORDER BY county ASC"
result = cursor1.execute(countyQuery)
if (result != 0):
for (myCounty) in cursor1:
createStatement = ""
county = "%s" % myCounty
county_reports = "%s_county_reports" % county
#print "County: %s" % county
cur2.execute("INSERT into counties(county) VALUES(?)", (county, ))
#get column headers
columnQuery = "DESCRIBE %s" % county_reports
result = cursor2.execute(columnQuery)
index = 1
if (result != 0):
for (header) in cursor2:
if(index < result):
createStatement = createStatement + "%s %s," % (header[0],header[1])
else:
createStatement = createStatement + "%s %s" % (header[0],header[1])
index += 1
createStatement = "create table " + county_reports + \
"(" "id integer primary key," + createStatement + ")"
if(DEBUG > 1):
print "makeSQLiteTables(): createStatement = %s\n" % createStatement
cur2.execute(createStatement)
cur1.close()
cur2.close()
cursor1.close()
cursor2.close()
开发者ID:mote-ocean-technology,项目名称:BCRS,代码行数:60,代码来源:sendBeachEmail.py
示例4: deleteFavourite
def deleteFavourite(meta, content):
try:
meta = json.loads(meta)
imdb = meta['imdb']
if 'title' in meta: title = meta['title']
if 'tvshowtitle' in meta: title = meta['tvshowtitle']
try:
dbcon = database.connect(control.favouritesFile)
dbcur = dbcon.cursor()
dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, imdb))
dbcon.commit()
except:
pass
try:
dbcon = database.connect(control.databaseFile)
dbcur = dbcon.cursor()
dbcur.execute("DELETE FROM favourites WHERE imdb_id = '%s'" % imdb)
dbcon.commit()
except:
pass
control.refresh()
control.infoDialog(control.lang(30412).encode('utf-8'), heading=title)
except:
return
开发者ID:JRepoInd,项目名称:lambda-addons,代码行数:26,代码来源:favourites.py
示例5: onPlayBackStopped
def onPlayBackStopped(self):
'''
Called when playback is stopped (normal or otherwise)
Checks to see if we've watched more than watch_percent. If so, then the bookmark is deleted and
watchedCallback is called if it exists.
If we didn't play at all, raises a playback failed exception.
Otherwise, save a new bookmark at the furthest watched spot.
'''
addon.log('> onPlayBackStopped')
self._playbackLock.clear()
playedTime = self._lastPos
addon.log('playedTime / totalTime : %s / %s = %s' % (playedTime, self._totalTime, playedTime/self._totalTime))
if playedTime == 0 and self._totalTime == 999999:
raise PlaybackFailed('XBMC silently failed to start playback')
elif (((playedTime/self._totalTime) > self.watch_percent) and (self.video_type == 'movie' or (self.season and self.episode))):
addon.log('Threshold met.')
if self.watchedCallback: self.watchedCallback()
db = sqlite.connect(DB_PATH)
db.execute('DELETE FROM bookmarks WHERE plugin=? AND video_type=? AND title=? AND season=? AND episode=? AND year=?', (self.plugin, self.video_type, self.title, self.season, self.episode, self.year))
db.commit()
db.close()
else:
addon.log('Threshold not met. Saving bookmark')
db = sqlite.connect(DB_PATH)
db.execute('INSERT OR REPLACE INTO bookmarks (plugin, video_type, title, season, episode, year, bookmark) VALUES(?,?,?,?,?,?,?)',
(self.plugin, self.video_type, self.title, self.season, self.episode, self.year, playedTime))
db.commit()
db.close()
开发者ID:philtimmes,项目名称:addons,代码行数:30,代码来源:playbackengine.py
示例6: main
def main(argv):
if len(argv) != 3:
print >> sys.stderr, "Syntax: %s old.db new.db" % argv[0]
print >> sys.stderr, "New db must exist but have no contents."
con1 = sqlite.connect(argv[1])
con1.text_factory = str
cur1 = con1.cursor()
con2 = sqlite.connect(argv[2])
cur2 = con2.cursor()
# Convert table board
cur1.execute('SELECT id, title FROM board')
for result in cur1.fetchall():
cur2.execute(u'INSERT INTO board (id, title) VALUES (%s, %s)' %
tuple([sqlquote(x) for x in result]))
# Convert for table forum
cur1.execute('SELECT id, boardid, title FROM forum')
for result in cur1.fetchall():
cur2.execute(u'INSERT into forum (id, boardid, title) VALUES '\
u'(%s, %s, %s)' % tuple(
[sqlquote(x) for x in result]))
# Convert for table message
cur1.execute('SELECT id, forumid, boardid, mdate, mtime, mto, mfrom, reference, subject, body FROM message')
for result in cur1.fetchall():
cur2.execute(u'INSERT into message (id, forumid, boardid, mdate, mtime, mto, mfrom, reference, subject, body) VALUES '\
u'(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' % tuple(
[sqlquote(x) for x in result]))
con2.commit()
con2.close()
开发者ID:jace,项目名称:qwkweb,代码行数:30,代码来源:cp850-to-unicode.py
示例7: __init__
def __init__(self, dbPath=".", dbName="UbuWeb.db", dbURL=None, updateURL=None, init=True, xbmc=True):
# TODO
# Make option to check status of database
self.dbPath = os.path.join(dbPath, dbName)
self.dbURL = dbURL
self.updateURL = updateURL
if init:
if not os.path.exists(dbPath):
os.makedirs(dbPath)
if dbURL is not None:
self.getDB(self.dbURL)
self.db = sqlite.connect(self.dbPath)
self.db.text_factory = str
else:
self.db = sqlite.connect(self.dbPath)
self.db.text_factory = str
self.createUbuWebDB()
self.parseFilmListingPage(numLinks=None, startLink=16)
else:
self.db = sqlite.connect(self.dbPath)
self.db.text_factory = str
if self.updateURL is not None:
self.checkDB()
开发者ID:alcoheca,项目名称:plugin.video.ubuweb,代码行数:25,代码来源:UbuWeb.py
示例8: create_database
def create_database(driver, database, username=None, password=None,
hostname=None):
if driver == 'sqlite':
db = SqliteDatabase(database)
return db
elif driver == 'mysql':
db = MysqlDatabase(database, username, password, hostname)
elif driver == 'postgres':
# TODO
raise DatabaseDriverNotSupported
else:
raise DatabaseDriverNotSupported
# Try to connect to database
try:
db.connect().close()
return db
except AccessDenied, e:
if password is None:
import sys
import getpass
# FIXME: catch KeyboardInterrupt exception
# FIXME: it only works on UNIX (/dev/tty),
# not sure whether it's bug or a feature, though
oldout, oldin = sys.stdout, sys.stdin
sys.stdin = sys.stdout = open('/dev/tty', 'r+')
password = getpass.getpass()
sys.stdout, sys.stdin = oldout, oldin
return create_database(driver, database, username, password,
hostname)
raise e
开发者ID:apepper,项目名称:cvsanaly,代码行数:33,代码来源:Database.py
示例9: _initialiseDB
def _initialiseDB(self):
from sqlite3 import dbapi2 as sqlite
self._dbFile = os.path.join(self._g.DATA_PATH, 'art.db')
self._db = sqlite.connect(self._dbFile)
self._createDB()
self._menuFile = os.path.join(self._g.DATA_PATH, 'menu-%s.db' % self._g.MarketID)
self._menuDb = sqlite.connect(self._menuFile)
开发者ID:Sandmann79,项目名称:xbmc,代码行数:7,代码来源:amazontld.py
示例10: __init__
def __init__(self, path, db_name="base.db"):
'''constructor'''
self.path = path
self.db_name = db_name
self.events = {}
self.groups = {}
self.accounts = {}
full_path = os.path.join(path, db_name)
if os.path.exists(full_path + "copy"):
shutil.copy(full_path + "copy", full_path)
self.connection = sqlite.connect(full_path)
self.cursor = self.connection.cursor()
if self.__need_clean():
self.__clean()
self.connection = sqlite.connect(full_path)
self.cursor = self.connection.cursor()
self._count = 0
try:
self._create()
except sqlite.OperationalError:
self._load_events()
self._load_groups()
self._load_accounts()
self._load_account_by_group()
开发者ID:Narciso91,项目名称:emesene,代码行数:32,代码来源:Logger.py
示例11: __init__
def __init__(self,db_filename):
self.db_filename = db_filename
if not os.path.isfile(self.db_filename):
self.con = sqlite.connect(self.db_filename)
self.con.execute("create table data (key PRIMARY KEY,value)")
else:
self.con = sqlite.connect(self.db_filename)
开发者ID:chrisidefix,项目名称:media-folder-sync,代码行数:7,代码来源:dbdict.py
示例12: update_musicbrainzid
def update_musicbrainzid( type, info ):
log( "Updating MusicBrainz ID", xbmc.LOGDEBUG )
artist_id = ""
try:
if type == "artist": # available data info["local_id"], info["name"], info["distant_id"]
name, artist_id, sortname = get_musicbrainz_artist_id( info["name"] )
conn = sqlite3.connect(addon_db)
c = conn.cursor()
c.execute('UPDATE alblist SET musicbrainz_artistid="%s" WHERE artist="%s"' % (artist_id, info["name"]) )
try:
c.execute('UPDATE lalist SET musicbrainz_artistid="%s" WHERE name="%s"' % (artist_id, info["name"]) )
except:
pass
conn.commit
c.close()
if type == "album":
album_id = get_musicbrainz_album( info["title"], info["artist"], 0 )["id"]
conn = sqlite3.connect(addon_db)
c = conn.cursor()
c.execute("""UPDATE alblist SET musicbrainz_albumid='%s' WHERE title='%s'""" % (album_id, info["title"]) )
conn.commit
c.close()
except:
print_exc()
return artist_id
开发者ID:Rah85,项目名称:script.cdartmanager,代码行数:25,代码来源:musicbrainz_utils.py
示例13: __conectar
def __conectar(self):
"""Método privado, que nos servirá para conectarnos a la base de datos."""
# Comprobamos si ya existe la base de datos
# para simplemente, conectarnos.
if os.path.exists(self.__fichero):
return sqlite.connect(self.__fichero)
# En caso de que no exista, creamos la base de datos.
else:
conexion = sqlite.connect(self.__fichero)
cursor = conexion.cursor()
#CREAMOS LA TABLA ZONAS
TABLA = """
CREATE TABLE ZONAS (
ID INTEGER PRIMARY KEY,
CODIGOPOSTAL VARCHAR(20),
TIPOZONA VARCHAR(30),
CANTIDADFOLLETOS VARCHAR(20),
PRECIOPORMILLAR VARCHAR(30),
PRECIOTOTAL VARCHAR(20)"""
cursor.execute(TABLA)
#CREAMOS LA TABLA BUZONEOS
conexion.commit()
# devolvemos la conexión
return conexion
开发者ID:AdaLovelance,项目名称:kaotika,代码行数:29,代码来源:zonas_modelo.py
示例14: _merge
def _merge(self):
if not os.path.isfile(self._fromdb):
raise OriginError("%r is not a file." % self._fromdb)
new = sqlite.connect(self._fromdb)
self._fromcursor = new_cursor = new.cursor(_DictCursor)
if not os.path.isfile(self._todb):
raise DestinationError("%r is not a file." % self._todb)
old = sqlite.connect(self._todb)
self._tocursor = old_cursor = old.cursor(_DictCursor)
new_tables = new_cursor.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table'").fetchall()
for table in new_tables:
name = table['name']
# Verify that this table is in the older db, or not
old_table = old_cursor.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' AND name=?", (name, )).fetchone()
if old_table is None:
# The older db does not have this table, create it there as
# well the related triggers.
print "Adding the table '%s' and related triggers." % name
if self._dryrun:
continue
self._create_table(name)
self._create_triggers(name)
else:
self._merge_table(name)
self._merge_triggers(name)
开发者ID:aregee,项目名称:network-scanner,代码行数:35,代码来源:sqlitedb.py
示例15: __init__
def __init__(self, sqlite_file, maf_file, target_seqname):
"""Indexes or loads the index of a MAF file"""
import os
try:
from sqlite3 import dbapi2 as _sqlite
except ImportError:
from Bio import MissingPythonDependencyError
raise MissingPythonDependencyError("Requires sqlite3, which is "
"included Python 2.5+")
self._target_seqname = target_seqname
self._maf_file = maf_file
# make sure maf_file exists, then open it up
if os.path.isfile(self._maf_file):
self._maf_fp = open(self._maf_file, "r")
else:
raise ValueError("Error opening %s -- file not found" % (self._maf_file,))
# if sqlite_file exists, use the existing db, otherwise index the file
if os.path.isfile(sqlite_file):
self._con = _sqlite.connect(sqlite_file)
self._record_count = self.__check_existing_db()
else:
self._con = _sqlite.connect(sqlite_file)
self._record_count = self.__make_new_index()
# lastly, setup a MafIterator pointing at the open maf_file
self._mafiter = MafIterator(self._maf_fp)
开发者ID:mhozza,项目名称:biopython,代码行数:31,代码来源:MafIO.py
示例16: onPlayBackStopped
def onPlayBackStopped(self):
addon.log("> onPlayBackStopped")
self._playbackLock.clear()
playedTime = self._lastPos
watched_values = [0.7, 0.8, 0.9]
min_watched_percent = watched_values[int(addon.get_setting("watched-percent"))]
addon.log("playedTime / totalTime : %s / %s = %s" % (playedTime, self._totalTime, playedTime / self._totalTime))
if playedTime == 0 and self._totalTime == 999999:
raise PlaybackFailed("XBMC silently failed to start playback")
elif (playedTime / self._totalTime) > min_watched_percent:
addon.log("Threshold met. Marking item as watched")
self.ChangeWatched(
self.imdbnum, self.video_type, self.title, self.season, self.episode, self.year, watched=7
)
db = sqlite.connect(DB)
db.execute(
"DELETE FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?",
(self.video_type, self.title, self.season, self.episode, self.year),
)
db.commit()
db.close()
else:
addon.log("Threshold not met. Saving bookmark")
db = sqlite.connect(DB)
db.execute(
"INSERT OR REPLACE INTO bookmarks (video_type, title, season, episode, year, bookmark) VALUES(?,?,?,?,?,?)",
(self.video_type, self.title, self.season, self.episode, self.year, playedTime),
)
db.commit()
db.close()
开发者ID:madgematthew,项目名称:1Channel,代码行数:31,代码来源:playback.py
示例17: alterFavourites
def alterFavourites(content, favourites):
try:
dbcon = database.connect(control.databaseFile)
dbcur = dbcon.cursor()
dbcon2 = database.connect(control.favouritesFile)
dbcur2 = dbcon2.cursor()
dbcur2.execute("CREATE TABLE IF NOT EXISTS %s (""id TEXT, ""items TEXT, ""UNIQUE(id)"");" % content)
except:
return
for i in favourites:
try:
dbcur.execute("DELETE FROM favourites WHERE imdb_id = '%s'" % i['imdb'])
except:
pass
try:
dbcur2.execute("INSERT INTO %s Values (?, ?)" % content, (i['imdb'], repr({'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tmdb': i['tmdb'], 'tvdb': i['tvdb'], 'tvrage': i['tvrage'], 'poster': i['poster'], 'fanart': i['fanart']})))
except:
pass
try:
dbcon.commit()
dbcon2.commit()
except:
return
开发者ID:JRepoInd,项目名称:lambda-addons,代码行数:25,代码来源:favourites.py
示例18: connect
def connect(self):
if self.LOGGING_LEVEL == 1:
IGNORE_UNIQUE_ERRORS = False
SILENT_STATEMENTS = False
try:
import mysql.connector as database
self.log("Loading mysql.connector as DB engine")
self.DBH = database.connect(self.dbname, self.username, self.password, self.host, buffered=True)
except:
import MySQLdb as database
self.log("Loading MySQLdb as DB engine")
self.DBH=database.connect(host=self.host,user=self.username,passwd=self.password,db=self.dbname)
self.DBC = self.DBH.cursor()
try:
row = self.query("SELECT version, (version < ?) AS outdated FROM rw_version ORDER BY version DESC LIMIT 1", [DATABASE_VERSION])
outdated = str2bool(str(row[1]))
if outdated:
self.log("Database outdated", level=0)
self.initialize()
self.log("Upgrading database", level=0)
for v in range(row[0]+1, DATABASE_VERSION+1):
upgrade_file = "upgrade.mysql.%s.sql" % str(v)
self.runSQLFile(upgrade_file)
self.commit()
self.log("Database version: %s" % str(DATABASE_VERSION))
except:
self.initialize()
开发者ID:jolid,项目名称:script.module.donnie,代码行数:27,代码来源:databaseconnector.py
示例19: __init__
def __init__(self, dbfile):
if not os.path.exists(dbfile):
self.conn = sqlite.connect(dbfile)
self.cursor = self.conn.cursor()
self.create_table()
self.conn = sqlite.connect(dbfile)
self.cursor = self.conn.cursor()
开发者ID:bviecelli,项目名称:PythonBot,代码行数:7,代码来源:bot_sql.py
示例20: __conectar
def __conectar(self):
"""Método privado, que nos servirá para conectarnos a la base de datos."""
# Comprobamos si ya existe la base de datos
# para simplemente, conectarnos.
if os.path.exists(self.__fichero):
return sqlite.connect(self.__fichero)
# En caso de que no exista, creamos la base de datos.
else:
conexion = sqlite.connect(self.__fichero)
cursor = conexion.cursor()
#CREAMOS LA TABLA BUZONEOS
TABLA = """
CREATE TABLE BUZONEOS (
ID INTEGER PRIMARY KEY,
BUZONEOSCODIGOPOSTAL INT(9)
BUZONEOSCLIENTE VARCHAR(30),
BUZONEOSZONA VARCHAR(30),
NUMEROFOLLETOSBUZONEOS VARCHAR(30),
TIPOBUZONEO VARCHAR(30),
FECHABUZONEO VARCHAR(30),
)"""
cursor.execute(TABLA)
# MUY IMPORTANTE:
conexion.commit()
# devolvemos la conexión
return conexion
开发者ID:AdaLovelance,项目名称:kaotika,代码行数:31,代码来源:buzoneos_modelo.py
注:本文中的sqlite3.dbapi2.connect函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论