Python——操作MySQL

來源:互聯網
上載者:User

標籤:upd   使用   步驟   串連   群組類型   hone   除了   建議   fetchall   

操作MySQL的步驟

1、匯入mysql模組

2、建立串連

3、建立遊標

4、執行select/update/delete/insert等操作(除了select外其他動作需要commit)

5、關閉遊標,關閉串連

import pymysql

conn = pymysql.connect(ip,port,user,password,db,charset,autocommit)

cur = conn.cursor()

sql = "select * from tbl_cpy"

cur.execute(sql)

cur.fetchall()

cur.close()

conn.close

遊標:

  遊標類型可以是普通類型也可以是字典類型。

  字典類型遊標查詢結果返回也是字典類型。cur = conn.cursor(cursor = pymysql.cursors.DictCursor)

  普通類型遊標查詢結果返回的是元群組類型。cur.conn.cursor()

  如果是將結果匯入excel表格,建議使用普通遊標,因為查詢結果是二位元組,有下標,方便取資料。(字典無序)

 

查看查詢結果的欄位名的方法:

cur.description()

擷取資料

        cur.fetchall() 擷取所有資料

        cur.fetchone() 每次擷取一條資料

        cur.fetchmany(num) 擷取指定條數的資料

 

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.