Python 如何操作MYSQL数据库
安装MySQLdb
在Ubuntu环境中,输入命令:
sudo apt-get install python-setuptools
sudo apt-get install libmysqld-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo easy_install mysql-python
使用MySQLdb进行数据库操作
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
#打开数据库连接
conn = MySQLdb.connect(host="localhost", user="root", passwd='cityfmsd', db='NLPData', charset='utf8')
cursor = conn.cursor()
# 使用cursor()方法获取操作游标
cursor.execute("SELECT VERSION()")
# 使用fetchone()方法获取一条数据
data = cursor.fetchone()
# 使用fetchall()方法获取多条数据
data = cursor.fetchall()
# 关闭数据库
db.close()