python 3 mysql數據庫的連接

python2.x使用的是mysqldb庫

Python3  所使用的mysql連接庫是pymysql,打開cmd輸入

pip install pymysql

進行pymysql庫的安裝,

下面是進行mysql數據庫的連接代碼

import pymysql
 
# 打開數據庫連接
db = pymysql.connect(host='xxx.xxx.xxx.xxx', port=3306, user='xxxx', passwd='xx', db='xxxx', charset='utf8')

# 使用 cursor() 方法創建一個遊標對象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法執行 SQL 查詢 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# 關閉數據庫連接
db.close()

host爲數據庫IP地址 port=3306數據庫訪問端口 user,passwd爲用戶名與密碼

運行結果如圖


以上說明數據庫連接已成功,接下來就可以對數據庫具體操作了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章