1、下載MySQL官方的mysql-connector-python-8.0.17-py3.7-windows-x86-64bit.msi,直接點擊安裝;
2、安裝完畢后直接可以導入mysql.connnector模塊
連接方式一:
import mysql.connector cnx = mysql.connector.connect(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()
連接方式二:
from mysql.connector import (connection) cnx = connection.MySQLConnection(user='scott', password='password', host='127.0.0.1', database='employees') cnx.close()
用try~except獲取錯誤代碼:
import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(user='scott', database='employ')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
3、獲取數據庫數據:
import mysql.connector myconn=mysql.connector.connect(host="localhost",user="lucy",passwd="123455",database="holiday") mycursor=myconn.cursor() my_cmd_sql="select * from birthday" a=mycursor.execute(my_cmd_sql) #執行SQL命令 for a in mycursor: #展示請求數據 print(a) mycursor.close() #指針必須關閉 myconn.close() #連接必須關閉
4、插入、更改和刪除數據
跟上面一樣的方法執行插入、更改和數據命令,這里有一點區別,execute語句后必須調用連接的.commit()方法確認執行。
另外:指針一定要關閉,否則容易引起
mysql 2014 error (2014) Commands out of sync; You can't run this command now
總結
以上所述是小編給大家介紹的python3連接MySQL8.0的兩種方式,希望對大家有所幫助,也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。