Python对MySQL的访问


# filename : database.py
# description : MySQL and Python
# datetime : 2011.12.07

import os
import sys
import MySQLdb

# connect to database
try :
conn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='school')
except Exception, e :
print e
sys.exit()

# get cursor to operator database
cursor = conn.cursor()

# create table
sql = "create table if not exists student(_id char(5) primary key, name varchar(20), age smallint);"
cursor.execute(sql)

# remove all record
sql = "delete from student;"
cursor.execute(sql)

# insert record
sql = "insert into student values('%s','%s',%d);" % ('00001', 'aaaaa', 21)
cursor.execute(sql)

# insert many record
val = (('00002','bbbbb',22), ('00003','ccccc',23), ('00004','ddddd',24))
sql = "insert into student values(%s,%s,%s);"
cursor.executemany(sql, val)

# select record
sql = "select * from student;"
cursor.execute(sql)
alldata = cursor.fetchall()
if alldata :
for rec in alldata :
print rec[0], rec[1], rec[2]

# close database
cursor.close()
conn.close()

python访问mysql,必须安装如下的mysql-python模块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值