本文整理汇总了Python中DB.connect方法的典型用法代码示例。如果您正苦于以下问题:Python DB.connect方法的具体用法?Python DB.connect怎么用?Python DB.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DB
的用法示例。
在下文中一共展示了DB.connect方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clickConnectButton
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
def clickConnectButton(self):
self.setup["host"]=self.host_le.text()
self.setup["database"]=self.database_le.text()
self.setup["user"]=self.user_le.text()
self.setup["password"]=self.password_le.text()
try:
conn=DB.connect(self.setup)
answer=messageDialog(title="Подключение завершено",\
text="Подключение завершено. Сохранить настройки?",\
yes="Да", no="Нет")
if answer==1:
b=True
while b:
if ConfigFile.write("config.json",self.setup):
b=False
else:
answer=messageDialog(title="Ошибка",\
text="Не удалось записать файл настроек. Повторить?",\
yes="Да", no="Нет")
if answer in (-1, 0):
b=False
if self.main_win:
self.main_win.editConnection(conn)
self.main_win.editSetup(self.setup)
else:
self.main_win=MainWindow(conn,self.setup)
self.close()
self.main_win.show()
except DB.ConnectToDBError:
answer=0
if self.main_win:
answer=messageDialog(title="Неудачная попытка", text=\
"Не удалось подключится к базе данных. Продолжить?",\
yes="Да", no="Нет, повторить ещё раз",\
cancel="Выйти из программы")
if answer==1:
self.main_win.editSetup(self.setup)
self.close()
self.main_win.show()
elif answer==0:
exit(0)
else:
answer=messageDialog(title="Неудачная попытка", text=\
"Не удалось подключится к базе данных. Войти в программу без подключения?",\
yes="Да", no="Нет, повторить ещё раз")
if answer in (0, 1):
self.main_win=MainWindow(setup=self.setup)
self.close()
self.main_win.show()
示例2: main
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
def main():
do_json = False
is_cgi = False
if 'GATEWAY_INTERFACE' in os.environ:
import cgi
#import cgitb; cgitb.enable()
form = cgi.FieldStorage()
is_cgi = True
if form.has_key('json'):
import json
do_json = True
print "Content-Type: application/json"
print
else:
do_json = False
print "Content-Type: text/html"
print
print "<html><head><title>Usage Report</title></head><body>"
#dumpenv(form)
db = DB.connect()
cursor = db.cursor()
do_team = ''
sql_team = ''
do_g = False
do_r = False
do_o = False
do_bat = True
do_pit = True
if is_cgi:
if form.has_key('team'):
do_team = form.getfirst('team').upper()
if form.has_key('batters'):
do_pit = False
if form.has_key('pitchers'):
do_bat = False
else:
for (opt, arg) in opts:
if opt == '-t':
do_team = arg.upper()
elif opt == '-A':
sql_team = " and ibl_team != 'FA'"
elif opt == '-B':
do_pit = False
elif opt == '-P':
do_bat = False
elif opt == '-g':
do_g = True
elif opt == '-r':
do_r = True
elif opt == '-o':
do_o = True
if len( do_team ) > 0 and len( sql_team ) == 0:
sql_team = " and ibl_team = '%s'" % do_team
mlb_usage( MLB_P, MLB_B )
bfp_file = cardpath() + '/' + 'bfp.txt'
if not os.path.isfile(bfp_file):
print bfp_file + " not found"
sys.exit(1)
with open( bfp_file, 'rU' ) as s:
for line in csv.reader(s):
sp = line[1].strip()
if sp.isdigit():
sp = float( sp )
else:
sp = float( 0 )
rp = line[2].strip()
if rp.isdigit():
rp = float( rp )
else:
rp = float( 0 )
rest = []
for x in line[3].split('/'):
val = x.strip()
if val.isdigit():
rest.append( float(val) )
else:
rest.append( float(0) )
BFP[line[0].rstrip()] = (sp, rp, rest )
injreport.main( INJ, module=True )
sql = "select mlb, name, sum(vl + vr)\
from %s group by mlb, name order by mlb, name;" % DB.usage
cursor.execute(sql)
for mlb, name, u in cursor.fetchall():
tig_name = mlb.rstrip() + " " + name.rstrip()
IBL_B[tig_name] = float(u)
sql = "select mlb, name, sum(bf)\
from %s group by mlb, name order by mlb, name;" % DB.usage
cursor.execute(sql)
for mlb, name, u in cursor.fetchall():
tig_name = mlb.rstrip() + " " + name.rstrip()
#.........这里部分代码省略.........
示例3: main
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
def main():
do_json = False
is_cgi = False
if 'GATEWAY_INTERFACE' in os.environ:
import cgi
#import cgitb; cgitb.enable()
form = cgi.FieldStorage()
is_cgi = True
if form.has_key('json'):
import json
do_json = True
print "Content-Type: application/json"
print
else:
do_json = False
print "Content-Type: text/html"
print
print "<html><head><title>Free Agent signing order</title></head><body>"
#dumpenv(form)
db = DB.connect()
cursor = db.cursor()
boxes = 0
results = 1
def late(team):
# array is (boxes, results)
# teams on probation pick last
if team in y['probation']:
return 2
# teams under caretaker control are exempt from late penalty
if team in y['exempt']:
return 0
# results or boxes must be current
if status[team][results] < week and status[team][boxes] < week:
return 1
# boxes must be no more than 1 week behind
if week > 1:
if status[team][boxes] < week - 1:
return 1
# return 0, team has nothing outstanding
return 0
week = 1
check_late = True
if is_cgi and form.has_key('week'):
week = int(form.getfirst('week'))
else:
for ( opt, arg ) in opts:
if opt == '-w':
week = int(arg)
elif opt == '-r':
check_late = False
# user inputs FA signing week (not results week), so subtract 1
week -= 1
if week == 0:
# find latest week with reported results
cursor.execute("select week, count(*) from games\
group by week order by week desc;");
# need to have more than 2 series reported to set week
for week, num in cursor.fetchall():
if num > 8:
break
# start with last year
# lastyear should be ordered to break ties
fa = []
lastyear = {}
try:
f = open( DB.bin_dir() + '/data/fa.yml', 'rU' )
except IOError, err:
print str(err)
sys.exit(1)
示例4: p_total
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
# pitcher array: bf, h, ob, tb, df, woba
def p_total( team, mlb, name ):
if (mlb, name) in p_cards:
vl = vsL(p_cards[mlb, name], pit)
vr = vsR(p_cards[mlb, name], pit)
#print mlb, name, bf, vl
#print mlb, name, bf, vr
ibl[team]['vL'][0] += bf
ibl[team]['vR'][0] += bf
for d in 1, 2, 3, 4:
ibl[team]['vL'][d] += vl[d - 1] * bf
ibl[team]['vR'][d] += vr[d - 1] * bf
ibl[team]['vL'][5] += wOBA(p_cards[mlb, name], pit, left) * bf
ibl[team]['vR'][5] += wOBA(p_cards[mlb, name], pit, right) * bf
db = DB.connect()
cursor = db.cursor()
# globals
ibl = {}
tot = {}
MLB_B = {}
MLB_P = {}
do_bat = True
do_pit = True
do_tot = False
do_opp = False
do_weekly = False
do_mlb = False
overall = 1
platoon = 2
示例5: main
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
def main( starts = {}, module = False, report_week = 27 ):
do_json = False
is_cgi = False
if not module and 'GATEWAY_INTERFACE' in os.environ:
import cgi
#import cgitb; cgitb.enable()
form = cgi.FieldStorage()
is_cgi = True
if form.has_key('json'):
import json
do_json = True
print "Content-Type: application/json"
print
else:
do_json = False
print "Content-Type: text/csv"
print
#dumpenv(form)
db = DB.connect()
cursor = db.cursor()
do_active = 0
team = ''
if is_cgi:
if form.has_key('week'):
report_week = int(form.getfirst('week'))
elif not module:
for (opt, arg) in opts:
if opt == '-i':
report_week = 0
if opt == '-a':
do_active = 1
elif opt == '-t':
team = arg
elif opt == '-w':
report_week = arg
elif opt == '-y':
DB.starts = 'starts' + arg
DB.inj = 'inj' + arg
sql = "select mlb, trim(name), sum(g), sum(p), sum(c), sum(\"1b\"), \
sum(\"2b\"), sum(\"3b\"), sum(ss), sum(lf), sum(cf), sum(rf) \
from %s where week is null or week <= %i \
group by mlb, name order by mlb asc, name asc;" \
% ( DB.starts, int(report_week) )
inj = {}
injreport.main( inj, module=True )
cursor.execute(sql)
for line in cursor.fetchall():
tig_name = line[0].rstrip() + " " + line[1].rstrip()
starts[tig_name] = line[2:]
if not module:
if len( team ) > 0:
if not is_cgi:
for spc in range(0, do_active):
sys.stdout.write(' ')
print "MLB Name GP SP C 1B 2B 3B SS LF CF RF INJ"
sql = "select tig_name, status from rosters where ibl_team = '%s' \
and item_type > 0 order by item_type, tig_name;" \
% team.upper()
cursor.execute(sql)
for tig_name, status in cursor.fetchall():
tig_name = tig_name.rstrip()
if inj.has_key(tig_name):
days = int(injreport.injdays( inj[tig_name], report_week ))
else:
days = 0
if starts.has_key(tig_name):
if do_active:
if status == 1:
sys.stdout.write(' ')
else:
sys.stdout.write('*')
print output( tig_name, starts[tig_name], days, is_cgi )
else:
if not is_cgi:
print "MLB Name GP SP C 1B 2B 3B SS LF CF RF INJ"
for tig_name in sorted(starts):
if inj.has_key(tig_name):
days = int(injreport.injdays( inj[tig_name], report_week ))
else:
days = 0
print output( tig_name, starts[tig_name], days, is_cgi )
db.close()
示例6: exit
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
answer=GUI.messageDialog(title="Ошибка",\
text="Конфигурационный файл повреждён. Настроить заново?",\
yes="Да", no="Нет, продолжить без настройки",\
cancel="Нет, выйти")
if answer==-1:
win=GUI.MainWindow()
win.show()
elif answer==0:
exit(0)
else:
win=GUI.SetupDatabaseWindow()
win.show()
else:
conn=None # Объект соединения с БД
try:
conn=DB.connect(configs)
except DB.ConnectToDBError:
answer=GUI.messageDialog(title="Ошибка",\
text="Не удаётся произвести подключение к базе данных. Изменить настройки?",\
yes="Да", no="Нет, продолжить без подключения",\
cancel="Нет, выйти")
if answer==-1:
win=GUI.MainWindow()
win.show()
elif answer==0:
exit(0)
else:
win=GUI.SetupDatabaseWindow()
win.show()
else:
win=GUI.MainWindow(conn,configs)
示例7: main
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
def main():
do_json = False
do_header = True
is_cgi = False
if 'GATEWAY_INTERFACE' in os.environ:
import cgi
#import cgitb; cgitb.enable()
form = cgi.FieldStorage()
is_cgi = True
if form.has_key('noheader'):
do_header = False
if form.has_key('json'):
import json
do_json = True
print "Content-Type: application/json"
print
else:
do_json = False
print "Content-Type: text/html"
print
if do_header:
print "<html><head><title>Legal Roster check</title></head><body>"
#dumpenv(form)
db = DB.connect()
cursor = db.cursor()
week = 1
if len(sys.argv) > 1:
week = int(sys.argv[1])
elif is_cgi and form.has_key('week'):
week = int(form.getfirst('week'))
else:
# no user input so we'll find latest week with reported results
cursor.execute("select week, count(*) from games\
group by week order by week desc limit 1;");
if cursor.rowcount > 0:
(week, num) = cursor.fetchone()
# and use first week afterward
week += 1
starts = {}
startsdb.main( starts, module=True )
inj = {}
IR.main( inj, module=True )
# teams/status
active = 1
inactive = 2
uncarded = 3
def ok( week ):
for series in week.keys():
out = map( lambda z: z & (IR.off + IR.inj + IR.sus), week[series] )
if not filter( lambda y: y == 0, out ):
return False
return True
sql_count = "select status, count(*) from rosters \
where ibl_team = (%s) and item_type != 0 \
group by status;"
sql_ros = "select trim(tig_name) from rosters \
where ibl_team = (%s) and item_type != 0 and status = 1;"
if not do_json:
if is_cgi:
print "<pre>"
print "WEEK %-2s # 1 2 3 4 5 6 7 8 9" % week
cursor.execute("select distinct(ibl_team) from rosters \
where ibl_team != 'FA' order by ibl_team;")
for (ibl, ) in cursor.fetchall():
ros = {}
cursor.execute( sql_count, (ibl, ) )
for status, count in cursor.fetchall():
ros[status] = count
legal = []
for pos in range(10):
legal.append(0)
cursor.execute( sql_ros, (ibl, ) )
for player, in cursor.fetchall():
#print player, starts[player]
# check if player has appearances left
if starts[player][0] <= 0:
continue
# check if player is out for a series
if inj.has_key(player):
if inj[player].has_key(week):
if not ok( inj[player][week] ):
#print "inj: %s" % player
continue
for pos in range(10):
if starts[player][pos] > 0:
#.........这里部分代码省略.........
示例8: main
# 需要导入模块: import DB [as 别名]
# 或者: from DB import connect [as 别名]
def main( player = {}, module = False, report_week = 0 ):
do_json = False
is_cgi = False
if not module and 'GATEWAY_INTERFACE' in os.environ:
import cgi
#import cgitb; cgitb.enable()
form = cgi.FieldStorage()
is_cgi = True
if form.has_key('json'):
import json
do_json = True
print "Content-Type: application/json"
print
else:
do_json = False
print "Content-Type: text/html"
print
if not form.has_key('notitle'):
print "<html><head><title>IBL Injury Report</title></head><body>"
#dumpenv(form)
db = DB.connect()
cursor = db.cursor()
# unset for actives only
do_all = 1
if is_cgi:
if form.has_key('week'):
report_week = int(form.getfirst('week'))
if form.has_key('active'):
do_all = 0
elif not module:
for (opt, arg) in opts:
if opt == '-a':
do_all = 0;
elif opt == '-w':
report_week = int(arg)
else:
print "bad option:", opt
usage()
if report_week == 0:
# no user supplied week, use latest week without all inj reported
sql = "select week, count(*) from %s where inj = 1\
group by week order by week desc;" % DB.sched
cursor.execute(sql)
for week, num in cursor.fetchall():
if num == 24:
report_week = week + 1
break
if is_cgi and not module:
print "<table>"
sql = "select week, home, away, day, type, ibl, ibl_team, status, \
i.tig_name, length, dtd, description from %s i \
left outer join rosters t on i.tig_name = t.tig_name\
order by ibl_team, i.tig_name, week;" % DB.inj
cursor.execute(sql)
for injury in cursor.fetchall():
week, home, away, day, code, inj_team, ibl, active, \
name, length, failed, desc = injury
##print injury
name = name.rstrip()
if active != 1:
active = 0
if not player.has_key(name):
player[name] = {}
if week == 28:
loc_q = [ 'playoffs' ]
elif inj_team == home:
loc_q = [ 'home', 'away' ]
else:
loc_q = [ 'away', 'home' ]
reported_day = day
reported_week = week
reported_loc = loc_q[0]
reported_length = length
# add 1 for dtd
if code == injured:
length += 1
served = 0
loc = loc_q[0]
series = get_series( player, name, week, loc )
# when day > series length inj time assessed next series
if day <= len(series):
served = update( series, code, length, day )
length -= served
player[name][week][loc] = series
##print "week %2i %s: %i served (%3i) %s" % \
## (week, loc, served, length, dcode(player[name][week][loc]))
if length > 0 and allstar( week ) and code != suspended:
# dtd expires during ASB
#.........这里部分代码省略.........