Python 3.4 鏈接mysql5.7 數據庫使用方法


最近筆者在研究Python3.4鏈接MySQL5.7版本,筆者意圖在網上找到一個比較好的鏈接方式,網上介紹的大致有 mysqldb或者pymssql這兩種方法來鏈接,mysqldb下載地址http://download.csdn.net/detail/txw1958/5818181 下載安裝后即可在Python3.2鏈接數據庫,http://mysql-python.sourceforge.net/MySQLdb.html關 於MySQLdb的介紹和API的。  pymssql的https://pypi.python.org/pypi/pymssql/2.1.0下載地址,使用詳情http: //pymssql.org/en/latest/pymssql_examples.html。但是這都是依賴於第三方的庫,筆者昨天費勁功夫在mysql的 官網找到了一篇就可以直接操作的方式;http://dev.mysql.com/doc/connector-python/en /connector-python-example-connecting.html 這是地址,雖然是英文,但是網站給了詳細的說明,大家可以不依賴於第三方庫,對於新手來說安裝第三方庫會出現很多這樣那樣的問題。

import mysql.connector  #導入需要的模塊

cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')
cnx.close()
這就是一個很簡單的鏈接方式。
import mysql.connector from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='scott', database='testt') 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() #加入了容錯機制,這在實際編程運用很大。
import mysql.connector config = { 'user': 'scott', 'password': 'tiger', 'host': '127.0.0.1', 'database': 'employees', 'raise_on_warnings': True, } cnx = mysql.connector.connect(**config) cnx.close() #這種方式的鏈接讓代碼更加簡潔。
最后筆者想告訴大家,在你利用的時候一定要先看官方有沒有給出新的方法,Python
的在改變,mysql也在改變,但是我相信在這些產品迭代的周期肯定會考慮用戶的角度去改善。
最后筆者祝願大家學習Python的道路越來越順暢,千里之行,始於足下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM