python資料庫操作常用功能使用詳解(建立表/插入資料/擷取資料)

來源:互聯網
上載者:User

標籤:

執行個體1、取得MYSQL版本

# -*- coding: UTF-8 -*-#安裝MYSQL DB for pythonimport MySQLdb as mdbcon = Nonetry:    #串連mysql的方法:connect(host=‘localhost‘,user=‘root‘,passwd=‘root‘,db=‘test‘,port=3306)    con = mdb.connect(‘localhost‘, ‘root‘,        ‘root‘, ‘test‘);    #所有的查詢,都在串連con的一個模組cursor上面啟動並執行    cur = con.cursor()    #執行一個查詢    cur.execute("SELECT VERSION()")    #取得上個查詢的結果,是單個結果    data = cur.fetchone()    print "Database version : %s " % datafinally:    if con:        #無論如何,串連記得關閉        con.close()

執行結果:

Database version : 5.5.25

 

 

執行個體2、建立一個表並且插入資料

# -*- coding: UTF-8 -*-import MySQLdb as mdbimport sys#將con設定為全域串連con = mdb.connect(‘localhost‘, ‘root‘, ‘root‘, ‘test‘);with con:    #擷取串連的cursor,只有擷取了cursor,我們才能進行各種操作    cur = con.cursor()    #建立一個資料表 writers(id,name)    cur.execute("CREATE TABLE IF NOT EXISTS         Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")    #以下插入了5條資料    cur.execute("INSERT INTO Writers(Name) VALUES(‘Jack London‘)")    cur.execute("INSERT INTO Writers(Name) VALUES(‘Honore de Balzac‘)")    cur.execute("INSERT INTO Writers(Name) VALUES(‘Lion Feuchtwanger‘)")    cur.execute("INSERT INTO Writers(Name) VALUES(‘Emile Zola‘)")    cur.execute("INSERT INTO Writers(Name) VALUES(‘Truman Capote‘)")

 

 

 

執行個體3、python使用slect擷取mysql的資料並遍曆

# -*- coding: UTF-8 -*-import MySQLdb as mdbimport sys#串連mysql,擷取串連的對象con = mdb.connect(‘localhost‘, ‘root‘, ‘root‘, ‘test‘);with con:    #仍然是,第一步要擷取串連的cursor對象,用於執行查詢    cur = con.cursor()    #類似於其他語言的query函數,execute是python中的執行查詢函數    cur.execute("SELECT * FROM Writers")    #使用fetchall函數,將結果集(多維元組)存入rows裡面    rows = cur.fetchall()    #依次遍曆結果集,發現每個元素,就是表中的一條記錄,用一個元組來顯示    for row in rows:        print row
執行結果:
(1L, ‘Jack London‘)
(2L, ‘Honore de Balzac‘)
(3L, ‘Lion Feuchtwanger‘)
(4L, ‘Emile Zola‘)
(5L, ‘Truman Capote‘)

 

執行個體4、使用字典cursor取得結果集(可以使用表欄位名字訪問值)

 

# -*- coding: UTF-8 -*-import MySQLdb as mdbimport sys#獲得mysql查詢的連結化物件con = mdb.connect(‘localhost‘, ‘root‘, ‘root‘, ‘test‘)with con:    #擷取串連上的字典cursor,注意擷取的方法,    #每一個cursor其實都是cursor的子類    cur = con.cursor(mdb.cursors.DictCursor)    #執行語句不變    cur.execute("SELECT * FROM Writers")    #擷取資料方法不變    rows = cur.fetchall()    #遍曆資料也不變(比上一個更直接一點)    for row in rows:        #這裡,可以使用索引值對的方法,由鍵名字來擷取資料        print "%s %s" % (row["Id"], row["Name"]) 

 

執行個體5、擷取單個表的欄位名和資訊的方法


# -*- coding: UTF-8 -*-import MySQLdb as mdbimport sys#擷取資料庫的連結化物件con = mdb.connect(‘localhost‘, ‘root‘, ‘root‘, ‘test‘)with con:    #擷取普通的查詢cursor    cur = con.cursor()    cur.execute("SELECT * FROM Writers")    rows = cur.fetchall()    #擷取連線物件的描述資訊    desc = cur.description    print ‘cur.description:‘,desc    #列印表頭,就是欄位名字    print "%s %3s" % (desc[0][0], desc[1][0])    for row in rows:        #列印結果        print "%2s %3s" % row 
運行結果: cur.description: ((‘Id‘, 3, 1, 11, 11, 0, 0), (‘Name‘, 253, 17, 25, 25, 0, 1))
Id Name
1 Jack London
2 Honore de Balzac
3 Lion Feuchtwanger
4 Emile Zola
5 Truman Capote

 


執行個體6、使用Prepared statements執行查詢(更安全方便)

 

# -*- coding: UTF-8 -*-import MySQLdb as mdbimport syscon = mdb.connect(‘localhost‘, ‘root‘, ‘root‘, ‘test‘)with con:    cur = con.cursor()    #我們看到,這裡可以通過寫一個可以組裝的sql語句來進行    cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s",        ("Guy de Maupasant", "4"))    #使用cur.rowcount擷取影響了多少行    print "Number of rows updated: %d" % cur.rowcount

結果:

Number of rows updated: 1 

python資料庫操作常用功能使用詳解(建立表/插入資料/擷取資料)

聯繫我們

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