Python3版本需导入库pymysql,(PyMySQL 是在 Python3.x 版本中用于链接 MySQL 服务器的一个库,Python2中的库为mysqldb)
现已安装MySQL,已有student数据库,并建立student表,如何将此表数据读取到python中?
链接步骤以下:python
对应代码:
建立新链接mysql
db = pymysql.connect('localhost','root','123456','student')
建立游标web
cursor = db.cursor()
调用execute()sql
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链接数据库,遵循以上四步走便可。svg