一、安裝
安裝已編譯版本(此方法簡便快捷):
http://www.codegood.com/downloads
根據自己系統下載,雙擊安裝,搞定
然後import MySQLdb,查看是否成功
我的,win7,32位,2.7版本
MySQL-python-1.2.3.win-amd32-py2.7.exe
二、使用
#!/usr/bin/python
# encoding: utf-8
import time,MySQLdb
# 打開數據庫連接
db = MySQLdb.connect("localhost","root","root","Python" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
#刪除表
sql = "drop table if exists thinkgamer"
cursor.execute(sql)
#創建
sql = "create table if not exists thinkgamer(name varchar(128) primary key,created int(10))"
cursor.execute(sql)
#寫入
sql = "insert into thinkgamer(name,created) values(%s,%s)"
param = ("aaa",int(time.time()))
n = cursor.execute(sql,param)
print 'insert',n
#寫入多行
sql = "insert into thinkgamer(name,created) values(%s,%s)"
param = (("bbb",int(time.time())),("ccc",33),("ddd",44))
n = cursor.executemany(sql,param)
print "insertmany",n
#更新
sql= "update thinkgamer set name=%s where name='aaa'"
param = ("zzz")
n = cursor.execute(sql,param)
print "updata",n
#查詢
n = cursor.execute("select * from thinkgamer")
for row in cursor.fetchall():
print row
for r in row:
print r
#刪除
sql = "delete from thinkgamer where name =%s"
param = ("bbb")
n = cursor.execute(sql,param)
print "delete",n
#查詢
n = cursor.execute("select * from thinkgamer")
print cursor.fetchall()
cursor.close()
#提交
db.commit()
#關閉
db.close()
輸出結果:
insert 1
insertmany 3
updata 1
('zzz', 1436067892L)
zzz
1436067892
('bbb', 1436067892L)
bbb
1436067892
('ccc', 33L)
ccc
33
('ddd', 44L)
ddd
44
delete 1
(('zzz', 1436067892L), ('ccc', 33L), ('ddd', 44L))