用Python 串連mysql資料庫

來源:互聯網
上載者:User

標籤:oracle   資料庫   python   python 串連mysql資料庫   

你必須下載一個單獨的DB API的模組,你需要訪問的每個資料庫。例如,如果你需要訪問Oracle資料庫以及MySQL資料庫,你必須下載Oracle和MySQL資料庫模組.

DB API提供了與資料庫的工作,儘可能使用Python的結構和文法的最低標準。這個API包括以下:

  • 匯入API模組.

  • 擷取與資料庫的串連.

  • 發出SQL語句和預存程序.

  • 關閉串連

檢驗MySQLdb模組是否安裝成功:

#!/usr/bin/env python

import MySQLdb

如果它產生以下結果,那麼它意味著未安裝MySQLdb模組:

Traceback (most recent call last):  File "test.py", line 3, inimport MySQLdbImportError: No module named MySQLdb

下載MySQLdb模組,Linux環境下安裝命令

$ gunzip MySQL-python-1.2.2.tar.gz$ tar -xvf MySQL-python-1.2.2.tar$ cd MySQL-python-1.2.2$ python setup.py build$ python setup.py install

*注意root許可權安裝


資料庫連接:

串連到一個MySQL資料庫之前確保以下:

  • 你已經建立了一個資料庫TESTDB.

  • 你已經建立了一個EMPLOYEE表在TESTDB中.

  • EMPLOYEE表有以下幾個欄位: FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

  • “testuser的”使用者ID和密碼“test12”設定用來訪問TESTDB。

  • Python模組MySQLdb在你的機器上正確安裝.

  • 你已通過MySQL的教程



例1:串連TESTDB

#!/usr/bin/env pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("Llocalhost", "testuser", "test12", "TESTDB")#prepare a cursor object using cursor() methodcursor = db.cursor()# execute SQL query using execute() methodcursor.execute("SELECT VERSION()")#Fetch a single row using fetch() methoddata = cursor.fetchone()print "Database version:%s" % data#disconnect from serverdb.close()


而在我的Linux機器運行此指令碼,其產生的結果如下.

Database version : 5.0.45












本文出自 “趕不上的腳步” 部落格,請務必保留此出處http://xxmspace.blog.51cto.com/1056016/1754124

用Python 串連mysql資料庫

聯繫我們

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