python 标准数据库接口为 python db-api,python db-api为开发人员提供了数据库应用编程接口。
python db-api使用流程:
引入 api 模块
获取与数据库的连接
执行sql语句和存储过程
关闭数据库连接
什么是mysqldb?
mysqldb 是用于python链接mysql数据库的接口,它实现了 python 数据库 api 规范 v2.0,基于 mysql c api 上建立的。
如何安装mysqldb?
为了用db-api编写mysql脚本,必须确保已经安装了mysql。复制以下代码,并执行:
#!/usr/bin/python# -*- coding: utf-8 -*-import mysqldb
如果执行后的输出结果如下所示,意味着你没有安装 mysqldb 模块:
traceback (most recent call last): file "test.py", line 3, in <module> import mysqldbimporterror: no module named mysqldb
数据库连接
连接数据库前,请先确认以下事项:
您已经创建了数据库 testdb.
在testdb数据库中您已经创建了表 employee
employee表字段为 first_name, last_name, age, sex 和 income。
连接数据库testdb使用的用户名为 "testuser" ,密码为 "test123",可以自己设定或者直接使用root用户名及其密码,mysql数据库用户授权请使用grant命令。
在你的机子上已经安装了 python mysqldb 模块。
实例:
以下实例链接mysql的testdb数据库:
#!/usr/bin/python# -*- coding: utf-8 -*-import mysqldb# 打开数据库连接db = mysqldb.connect("localhost", "testuser", "test123", "testdb", charset='utf8' )# 使用cursor()方法获取操作游标 cursor = db.cursor()# 使用execute方法执行sql语句cursor.execute("select version()")# 使用 fetchone() 方法获取一条数据data = cursor.fetchone()print "database version : %s " % data# 关闭数据库连接db.close()
执行以上代码
database version : 5.0.45
以上就是python如何连接数据库的详细内容。