pymysql
跳转到导航
跳转到搜索
上下文管理器
pymysql 的 Connection 支持上下文管理器,并且会返回一个 Cursor 对象。
代码片断
连接到 URL:
from urllib.parse import urlsplit, unquote
def mysql_connect(db_url):
u = urlsplit(db_url)
login, host = u.netloc.split('@')
if ':' in host:
host, port = host.split(':')
port = int(port)
else:
port = 3306
user, passwd = login.split(':')
passwd = unquote(passwd)
db = u.path.strip('/')
conn = pymysql.connect(
host=host, user=user, passwd=passwd, db=db, port=port)
return conn