Python查詢更新mysql資料庫(增刪改查)

來源:互聯網
上載者:User

首先,我們來操作下面步驟:(1)串連資料庫;(2)建立指標;(3)通過指標插入記錄;(4)提交將插入結果儲存到資料庫。

>>> #匯入模組>>> import MySQLdb>>> #串連資料庫>>> conn = MySQLdb.connect(host="localhost",user="root",passwd="123123",db="qiwsirtest",port=3036,charset="utf8")>>> #建立指標>>> cur = conn.cursor()>>> #插入記錄>>> cur.execute("insert into users (username,password,email) values (%s,%s,%s)",("老齊","9988","<a href="mailto:qiwsir@gmail.com" target="_blank">qiwsir@gmail.com</a>"))1L>>> #提交儲存>>> conn.commit()


先進入資料庫看看資料是否成功插入


mysql> select * from users;  
 
    +----+----------+----------+------------------+  
 
    | id | username | password | email            |  
 
    +----+----------+----------+------------------+  
 
    |  1 | qiwsir   | 123123   | <a href="mailto:qiwsir@gmail.com" target="_blank">qiwsir@gmail.com</a> |  
 
    |  2 | python   | 123456   | <a href="mailto:python@gmail.com" target="_blank">python@gmail.com</a> |  
 
    |  3 | google   | 111222   | <a href="mailto:g@gmail.com" target="_blank">g@gmail.com</a>      |  
 
    |  4 | facebook | 222333   | <a href="mailto:f@face.book" target="_blank">f@face.book</a>      |  
 
    |  5 | github   | 333444   | <a href="mailto:git@hub.com" target="_blank">git@hub.com</a>      |  
 
    |  6 | docker   | 444555   | <a href="mailto:doc@ker.com" target="_blank">doc@ker.com</a>      |  
 
    |  7 | 老齊     | 9988     | <a href="mailto:qiwsir@gmail.com" target="_blank">qiwsir@gmail.com</a> |  
 
    +----+----------+----------+------------------+  
 
    7 rows in set (0.00 sec)  


我們可以看到7條記錄是存在的。不過這裡特別提醒,我在前面建立這個資料庫和資料表的時候,就已經設定好了字元編碼為utf8,所以,在現在看到的查詢結果中,可以顯示漢字。否則,就看到的是一堆你不懂的碼子了。如果遇到,請不要慌張,只需要修改字元編碼即可。怎麼改?請google。網上很多。


查詢資料

在前面操作的基礎上,如果要從資料庫中查詢資料,當然也可以用指標來操作了。

>>> cur.execute("select * from users")      
 
7L  


這說明從users表匯總查詢出來了7條記錄。但是,這似乎有點不友好,告訴我7條記錄查出來了,但是在哪裡呢,看前面在'mysql>'下操作查詢命令的時候,一下就把7條記錄列出來了。怎麼顯示python在這裡的查詢結果呢?

原來,在指標執行個體中,還要用這樣的方法,才能實現上述想法:

fetchall(self):接收全部的返回結果行.

fetchmany(size=None):接收size條返回結果行.如果size的值大於返回的結果行的數量,則會返回cursor.arraysize條資料.

fetchone():返回一條結果行.

scroll(value, mode='relative'):移動指標到某一行.如果mode='relative',則表示從當前所在行移動value條,如果mode='absolute',則表示從結果集的第一行移動value條.

按照這些規則,嘗試:


>>> cur.execute("select * from users")        7L>>> lines = cur.fetchall()<br><br>


到這裡,還沒有看到什麼,其實已經將查詢到的記錄(把他們看做對象)賦值給變數lines了。如果要把它們顯示出來,就要用到曾經學習過的迴圈語句了。


>>> for line in lines:    ...     print line    ...     (1L, u'qiwsir', u'123123', <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>)    (2L, u'python', u'123456', <a href="mailto:u'python@gmail.com'" target="_blank">u'python@gmail.com'</a>)    (3L, u'google', u'111222', <a href="mailto:u'g@gmail.com'" target="_blank">u'g@gmail.com'</a>)    (4L, u'facebook', u'222333', <a href="mailto:u'f@face.book'" target="_blank">u'f@face.book'</a>)    (5L, u'github', u'333444', <a href="mailto:u'git@hub.com'" target="_blank">u'git@hub.com'</a>)    (6L, u'docker', u'444555', <a href="mailto:u'doc@ker.com'" target="_blank">u'doc@ker.com'</a>)    (7L, u'\u8001\u9f50', u'9988', <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>)




很好。果然是逐條顯示出來了。列位注意,第七條中的u'\u8001\u95f5',這裡是漢字,只不過由於我的shell不能顯示罷了,不必驚慌,不必搭理它。

只想查出第一條,可以嗎?當然可以!看下面的:


>>> cur.execute("select * from users where id=1")    1L    >>> line_first = cur.fetchone()     #只返回一條    >>> print line_first    (1L, u'qiwsir', u'123123', <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>)




