不多说了,直接贴代码,如果有人看的话,不明白的地方可以评论哦
#数据库操作程序:主要完成的功能包含,1、数据库表创建 2、数据库数据插入 3、数据库修改
#4、数据库数据删除 5、数据库查询,主要就是做增删改查
#
#
# -*- coding: utf-8 -*-
import MySQLdb
#实际执行数据库的操作
#1、连接数据库
#2、执行相关语句
#3、opetype是操作类型-----1、代表建表 2、代表插入 3、代表修改等
#4、有一个默认形参,主要是用来存放查询结果的。
conn = 0
def OperateDb( sql, opetype, results = [] ):
#连接数据库
if conn == 0:
db=MySQLdb.connect(host="localhost",
user="root",
passwd="root",
db="test",
charset="utf8")
conn == 1
#获取操作游标
cursor = db.cursor()
#执行语句
if opetype == 1 :
#创建表
cursor.execute( sql )
elif opetype == 2:
#插入语数据
cursor.execute( sql )
elif opetype == 3:
#修改数据
cursor.execute( sql )
elif opetype == 4:
#删除数据
cursor.execute( sql )
elif opetype == 5:
#查询数据
cursor.execute( sql )
result = cursor.fetchall()
x = list(result)
#print x
for row in x:
#print row
results.append(row)
#print results
db.commit()
if conn == 1:
db.close()
def create_table():
#该处可以继续优化下
#sql = "DROP TABLE IF EXISTS EMPLOYEEwxp"
#OperateDb( sql, 1 )
sql = """CREATE TABLE if not exists EMPLOYEEwxp (
name CHAR(20) NOT NULL primary key,
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
OperateDb( sql, 1 )
def insert_value():
try:
sql = """INSERT INTO EMPLOYEEwxp(name, AGE, SEX, INCOME)
VALUES ('Mac', 20, 'M', 2000)"""
OperateDb( sql, 2 )
sql = """INSERT INTO EMPLOYEEwxp(name, AGE, SEX, INCOME)
VALUES ('Mark', 21, 'F', 2001)"""
OperateDb( sql, 2 )
except MySQLdb.Error,e:
#print e
if e[0] == 1062:
print "haved"
def printlist( date ):
i = 0
#print len(date)
for row in date:
name1 = row[0]
age = row[1]
sex = row[2]
income = row[3]
# 打印结果
print "name=%s,age=%d,sex=%s,income=%d" % (name1,age, sex, income )
def select_ope():
sql = "SELECT * FROM EMPLOYEEwxp"
date = []
OperateDb( sql, 5, date )
if len( date ) != 0:
printlist( date )
else:
print "无数据"
def update_value():
sql = """update EMPLOYEEwxp set INCOME=3000 where name='mark'"""
OperateDb( sql, 3 )
def del_value():
sql="delete from EMPLOYEEwxp where name ='Mark'"
OperateDb( sql, 4 )
if __name__ == "__main__":
create_table()
#插入两条数据
insert_value()
print "first select"
#查询显示数据
select_ope()
print "first update"
update_value()
select_ope()
print "del"
del_value()
select_ope()
<pre name="code" class="html">运行结果:
first select
name=Mac,age=20,sex=M,income=2000
name=Mark,age=21,sex=F,income=2001
first update
name=Mac,age=20,sex=M,income=2000
name=Mark,age=21,sex=F,income=3000
del
name=Mac,age=20,sex=M,income=2000