安装已编译版本(此方法简便快捷): http://www.codegood.com/downloads

根据自己系统下载,双击安装,搞定,然后import MySQLdb,查看是否成功

安装

我的,win7,32位,2.7版本

MySQL-python-1.2.3.win-amd32-py2.7.exe

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/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))

更多详情请戳:MySQLdb User’s Guide



打开微信扫一扫,关注公众号【搜索与推荐Wiki】