以基本的学生选课为例,建立选课数据库,学生、班级、选课信息三张表,并分别对表进行插删改操作:
import MySQLdb
try:
conn = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'root', db = 'xuanke', port = 3306)
cur = conn.cursor()
cur.execute("CREATE DATABASE xuanke")
cur.execute("CREATE TABLE Student (Sno VARCHAR(9) PRIMARY KEY, Sname VARCHAR(20) UNIQUE, Ssex VARCHAR(2), Sage SMALLINT, Sdept VARCHAR(20))")
cur.execute("CREATE TABLE Course (Cno VARCHAR(4) PRIMARY KEY, Cname VARCHAR(40), Cpno VARCHAR(4), Ccredit SMALLINT, FOREIGN KEY (Cpno) REFERENCES Course(Cno))")
cur.execute("CREATE TABLE SC (Sno VARCHAR(9), Cno VARCHAR(4), Grade SMALLINT, PRIMARY KEY (Sno, Cno), FOREIGN KEY (Sno) REFERENCES Student(Sno), FOREIGN KEY (Cno) REFERENCES Course(Cno))")
cur.execute("INSERT INTO Student VALUES ('200215121', 'Stephen Zhou', 'M', '20', 'CS')")
cur.execute("INSERT INTO Student VALUES ('200215122', 'Stan Qian', 'M', '23', 'CS')")
cur.execute("INSERT INTO Student VALUES ('200215123', 'Linda Fan', 'F', '21', 'MA')")
cur.execute("INSERT INTO Student VALUES ('200215125', 'Zac Gu', 'M', '26', 'IS')")
cur.execute("INSERT INTO Course VALUES ('2', 'Math', Null, '2')")
cur.execute("INSERT INTO Course VALUES ('6', 'Data Processing', Null, '2')")
cur.execute("INSERT INTO Course VALUES ('7', 'PASCAL', '6', '4')")
cur.execute("INSERT INTO Course VALUES ('5', 'Data Structure', '7', '4')")
cur.execute("INSERT INTO Course VALUES ('1', 'Database', '5', '4')")
cur.execute("INSERT INTO Course VALUES ('3', 'Information System', '1', '4')")
cur.execute("INSERT INTO Course VALUES ('4', 'Operating System', '6', '3')")
cur.execute("INSERT INTO SC VALUES('200215121', '1', '92')")
cur.execute("INSERT INTO SC VALUES('200215121', '2', '85')")
cur.execute("INSERT INTO SC VALUES('200215121', '3', '88')")
cur.execute("INSERT INTO SC VALUES('200215122', '2', '90')")
cur.execute("INSERT INTO SC VALUES('200215122', '3', '80')")
cur.execute("INSERT INTO Student VALUES('200215128', 'Cuan Qu', 'M', '22', 'IS')")
cur.execute("UPDATE Student SET Sage = '23' WHERE Sno = '200215128'")
cur.execute("UPDATE Student SET Sage = Sage + 7")
cur.execute("DELETE FROM Student WHERE Sno = '200215128'")
cur.close()
conn.commit()
conn.close()
except MySQLdb.Error, e:
print 'Mysql error msg: ', e
显示数据库:
显示所建表:
显示学生表:
显示课程表:
显示选课信息表:
注:以上python程序中插入操作需要一步步运行,特别是课程表中‘Cpno’为先选课程,其为课程表外键并与Course.Cno参照,必须按顺序依次插入。