Python實戰之MySQL資料庫操作

來源:互聯網
上載者:User

本文地址:http://blog.csdn.net/kongxx/article/details/7094018

1. 要想使Python可以操作MySQL資料庫,首先需要安裝MySQL-python包,在CentOS上可以使用一下命令來安裝

$ sudo yum install MySQL-python2. 啥都不說了,走兩步吧,下面的程式建立了一個到mysql資料庫的串連,然後執行了一個簡單的查詢,並列印查詢結果

import MySQLdb</p><p>conn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong")<br />cursor = conn.cursor ()<br />cursor.execute ("SELECT VERSION()")<br />row = cursor.fetchone ()<br />print "MySQL server version:", row[0]<br />cursor.close ()<br />conn.close ()3. 下面看一個資料庫建表和插入操作
import MySQLdb</p><p>conn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong")<br />cursor = conn.cursor ()</p><p>cursor.execute ("""<br />CREATE TABLE TEST<br />(<br />ID INT,<br />COL1 VARCHAR(40),<br />COL2 VARCHAR(40),<br />COL3 VARCHAR(40)<br />)<br />""")</p><p>cursor.execute ("""<br />INSERT INTO TEST (ID, COL1, COL2, COL3)<br />VALUES<br />(1, 'a', 'b', 'c'),<br />(2, 'aa', 'bb', 'cc'),<br />(3, 'aaa', 'bbb', 'ccc')<br />""")</p><p>conn.commit()<br />cursor.close ()<br />conn.close ()4. 下面再來看看查詢,查詢通常有兩種方式:一種是使用cursor.fetchall()擷取所有查詢結果,然後再一行一行的迭代;另一種每次通過cursor.fetchone()擷取一條記錄,直到擷取的結果為空白為止。看一下下面的例子:

import MySQLdb</p><p>conn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong")<br />cursor = conn.cursor ()</p><p>cursor.execute ("SELECT * FROM TEST")<br />rows = cursor.fetchall()<br />for row in rows:<br />print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3])</p><p>print "Number of rows returned: %d" % cursor.rowcount</p><p>cursor.execute ("SELECT * FROM TEST")<br />while (True):<br />row = cursor.fetchone()<br />if row == None:<br />break<br />print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3])</p><p>print "Number of rows returned: %d" % cursor.rowcount</p><p>cursor.close ()<br />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.