Python串連Mysql資料庫(Debian)

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

Python串連Mysql資料庫(Debian)

以下是Python 2.*版本的安裝方法,MySQL-python暫不支援Python 3.*版本

提前要做的工作:
  1. 安裝setuptools,在終端中運行

    wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
  2. 安裝pip,下載“get_pip.py”,運行

    python get_pip.py
  3. 運行如下命令裝好必要的包

    sudo apt-get install python-dev libmysqld-dev libmysqlclient-dev
正式安裝:
  1. 安裝MySQL(有些系統內建):

    sudo apt-get install mysql-server
  2. 下載MySQL-python並解壓,進入解壓出的檔案夾下,依次運行命令

    python setup.py build python setup.py install
  • 注意:如果運行上述命令時報錯 “EnvironmentError: mysql_config not found” ,重新運行以下命令檢查是否已安裝“libmysqld-dev”
    sudo apt-get install libmysqld-dev
使用

代碼執行個體(來自w3cschool),串連MySQL的TESTDB資料庫,輸出MySQL的版本號碼:

# encoding: utf-8#!/usr/bin/pythonimport MySQLdb# 開啟資料庫連接db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# 使用cursor()方法擷取操作遊標 cursor = db.cursor()# 使用execute方法執行SQL語句cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法擷取一條資料庫。data = cursor.fetchone()print "Database version : %s " % data# 關閉資料庫連接db.close()
?

Python串連Mysql資料庫(Debian)

聯繫我們

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