python3.x连接MySQL一般步骤

Python3版本需导入库pymysql,(PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中的库为mysqldb)
现已安装MySQL,已有student数据库,并创建student表,如何将此表数据读取到python中?
在这里插入图片描述
连接步骤如下:

在这里插入图片描述
对应代码:
创建新连接

db = pymysql.connect('localhost','root','123456','student')

创建游标

cursor = db.cursor()

调用execute()

cursor.execute('select * from  student')

关闭连接

db.close()

现在将以上代码实际应用起来

import pymysql
db = pymysql.connect('localhost','root','123456','student')
cursor = db.cursor()
cursor.execute('select * from  student')
result = cursor.fetchall()  #查询需要获得结果,所以要多出这句代码
db.close()
for row in result:
    print(row)

在这里插入图片描述
python连接数据库,遵循以上四步走即可。

发布了41 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43616178/article/details/89484519