HELLO WORLD|

kingwzun

园龄:3年6个月粉丝:111关注:0

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 中国大陆许可协议进行许可。

posted @   kingwzun  阅读(288)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起