python 简单操作MySQL
2016-06-14 本文已影响176人
2010jing
前言
- python 配置 mysql
- 通过 python 爬取一些数据,存入数据库 并生成简单图表
环境
linux (Ubuntu)
安装
1-MySQL
$ sudo apt-get install mysql-server
2-MySQL-python
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
安装成功之后,终端进入python,然后测试

测试数据库
Create a database name ‘book’ in your mysql


Connect to MySQL

Create table user

Insert record into your table user

Output the record from your table user

Run the program

小例子
import sys
import MySQLdb
db = MySQLdb.connect(host='localhost',user='root',passwd='root',db='hello')
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
# print "Database version : %s " % data
#---------------------------------------------------
# sql = "create table if not exists test2(name varchar(128) primary key, age int(4))"
# cursor.execute(sql)
sql = "insert into test2(name, age) values ('%s', %d)" % ("ccc", 21)
try:
cursor.execute(sql)
except Exception, e:
print e
db.commit()
sql = "select * from test2"
cursor.execute(sql)
alldata = cursor.fetchall()
if alldata:
for rec in alldata:
print rec[0], rec[1]
db.close()