Python操作MySQL資料庫

來源:互聯網
上載者:User

標籤:使用者名稱   處理   exec   pytho   com   font   sel   l資料庫   val   

1. 安裝mysql-python

運行下面的命令:

pip intall mysql-python

安裝以後:

import MySQLdb

如果沒有出錯,就表明安裝成功。

2. 串連MySQL 

db = MySQLdb.connect("localhost", "root", "1", "fs")

其中localhost是伺服器名,root是使用者名稱,1是密碼,fs是資料庫名稱,前提是MySQL資料庫設定了相應的使用者名稱和密碼。

串連成功以後,通過

cur = db.cursor()

擷取遊標。

3. 查詢資料
    cur.execute("select * from TableName where A = %s and B = %s order by C desc", (a, b))    results = cur.fetchall()    result = list(results)

cur.execute()執行查詢語句,cur.fetchal()取得結果集,再用list()把結果集轉換成tuple數組,剩下的就很容易處理了。

4. 寫入資料
cur.execute("insert into A values(%s, %s, %s, %s)", (x1, x2, x3, x4))db.commit()

不論寫入的欄位在表中是什麼類型,都使用%s,否則會出錯,寫完以後需要commit()。

其他的還有Delete和Update操作,都是類似的,通過cur.execute()執行SQL語句,用%s代入參數就行了。

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.