MySQLdb的安装与使用

jopen 9年前

一、安装

安装已编译版本(此方法简便快捷):

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))


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