Python3操作MySQL数据库
前提:
- python3
- pymysql库
若未安装,命令行执行pip install pymysql
安装
基本步骤
导包
import pymysql
打开数据库连接
db = pymysql.connect(host="数据库地址", user="用户名", password="密码", port=3306,# 端口 database="数据库名", charset='utf8')
创建游标
cursor = db.cursor()
操作数据库
sql="select * from student" # sql语句 try: cursor.execute(sql)# 提交 results =cursor.fetchall() # 获取数据 for row in results : studentno = row[0] sname= row[1] sex=row[2] birthdate=row[3] entrance=row[4] phone=row[5] Email=row[6] print("studentno={},sname={},sex={},birthdate={},\ entrance={},phone={},Email={}" .format(studentno,sname,sex,birthdate,entrance,phone,Email)) except: print("Error: unable to fecth data")
关闭游标,数据库连接
cursor.close() db.close()
本文作者:kingwzun
本文链接:https://www.cnblogs.com/kingwz/p/16193255.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步