Python操作MySQL数据库


首先需要先有Python的MySQL连接模块MySQLdb
在CentOS 5.4下已经默认安装上了,Ubuntu下面没有,需要自己手动安装,下载地址如下:

下载地址:http://sourceforge.net/projects/mysql-python/

一个能覆盖80%使用场景的例子:

import MySQLdb

# 建立一个连结
con = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="123456", db="test")
# 生成一个cursor,   用来执行sql语句
cursor = con.cursor()

# 执行sql语句
sql = "SELECT * FROM Users"
cursor.execute(sql)

# Fetch all results from the cursor into a sequence and close the connection
# 取得返回的值并关闭连接
results = cursor.fetchall()

相关内容