首页 > 代码库 > MySQL常用SQL语句(Python实现学生、课程、选课表增删改查)
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。