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