文章内容
2019/3/4 17:17:04,作 者: 黄兵
MySQLdb连接数据库封装
最近在大量使用MySQLdb,有一些公共代码总结记录,方便以后其他项目使用。
在使用MySQLdb库的时候,首先是需要连接数据库,对连接数据库部分做一个封装,方便以后调用。
具体代码如下:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
class Conn_Config:
"""MySQL连接"""
def __init__(self):
# MySQL Config
self.mysql_host = 'database.xxx.com'
self.mysql_port = 3306
self.mysql_user = 'user'
self.mysql_password = 'password'
self.mysql_database = 'database'
self.charset = 'utf8'
def Conn_MySQL(self):
"""连接MySQL数据库"""
# 打开数据库连接
db = MySQLdb.connect(host=self.mysql_host, port=self.mysql_port, user=self.mysql_user,
passwd=self.mysql_password,
db=self.mysql_database, charset=self.charset)
return db
直接返回一个连接字符串,在其他地方调用即可。
评论列表