python通过connect对象连接数据库对吗_Python连接数据库
Python连接数据库的接口
MySQL:MySQLdb是用于Python连接MySQL数据库的接口,实现了python数据库API规范,基于MySQL C API上建立的
Oracle:cx_Oracle是用于Python连接Oracle数据库的接口
SQL Server:pymssql是用于Python连接SQL Server数据库的接口
Python连接MySQL数据库(MySQLdb)
安装mysqlclient模块,命令:pip install mysqlclient
导入mysqldb模块,如:import MySQLdb
通过MySQLdb创建连接对象,MySQLdb.connect(host,port,user,password,db,charset)
host:ip地址
port:端口
user:用户名
password:密码
db:数据库名
charset:字符编码
通过连接对象,获取游标对象,Connect.cursor()
通过游标对象执行sql语句(注意:如果执行更新语句,需要手动提交事务)
关闭游标对象,释放资源
关闭连接对象,释放资源
代码示例
import MySQLdb
import traceback
class DatabaseConfig:
""" 数据库配置信息类 """
host = "127.0.0.1"
port = 3306
user = "root"
password = "root"
db = "python_db"
charset = "UTF8"
def connect_mysql(db_config):
"""
连接MySQL数据库方法
:param db_config: 数据源配置信息
:return: None
"""
# 定义变量接收连接对象,游标对象
connect = None
cur = None
try:
connect = MySQLdb.connect(host=db_config.host, port=db_config.port, user=db_config.user,
password=db_config.password, db=db_config.db, charset=db_config.charset)
except:
print("数据库连接失败:" + traceback.format_exc())
else:
# 通过连接对象获取游标对象,执行sql语句,
cur = connect.cursor()
cur.execute("show databases")
fetchone = cur.fetchall()
print(fetchone)
# 注意:非查询语句要提交事务
# connect.commit()
finally:
# 关闭游标、连接对象,释放资源
cur.close()
connect.close()
if __name__ == "__main__":
connect_mysql(DatabaseConfig)
标签:Python,数据库,db,MySQLdb,connect,config,连接
来源: https://www.cnblogs.com/jason2018524/p/13062448.html