Python 3.4 連結mysql5.7 資料庫使用方法

來源:互聯網
上載者:User

標籤:

最近筆者在研究Python3.4連結MySQL5.7版本,筆者意圖在網上找到一個比較好的連結方式,網上介紹的大致有 mysqldb或者pymssql這兩種方法來連結,mysqldbhttp://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.connectorfrom mysql.connector import errorcodetry: 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.connectorconfig = { ‘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的道路越來越順暢,千裡之行,始於足下。

Python 3.4 連結mysql5.7 資料庫使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.