Python Mysql操作.

來源:互聯網
上載者:User

標籤:

 1. 安裝MySQLdb.從網站下載Mysql for python 的package 注意有32位和64位之分.2. 安裝完成之後從Python IDLE 匯入MySQLdb  >>>import MySQLdb 3. 建立一個資料庫連接:    >>>conn =MySQLdb.connect(host = ‘127.0.0.1‘,user= ‘root‘,passwd=‘123456‘,db=‘test‘,port=3306,charset=‘utf8‘)  >>>  注意:其中的hsot 參數的值也可寫為host = "localhost", passwd 切勿寫成了password, port 參數需要int類型,上面的3306不要加引號. charset要和資料庫的字元集相同. 4. 建立遊標:    >>>cur = conn.cursor()  >>> 5. 執行插入單條資料命令  >>>cur.execute("insert into msg (title,name,content) values (‘python‘,‘zz‘,‘test mysql insert‘)")   1L  #返回受影響的記錄條數.  >>>conn.commit()  #需要提交事務插入才會生效.  >>> 6. 利用參數插入多條資料命令  >>>sql = "insert into msg (title,name,content) values (%s,%s,%s)"  #定義一個sql語句  >>>cur.executemany(sql,[(‘title01‘,‘name01‘,‘content01‘),(‘title02‘,‘name02‘,‘content02‘)])  2L  >>>conn.commit()  >>> 7. 利用 for 迴圈拼接sql命令插入多條資料.  >>>sql = "insert into msg (title,name,content) values"  >>>for i in range (100):    >>>  sql += "(‘id" + str(i) + "‘," + "‘name" + str(i) + "‘," + "‘content" + str(i) + "‘),"  >>>sql = sql[:-1]  #利用切片將最後的"," 刪除.  >>>cur.execute(sql)  103L  >>>conn.commit()  >>>8. 執行刪除命令  >>>cur.execute("delete from msg where title = ‘title02‘ ")  1L  >>>conn.commit()  >>> 9. 執行更改命令  >>>cur.execute("update msg set title=‘changedTitle‘ where title=‘title01‘")  1L  >>>conn.commit()  >>> 10. 執行查詢命令  >>>cur.execute("select * from msg")  3L #返回記錄條數  >>>python的查詢語句並不會返回資料庫中存取的實際值, 僅返回獲得的記錄條數, 那麼想要獲得資料庫中的值該怎麼做呢?我們需要用到遊標的fetch. 11. 利用fetchone()獲得一條記錄.該條記錄是當前遊標所在行的下一行資料.  >>>cur.fetchone()  (1L, ‘title01‘, ‘name01‘, ‘content01‘) 12. 利用fetchmany(size=num) 擷取多條記錄.  >>>cur.fetchmany(size=5)  ((2L, ‘python‘, ‘ChenYL‘, ‘insert content‘), (3L, ‘py03‘, ‘name03‘, ‘content03‘), (4L, ‘py04‘, ‘name04‘, ‘content04‘), (5L, ‘id0‘, ‘name0‘, ‘content0‘),   (7L, ‘id2‘, ‘name2‘, ‘content2‘))  >>>Note: 此處若查詢資料多於size參數則擷取和size參數相同的記錄條數, 若查詢資料記錄少於size參數的值,則只顯示查詢到的資料記錄條數. 13. 利用fetchall()擷取從遊標位置下一行開始直到查詢記錄結束的全部記錄.  >>>cur.fetchall()  105L  >>>14. 利用scroll()移動遊標  >>>cur.scroll(1,mode="absolute")  >>>Note: 當mode為absolute時遊標走到表中的第一個參數行(若第一個參數為1,則走到表中第一行),次數用fetchone()會取到第二行.當mode為relative是,此時遊標會往下走一行, 假如遊標在第三行, scroll之後會走到第四行. 15. 資料庫使用完之後記得關閉遊標. 關閉資料庫連接.  >>>cur.close()  >>>conn.close   注: 上述執行個體執行結果返回的記錄條數和結果與資料庫中記錄相關.  

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.