為了對上述過程瞭解深入,做下面實驗:

>>> cur.execute("select * from users")    7L    >>> print cur.fetchall()    ((1L, u'qiwsir', u'123123', <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>), (2L, u'python', u'123456', <a href="mailto:u'python@gmail.com'" target="_blank">u'python@gmail.com'</a>), (3L, u'google', u'111222', <a href="mailto:u'g@gmail.com'" target="_blank">u'g@gmail.com'</a>), (4L, u'facebook', u'222333', <a href="mailto:u'f@face.book'" target="_blank">u'f@face.book'</a>), (5L, u'github', u'333444', <a href="mailto:u'git@hub.com'" target="_blank">u'git@hub.com'</a>), (6L, u'docker', u'444555', <a href="mailto:u'doc@ker.com'" target="_blank">u'doc@ker.com'</a>), (7L, u'\u8001\u9f50', u'9988', <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>))



原來,用cur.execute()從資料庫查詢出來的東西,被“儲存在了cur所能找到的某個地方”,要找出這些被儲存的東西,需要用cur.fetchall()(或者fechone等),並且找出來之後,做為對象存在。從上面的實驗探討發現,被儲存的對象是一個tuple中,裡面的每個元素,都是一個一個的tuple。因此,用for迴圈就可以一個一個拿出來了。

看官是否理解其內涵了?

接著看,還有神奇的呢。

接著上面的操作,再列印一遍

>>> print cur.fetchall()  
 
()  

暈了!怎麼什麼是空?不是說做為對象已經存在了記憶體中了嗎?難道這個記憶體中的對象是一次有效嗎?

不要著急。

通過指標找出來的對象,在讀取的時候有一個特點,就是那個指標會移動。在第一次操作了print cur.fetchall()後,因為是將所有的都列印出來,指標就要從第一條移動到最後一條。當print結束之後,指標已經在最後一條的後面了。接下來如果再次列印,就空了,最後一條後面沒有東西了。

下面還要實驗,檢驗上面所說:

>>> cur.execute('select * from users')    7L    >>> print cur.fetchone()     (1L, u'qiwsir', u'123123', <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>)    >>> print cur.fetchone()    (2L, u'python', u'123456', <a href="mailto:u'python@gmail.com'" target="_blank">u'python@gmail.com'</a>)    >>> print cur.fetchone()    (3L, u'google', u'111222', <a href="mailto:u'g@gmail.com'" target="_blank">u'g@gmail.com'</a>)



這次我不一次全部列印出來了,而是一次列印一條,看官可以從結果中看出來,果然那個指標在一條一條向下移動呢。注意,我在這次實驗中,是重新運行了查詢語句。

那麼,既然在操作儲存在記憶體中的對象時候,指標會移動,能不能讓指標向上移動,或者移動到指定位置呢?這就是那個scroll()


>>> cur.scroll(1)    >>> print cur.fetchone()    (5L, u'github', u'333444', <a href="mailto:u'git@hub.com'" target="_blank">u'git@hub.com'</a>)    >>> cur.scroll(-2)    >>> print cur.fetchone()    (4L, u'facebook', u'222333', <a href="mailto:u'f@face.book'" target="_blank">u'f@face.book'</a>)



果然,這個函數能夠移動指標,不過請仔細觀察,上面的方式是讓指標相對與當前位置向上或者向下移動。即:
cur.scroll(n),或者,cur.scroll(n,"relative"):意思是相對當前位置向上或者向下移動,n為正數,表示向下(向前),n為負數,表示向上(向後)

還有一種方式,可以實現“絕對”移動,不是“相對”移動:增加一個參數"absolute"

特別提醒看官注意的是,在python中,序列對象是的順序是從0開始的。

>>> cur.scroll(2,"absolute")    #回到序號是2,但指向第三條    >>> print cur.fetchone()        #列印,果然是    (3L, u'google', u'111222', <a href="mailto:u'g@gmail.com'" target="_blank">u'g@gmail.com'</a>)  >>> cur.scroll(1,"absolute")    >>> print cur.fetchone()    (2L, u'python', u'123456', <a href="mailto:u'python@gmail.com'" target="_blank">u'python@gmail.com'</a>)  >>> cur.scroll(0,"absolute")    #回到序號是0,即指向tuple的第一條    >>> print cur.fetchone()    (1L, u'qiwsir', u'123123', <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>)




至此,已經熟悉了cur.fetchall()和cur.fetchone()以及cur.scroll()幾個方法,還有另外一個,接這上邊的操作,也就是指標在序號是1的位置,指向了tuple的第二條


>>> cur.fetchmany(3)  
 
((2L, u'python', u'123456', <a href="mailto:u'python@gmail.com'" target="_blank">u'python@gmail.com'</a>), (3L, u'google', u'111222', <a href="mailto:u'g@gmail.com'" target="_blank">u'g@gmail.com'</a>), (4L, u'facebook', u'222333', <a href="mailto:u'f@face.book'" target="_blank">u'f@face.book'</a>))  


