前提条件:mysql中创建了一个名为scuecdb的数据库 其中创建了表 student(详细字段见上一篇文章)
这里以添加和查询语句为例,删除和更新只需要更改sql语句即可
一、面向对象的思想
1.mysql+pycharm(python) 实现增加功能
import pymysql
#链接数据库conn
conn = pymysql.connect("localhost","root","2611","scuecDB")
#操作数据库的游标
cur = conn.cursor()
#执行CRUD(此处是添加)
saveSQL ="insert into student(sid,sname,sage,score,sheight)values(100,'小青龙',22,99,1.56)"
#执行SQL语句并返回对数据库成功的条数(>0表示成功) 这里只是执行了并未从内存拿带硬盘 所以查询数据库并为添加到其中
count = cur.execute(saveSQL)
print("数据库执行成功的条数为%d"%count)
#事务提交
conn.commit()
#关闭
conn.close()
2.mysql+pycharm 实现查询功能
import pymysql
#链接数据库conn
conn = pymysql.connect("localhost","root","2611","scuecDB")
#操作数据库的游标
cur =conn.cursor()
#执行CRUD(此处是查询)
#selSQL2 = "select sname from student where sid=101"
#selSQL3 = "select * from student where sid = 101"
selSQL = "select*from student"
#查询成功了几条,可以不用接收返回成功的count数
count = cur.execute(selSQL)
#从查询结果中选取几条,取出全部
#students =cur.fetchchone() cur.fetchone() cur.fetchmany(3)
students = cur.fetchall()
#print(students)
for student in students:
print("学号:%d"%student[0])
print("姓名:%s"%student[1])
print("年龄:%d"%student[2])
print("成绩:%f"%student[3])
print("身高:%f"%student[4])
conn.close()
3.mysql+pycharm 实现修改功能
import pymysql
def main():
#1.连接mysql数据库
conn = pymysql.connect("localhost","root","2611","scuecDB")
#2.操作游标
cur = conn.cursor()
#提取用户要修改输入的信息
sid = int (input("请输入要修改的学生学号..."))
sname = input("请输入修改后的学生姓名...")
sage =int(input("请输入修改后的学生年龄..."))
score =int(input("请输入修改后的学生成绩..."))
sheight = float(input("请输入修改后的学生身高..."))
#3.sql语句
updateSQL = "update student set sname='"+sname+"',sage="+str(sage)+",score="+str(score)+",sheight="+str(sheight)+"where sid ="+str(sid)
#4.预编译执行sql
cur.execute(updateSQL)
#5.事务提交
conn.commit()
#6.关闭
conn.close()
if __name__ == '__main__':
main()
4.mysql+pycharm 实现删除功能
import pymysql
def main():
#1.连接
conn = pymysql.connect("localhost","root","2611","scuecDB")
#2.游标
cur = conn.cursor()
#提取要用户要删除的信息的sid
sid = int(input("请输入你要删除的学生信息对应的学号..."))
#3.sql语句
delSQL = "delete from student where sid ="+str(sid)
#4.# 预编译
cur.execute(delSQL)
#5.事务提交
conn.commit()
#6.关闭
conn.close()
if __name__ == '__main__':
main()