使用python操作mysql数据库

前言:以下内容主要介绍python使用pymysql 操作mysql的查询和插入 、使用的编译工具为pycharm (pymysql属于第三方库、需要我们自己安装)

参考链接:https://blog.csdn.net/qq_37176126/article/details/72824106

我要操作的数据库表(表名为student)如下、其中sno是自增:

    

一、查询该表的数据:

import pymysql   #导库

#
1-打开数据库连接 前提是自己本地的mysql服务是打开的 db=pymysql.connect(host="localhost",user="root",password="123456",db="yhrtest",port=3306) cursor=db.cursor() #2-使用cursor()方法获取操作游标 sql="select * from student" #3-添加查询语句 try: cursor.execute(sql) #4-执行sql语句 result=cursor.fetchall() #5-获取查询的结果 结果为元组类型 print("sno","sname","age","sdept") #先输出表头字段 for one in result: sno,sname,age,sdept=one print(sno,sname,age,sdept) except Exception as error: print("错误提示:",error) #打印错误信息 finally: db.close() #6-关闭连接

查询结果如下:

    

 二、插入一条数据:

import pymysql   #导库

#1-打开数据库连接  前提是自己本地的mysql服务是打开的
db=pymysql.connect(host="localhost",user="root",password="123456",db="yhrtest",port=3306)

cursor=db.cursor()  #2-新建游标

sql='insert into student(sname,age,sdept) values("测试","21","测试")'  #3-编写sql语句

try:
    cursor.execute(sql)  #4-执行sql语句
    db.commit()   #5-记得提交、否则不生效
except Exception as error:
    print(error)    #查看报错信息
    db.rollback()   #执行中如果报错则回滚
finally:
    db.close()   #6-关闭数据库

最终执行结果:

    

 总结:以上只写了查询和插入语句、因为修改以及删除语句的操作步骤跟插入的是类似的、直接替换sql语句就可以了。另外要注意的是增删改的时候、执行完sql语句后记得要commit否则语句可能会不生效、还有最后记得关闭数据库连接。

原文地址:https://www.cnblogs.com/yanghr/p/14713555.html