python链接mysql

时间:2023-03-09 19:39:03
python链接mysql

1.安装MySQLdb

MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。

下载地址:

http://sourceforge.net/projects/mysql-python/files/mysql-python/

我下载了1.2.3版本

2.代码

 #!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='xxx', charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "mysql版本%s" %data
# 关闭数据库连接
db.close()

这是最基本的一个小例子