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.代码

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

这是最基本的一个小例子

原文地址:https://www.cnblogs.com/baipeng/p/6823006.html