MySQL常用SQL语句(Python实现学生、课程、选课表增删改查)
以基本的学生选课为例,建立选课数据库,学生、班级、选课信息三张表,并分别对表进行插删改操作:
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参照,必须按顺序依次插入。
本文出自 “小鬼的地盘” 博客,请务必保留此出处http://zhoufwind.blog.51cto.com/1029821/1435026
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。