本文整理汇总了Python中mysql.connector.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _connect_to_db
def _connect_to_db(self):
# connect to db at class init and use it globally
if DB == "mysql":
class MySQLCursorDict(database.cursor.MySQLCursor):
def _row_to_python(self, rowdata, desc=None):
row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
if row:
return dict(zip(self.column_names, row))
return None
self.dbcon = database.connect(
database=common.db_name,
user=common.db_user,
password=common.db_pass,
host=common.db_address,
buffered=True,
charset="utf8",
)
self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True)
else:
self.dbcon = database.connect(self.db)
self.dbcon.row_factory = (
database.Row
) # return results indexed by field names and not numbers so we can convert to dict
self.dbcon.text_factory = str
self.dbcur = self.dbcon.cursor()
示例2: onPlayBackStarted
def onPlayBackStarted(self):
xbmc.log("1Channel: Service: Playback started")
self.tracking = self.check()
if self.tracking:
xbmc.log("1Channel: Service: tracking progress...")
win = xbmcgui.Window(10000)
self.title = win.getProperty("1ch.playing.title")
self.imdb = win.getProperty("1ch.playing.imdb")
self.season = win.getProperty("1ch.playing.season")
self.year = win.getProperty("1ch.playing.year")
self.episode = win.getProperty("1ch.playing.episode")
if self.season or self.episode:
self.video_type = "tvshow"
else:
self.video_type = "movie"
self._totalTime = self.getTotalTime()
sql = "SELECT bookmark FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?"
if DB == "mysql":
sql = sql.replace("?", "%s")
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
else:
db = database.connect(db_dir)
cur = db.cursor()
cur.execute(sql, (self.video_type, self.title, self.season, self.episode, self.year))
bookmark = cur.fetchone()
db.close()
if bookmark:
bookmark = float(bookmark[0])
if not (self._sought and (bookmark - 30 > 0)):
question = "Resume %s from %s?" % (self.title, format_time(bookmark))
resume = xbmcgui.Dialog()
resume = resume.yesno(self.title, "", question, "", "Start from beginning", "Resume")
if resume:
self.seekTime(bookmark)
self._sought = True
示例3: ListArtist
def ListArtist(url,arttype):
sql = 'SELECT * FROM artist where art_type =? ORDER BY name'
if DB == 'mysql':
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
sql = sql.replace('?','%s')
else: db = database.connect( db_dir )
cur = db.cursor()
cur.execute(sql, (arttype,))
favs = cur.fetchall()
artist=""
totalartist = 0
addLink("Refresh Artist Database",url+"|"+arttype,8,"")
for row in favs:
totalartist=totalartist+1
artistname = row[0]
artisturl = row[1].replace(" ","%20")
artistimg = row[2]
addDir(artistname,artisturl,6,artistimg)
db.close()
if(totalartist==0):
artistlist=GetArtist(url,arttype)
for vurl,vimg,aname in artistlist:
cursql=""
addDir(TAG_RE.sub('', aname),vurl,6,vimg)
示例4: connect_db
def connect_db():
if DB == 'mysql':
db = orm.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_ADDR, buffered=True)
else:
db = orm.connect(DB_DIR)
db.text_factory = str
return db
示例5: __init__
def __init__(self):
#Check if a path has been set in the addon settings
db_path = common.addon.get_setting('local_db_location')
if db_path:
self.path = xbmc.translatePath(db_path)
else:
self.path = xbmc.translatePath('special://profile/addon_data/script.icechannel/databases')
self.path = common.make_dir(self.path, '')
self.db = os.path.join(self.path, self.local_db_name)
# connect to db at class init and use it globally
if DB == 'mysql':
class MySQLCursorDict(database.cursor.MySQLCursor):
def _row_to_python(self, rowdata, desc=None):
row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
if row:
return dict(zip(self.column_names, row))
return None
self.dbcon = database.connect(database=common.addon.get_setting('db_name'), user=common.addon.get_setting('db_user'),
password=common.addon.get_setting('db_pass'), host=common.addon.get_setting('db_address'), buffered=True, charset='utf8')
self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True)
else:
self.dbcon = database.connect(self.db)
self.dbcon.row_factory = database.Row # return results indexed by field names and not numbers so we can convert to dict
self.dbcon.text_factory = str
self.dbcur = self.dbcon.cursor()
self._create_subscription_tables()
示例6: mysql
def mysql(u,username='root',password=''):
try:
mconn.connect(host=u,user=username, password=password)
return True
except Exception as e:
pass
return False
示例7: ListSongs
def ListSongs(artist_url,album):
sql = 'SELECT artist_url,album, img, name,url FROM songs where artist_url=? and album =? ORDER BY name'
if DB == 'mysql':
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
sql = sql.replace('?','%s')
else: db = database.connect( db_dir )
cur = db.cursor()
cur.execute(sql, (artist_url,album))
favs = cur.fetchall()
artist=""
totalsong = 0
xbmc.PlayList(0).clear()
addLink("Play All",artist_url,10,"")
for row in favs:
totalsong=totalsong+1
arturl = row[0]
album=row[1]
songImg=row[2]
songname = row[3]
songurl = row[4].replace(" ","%20")
addPlaylist(songname,songurl,songImg,"")
songitem(songname,songurl,songImg,album,artist, totalsong)
db.close()
示例8: __init__
def __init__(self, db_host='localhost', db_user='', db_user_passwd='', db_name='', charset = '', debug = 0, db_port=3306, curstype='TUPLE'):
"""
初始化数据库连接
@param db_host: 地址
@param db_user: 用户名
@param db_user_passwd: 密码
@param db_name: 数据库名称
@param charset: 字符集
@param debug: 调试模式
@param db_port: 端口号
"""
try:
if isinstance(db_host, unicode):db_host = db_host.encode('utf8')
if isinstance(db_user, unicode):db_user = db_user.encode('utf8')
if isinstance(db_user_passwd, unicode):db_user_passwd = db_user_passwd.encode('utf8')
if isinstance(db_name, unicode):db_name = db_name.encode('utf8')
if isinstance(charset, unicode):charset= charset.encode('utf8')
if isinstance(db_port, unicode):db_port= db_port.encode('utf8')
if isinstance(db_port, str):db_port= int(db_port)
if charset != '':
self.mdb = dblib.connect(host=db_host, port=db_port, user=db_user, passwd=db_user_passwd, db=db_name, charset=charset, use_unicode = False ) #, charset='utf8'
self.charset = charset
else:
self.mdb = dblib.connect(db_host, db_user, db_user_passwd, db_name, db_port )
self.debug = debug
#print "character_set_name:",self.mdb.character_set_name()
except dblib.Error, error:
print "Connect MySql[%s %s/%s %s] DB Error:"%(db_host,db_user,db_user_passwd,db_name),error,"\n"
示例9: initDatabase
def initDatabase():
print 'Building Khmermusic Database'
if DB == 'mysql':
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
cur = db.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS artist ( name TEXT,artist_url VARCHAR(255) UNIQUE,img VARCHAR(255) ,art_type VARCHAR(255),PRIMARY KEY (url))')
cur.execute('CREATE TABLE IF NOT EXISTS songs (artist_url VARCHAR(255), album TEXT,img VARCHAR(255) ,name TEXT, url VARCHAR(255) UNIQUE,PRIMARY KEY (url))')
cur.execute('CREATE TABLE IF NOT EXISTS playlist (playlist_id,url VARCHAR(255), name UNIQUE)')
else:
if not os.path.isdir(os.path.dirname(db_dir)):
os.makedirs(os.path.dirname(db_dir))
db = database.connect(db_dir)
db.execute('CREATE TABLE IF NOT EXISTS artist (name,artist_url PRIMARY KEY,img, art_type)')
db.execute('CREATE TABLE IF NOT EXISTS songs ( artist_url, album TEXT,img,name, url PRIMARY KEY)')
db.execute('CREATE TABLE IF NOT EXISTS playlist (playlist_id INTEGER PRIMARY KEY AUTOINCREMENT,song_id,url, name)')
db.commit()
db.close()
示例10: onPlayBackStarted
def onPlayBackStarted(self):
xbmc.log('1Channel: Service: Playback started')
self.tracking = self.check()
if self.tracking:
xbmc.log('1Channel: Service: tracking progress...')
win = xbmcgui.Window(10000)
self.title = win.getProperty('1ch.playing.title')
self.imdb = win.getProperty('1ch.playing.imdb')
self.season = win.getProperty('1ch.playing.season')
self.year = win.getProperty('1ch.playing.year')
self.episode = win.getProperty('1ch.playing.episode')
if self.season or self.episode:
self.video_type = 'tvshow'
else:
self.video_type = 'movie'
self._totalTime = self.getTotalTime()
sql = 'SELECT bookmark FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?'
if DB == 'mysql':
sql = sql.replace('?', '%s')
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
else:
db = database.connect(db_dir)
cur = db.cursor()
cur.execute(sql, (self.video_type, self.title, self.season, self.episode, self.year))
bookmark = cur.fetchone()
db.close()
if bookmark:
bookmark = float(bookmark[0])
if not (self._sought and (bookmark - 30 > 0)):
question = 'Resume %s from %s?' % (self.title, format_time(bookmark))
resume = xbmcgui.Dialog()
resume = resume.yesno(self.title, '', question, '', 'Start from beginning', 'Resume')
if resume: self.seekTime(bookmark)
self._sought = True
示例11: __connect_to_db
def __connect_to_db(self):
if not self.db:
if self.db_type == DB_TYPES.MYSQL:
self.db = db_lib.connect(database=self.dbname, user=self.username, password=self.password, host=self.address, buffered=True)
else:
self.db = db_lib.connect(self.db_path)
self.db.text_factory = str
示例12: ListAlbum
def ListAlbum(url):
sql = 'SELECT distinct artist_url,album,img FROM songs where artist_url=? order by album'
if DB == 'mysql':
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
sql = sql.replace('?','%s')
else: db = database.connect( db_dir )
cur = db.cursor()
cur.execute(sql, (url,))
favs = cur.fetchall()
artist=""
totalalbum = 0
addLink("Refresh Album Database",url,9,"")
for row in favs:
totalalbum=totalalbum+1
arturl = row[0]
album = row[1]
albumimg = row[2]
addDir(album,arturl,7,albumimg)
db.close()
if(totalalbum==0):
(SongList,xmlpath)=GetSongs(url)
for albid,auth,alimg,alname,tracks in SongList:
addDir(TAG_RE.sub('', alname),url,7,xmlpath+alimg)
示例13: __init__
def __init__(self, addon_id, sys_argv=''):
#Check if a path has been set in the addon settings
if common.db_path:
self.path = xbmc.translatePath(common.db_path)
else:
self.path = xbmc.translatePath(common.default_path)
self.addon_id = addon_id
self.sys_argv = sys_argv
self.cache_path = common.make_dir(self.path, '')
self.addon = Addon(self.addon_id, self.sys_argv)
self.db = os.path.join(self.cache_path, self.local_db_name)
# connect to db at class init and use it globally
if DB == 'mysql':
class MySQLCursorDict(database.cursor.MySQLCursor):
def _row_to_python(self, rowdata, desc=None):
row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
if row:
return dict(zip(self.column_names, row))
return None
self.dbcon = database.connect(common.db_name, common.db_user, common.db_pass, common.db_address, buffered=True, charset='utf8')
self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True)
else:
self.dbcon = database.connect(self.db)
self.dbcon.row_factory = database.Row # return results indexed by field names and not numbers so we can convert to dict
self.dbcon.text_factory = str
self.dbcur = self.dbcon.cursor()
self._create_favorites_tables()
示例14: onPlayBackStopped
def onPlayBackStopped(self):
xbmc.log('1Channel: Playback Stopped')
if self.tracking:
playedTime = int(self._lastPos)
watched_values = [.7, .8, .9]
min_watched_percent = watched_values[int(ADDON.getSetting('watched-percent'))]
percent = int((playedTime / self._totalTime) * 100)
pTime = format_time(playedTime)
tTime = format_time(self._totalTime)
xbmc.log('1Channel: Service: %s played of %s total = %s%%' % (pTime, tTime, percent))
if playedTime == 0 and self._totalTime == 999999:
raise RuntimeError('XBMC silently failed to start playback')
elif ((playedTime / self._totalTime) > min_watched_percent) and (
self.video_type == 'movie' or (self.season and self.episode)):
xbmc.log('1Channel: Service: Threshold met. Marking item as watched')
if self.video_type == 'movie':
videotype = 'movie'
else:
videotype = 'episode'
ChangeWatched(self.imdb, videotype, self.title, self.season, self.episode, self.year, watched=7)
if self.librarymode:
dbidnum = xbmc.getInfoLabel('ListItem.DBID')
if dbidnum != 0:
if self.video_type == 'movie':
jsonquery = '{"jsonrpc": "2.0", "method": "VideoLibrary.SetMovieDetails", "params": {"movieid" : %s, "playcount" : 1 }, "id": 1 }'
else:
jsonquery = '{"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid" : %s, "playcount" : 1 }, "id": 1 }'
jsonquery = jsonquery % dbidnum
xbmc.log('1Channel: Service: Updating Library. Json query is %s' % jsonquery)
xbmc.executeJSONRPC(jsonquery)
sql = 'DELETE FROM bookmarks WHERE video_type=? AND title=? AND season=? AND episode=? AND year=?'
if DB == 'mysql':
sql = sql.replace('?', '%s')
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
else:
db = database.connect(db_dir)
cur = db.cursor()
cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season, self.episode, self.year))
db.commit()
db.close()
else:
xbmc.log('1Channel: Service: Threshold not met. Saving bookmark')
sql = 'REPLACE INTO bookmarks (video_type, title, season, episode, year, bookmark) VALUES(?,?,?,?,?,?)'
if DB == 'mysql':
sql = sql.replace('?', '%s')
db = database.connect(DB_NAME, DB_USER, DB_PASS, DB_ADDRESS, buffered=True)
else:
sql = 'INSERT or ' + sql
db = database.connect(db_dir)
cur = db.cursor()
cur.execute(sql, (self.video_type, unicode(self.title, 'utf-8'), self.season,
self.episode, self.year, playedTime))
db.commit()
db.close()
self.reset()
示例15: __init__
def __init__(self):
try:
self.dbConnection = mysql.connect(host='localhost',user='root',db='dewi_experiments',buffered=True)
except mysql.Error, e:
self.dbConnection = mysql.connect(host='localhost',user='root',buffered=True)
cursor = self.dbConnection.cursor()
cursor.execute("CREATE DATABASE dewi_experiments DEFAULT CHARACTER SET 'utf8'")
self.dbConnection.database = 'dewi_experiments'