多環境下折騰python-mysql
這2天一直在折騰寫一個測試案例調度執行的指令碼,與mysql會有一定的互動。在Mac下面開發測試都OK,但是移植到伺服器上,發現有太多的問題。
在伺服器上Centos 5 上安裝MySQLdb碰到這種坑,折騰了一下午。當然,Mysqldb應該是python比較常見的外部lib,像django項目就是使用MySQLdb。
簡單總結下,MySQLdb是使用C模組來連結Mysql ,所有會需要有下面幾個先決條件:
c 編譯器
python 的開發庫及其標頭檔
mysql 的開發庫及其標頭檔
所有,相應成功裝上MySQLdb, 請先做如下的確認:
確認python的版本2.3 ~ 2.7 之間
確認安裝了 gcc
確認安裝了 mysql
確認安裝了 python-devel
如果是本地編譯安裝,還得先確認已經裝好了setuptools
總之:安裝過程中,碰到的問題,基本網上都能找得到解決方案,畢竟,這個模組的使用已經經過了多個版本的洗禮。算是很成熟的一個解決方案。
但是,我這裡並不推薦大家繼續使用它。我在解決上述問題的過程中,發現mysql官方已經推出了一個新的解決方案。MySQL Connector/Python
這貨最迷人的地方就是,它基本上支援了mysql server所包含的所有特性,對python 2/3都提供了支援。(注意,它對於mysql老的加密驗證是不支援的,所以 mysql 4.1 一下是不支援的)。還有就是它是官方推薦的,後續的維護肯定也是最及時的。
而且,從MySQLdb切換到Connector/python基本上算是無縫切換。常用的功能基本都沒有什麼變化
Connector/python example
具體的可以參考:http://dev.mysql.com/doc/connector-python/en/connector-python-examples.html
| 代碼如下 |
複製代碼 |
connect: import mysql.connector from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='scott', password='tiger', host='127.0.0.1', database='employees') 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() create table import mysql.connector from mysql.connector import errorcode cnx = mysql.connector.connect(user='scott') cursor = cnx.cursor() try: cursor.execute( "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME)) except mysql.connector.Error as err: print("Failed creating database: {}".format(err)) exit(1) query import mysql.connector conn = mysql.connector.connect(host=’127.0.0.1’, user='root', password='root', database='athena') cursor = conn.cursor(dictionary=True) try: cursor.execute(sql) rows = cursor.fetchall() finally: conn.close() |