ITeye博客

Python对MySQL的访问

chensx · 2011-12-07 18:44 · Python · MySQL · 编程语言 · MySQL · Python · Markdown


# 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模块。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。