python處理mysql的的方案匯總

來源:互聯網
上載者:User

多環境下折騰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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.