上面這個操作,就是實現了從當前位置(指標指向tuple的序號為1的位置,即第二條記錄)開始,含當前位置,向下列出3條記錄。

讀取資料,好像有點??卵健O趕缸聊ィ?故怯械覽淼摹D憔醯媚兀?br/>
不過,python總是能夠為我們著想的,它的指標提供了一個參數,可以實現將讀取到的資料變成字典形式,這樣就提供了另外一種讀取方式了。


>>> cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)    >>> cur.execute("select * from users")    7L    >>> cur.fetchall()    ({'username': u'qiwsir', 'password': u'123123', 'id': 1L, 'email': <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>}, {'username': u'mypython', 'password': u'123456', 'id': 2L, 'email': <a href="mailto:u'python@gmail.com'" target="_blank">u'python@gmail.com'</a>}, {'username': u'google', 'password': u'111222', 'id': 3L, 'email': <a href="mailto:u'g@gmail.com'" target="_blank">u'g@gmail.com'</a>}, {'username': u'facebook', 'password': u'222333', 'id': 4L, 'email': <a href="mailto:u'f@face.book'" target="_blank">u'f@face.book'</a>}, {'username': u'github', 'password': u'333444', 'id': 5L, 'email': <a href="mailto:u'git@hub.com'" target="_blank">u'git@hub.com'</a>}, {'username': u'docker', 'password': u'444555', 'id': 6L, 'email': <a href="mailto:u'doc@ker.com'" target="_blank">u'doc@ker.com'</a>}, {'username': u'\u8001\u9f50', 'password': u'9988', 'id': 7L, 'email': <a href="mailto:u'qiwsir@gmail.com'" target="_blank">u'qiwsir@gmail.com'</a>})




這樣,在元組裡面的元素就是一個一個字典。可以這樣來操作這個對象:

>>> cur.scroll(0,"absolute")    >>> for line in cur.fetchall():    ...     print line["username"]    ...     qiwsir    mypython    google    facebook    github    docker    老齊



根據字典對象的特點來讀取了“鍵-值”。

更新資料

經過前面的操作,這個就比較簡單了,不過需要提醒的是,如果更新完畢,和插入資料一樣,都需要commit()來提交儲存。

>>> cur.execute("update users set username=%s where id=2",("mypython"))    1L    >>> cur.execute("select * from users where id=2")    1L    >>> cur.fetchone()    (2L, u'mypython', u'123456', <a href="mailto:u'python@gmail.com'" target="_blank">u'python@gmail.com'</a>)



從操作中看出來了,已經將資料庫中第二條的使用者名稱修改為mypython了,用的就是update語句。

不過,要真的實現在資料庫中更新,還要運行:

>>> conn.commit()  

這就大事完吉了。




Python操作mysql(增刪改查)

#!/usr/bin/env python#coding:utf-8 import MySQLdbtry:    #串連mysql的方法:connect('ip','user','password','dbname')    #conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='test')conn =MySQLdb.connect('127.0.0.1','root','123456',charset = 'gb2312')conn.select_db('python')cur=conn.cursor()sql1 = 'drop database python' #刪除資料庫 sql2 = 'create database if not exists python' #若不存在,則建立資料庫sql3 = 'create database python'sql4 = 'create table module(m_id int not null,m_name VARCHAR(25),m_size int)'#建立表sql5 = 'create table if not exists demo(d_id int not null,d_name varchar(25),m_size int default 0)'values=[]    for i in range(1):     values.append((i,'mysql',i+1)) sql6 = 'insert into module values(%s,%s,%s)'#cur.executemany(sql6,values)   #批量插入values = [1,'MySQLdb',5]sql6 = "insert into module VALUES('%d','%s','%d')"%(2,'MySQLdb',7) #插入#sql6 = "insert into module(m_id,m_name,m_size) VALUES('%d','%s','%d')"%(2,'MySQLdb',7)#sql6 = "insert into module(m_id,m_name,m_size) VALUES('%d','%s','%d')"%(values[0],values[1],values[2])sql7 = "update module set m_name='MySql' where m_id=0 and m_size=0" #修改sql8 = "delete from module where m_id=1 and m_size=0" #刪除sql9 = "select * from module where m_id=1"cur.execute(sql9)count = cur.execute(sql9)  #查詢結果數量print u'查詢結果數量:',countresult = cur.fetchone() print u'單條查詢結果:',resultresult = cur.fetchmany(2)    print u'多條查詢結果:',resultresult = cur.fetchall()    print u'所有不同的查詢結果:',result    for data in result:        print dataconn.commit()cur.close()conn.close()except MySQLdb.Error,e:    print "Mysql Error %d: %s" % (e.args[0], e.args[1])


聯繫我們

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