python脚本连接mysql
程序员文章站
2022-07-14 10:33:45
...
文件db
文件dbconf.py
ln -s /Users/wanglin/script/db /usr/local/bin/db
即可 命令行 db dbname快速连接mysql
#!/usr/bin/python #coding=gbk from dbconf import dbconf from urlparse import urlparse import os, sys import re def warning(str): print '\033[1;31mWARNING: %s\033[0m' %str def info(str): print '\033[0;33m%s\033[0m' %str def parse(url): username = '' password = '' host = '' port = 3306 db = '' if url.startswith("mysql://"): url = url[8:] p = re.compile("[:@/]") arr = p.split(url) if len(arr) == 5: username = arr[0] password = arr[1] host = arr[2] port = arr[3] db = arr[4] if len(arr) == 7: username = arr[0] password = ''.join([arr[1], '@', arr[2], '@', arr[3]]) host = arr[4] port = arr[5] db = arr[6] return { 'user' : username, 'password' : password, 'host' : host, 'port' : port, 'db' : db, } def init(conf): map = {} desc = {} for i in conf: conn = parse(i['url']) for j in i['name']: if j in map: warning('duplicate key %s!' % j) map[j] = conn if 'desc' in i: desc[j] = '[%s]%s' %(conn['host'], i['desc']) return map, desc def initusermap(): fn = os.path.join(os.environ['HOME'], 'bin', 'userdbconf.py'); if os.path.exists(fn): sys.path.append(os.path.dirname(fn)) from userdbconf import dbconf for i in dbconf: dbconf[i] = parse(dbconf[i]) return dbconf return {} def usage(dbdesc): dbdesc = sorted(dbdesc.items(), key=lambda x : x[0]) info('dbconf列表:') for name, desc in dbdesc: info('%20s: %s' %(name,desc)) def main(): dbmap, dbdesc = init(dbconf) dbmap.update(initusermap()) if len(sys.argv) < 2: usage(dbdesc) return else: db = sys.argv[1] params = ' '.join(sys.argv[2:]) if not db in dbmap and db.endswith('.rw') and db[:-3] in dbmap: db = db[:-3] warning('use %s instead' % db) if db in dbmap: cmd = 'mysql -A -U -u%(user)s -p%(password)s -h%(host)s -P%(port)s %(db)s ' % dbmap[db] info(cmd) os.system(cmd + params) else: warning('%s not found' % db) if __name__ == '__main__': main()
文件dbconf.py
#!/usr/bin/python #coding=utf-8 dbconf = [ # mart_finance {'url': 'mysql://username:"password"@ip:port/dbname', 'name': ['dbname'], 'desc':'xxx数据库' }, ]
ln -s /Users/wanglin/script/db /usr/local/bin/db
即可 命令行 db dbname快速连接mysql
上一篇: 页面实战 推广