【Python之路】第十九篇--Python操作MySQL

來源:互聯網
上載者:User

標籤:hal   遊標   相同   行資料   mysqld   val   查詢   install   new   

本篇對於Python操作MySQL主要使用兩種方式:

  • 原生模組 pymsql

  • ORM架構 SQLAchemy

pymsql

pymsql是Python中操作MySQL的模組,其使用方法和MySQLdb幾乎相同。

下載安裝

pip3 install pymysql

使用操作

1、執行SQL

# 建立串連conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘db1‘)# 建立遊標cursor = conn.cursor()# 執行SQL,並返回受影響行數effect_row = cursor.execute("update hosts set host = ‘1.1.1.2‘ where nid > %s", (1,))  # 執行SQL,並返回受影響行數effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])# 提交,不然無法儲存建立或者修改的資料conn.commit()  # 關閉遊標cursor.close()# 關閉串連conn.close()

增,刪,改需要執行 conn.commit()

2、擷取新建立資料自增ID

import pymysql  conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)cursor = conn.cursor()cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])conn.commit()cursor.close()conn.close()  # 擷取最新自增ID  => 如果插入多條,只能拿到最後一條idnew_id = cursor.lastrowid

3、擷取查詢資料

import pymysql  conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)cursor = conn.cursor()cursor.execute("select * from hosts")  # 擷取第一行資料row_1 = cursor.fetchone()# => 再次執行:cursor.fetchone() 獲得下一條資料,沒有時為None# 擷取前n行資料# row_2 = cursor.fetchmany(n)# ==> 執行了n次fetchone()# 擷取所有資料# row_3 = cursor.fetchall()  conn.commit()cursor.close()conn.close()

註:在fetch資料時按照順序進行,可以使用cursor.scroll(num,mode)來移動遊標位置,如:

  • cursor.scroll(-1,mode=‘relative‘)  # 相對當前位置移動

  • cursor.scroll(2,mode=‘absolute‘) # 相對絕對位置移動

4、fetch資料類型

  關於預設擷取的資料是元祖類型,如果想要或者字典類型的資料,即:

import pymysql  conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘t1‘)  # 遊標設定為字典類型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)row = cursor.execute("select * from user")  result = cursor.fetchone()print(result)conn.commit()cursor.close()conn.close()

  

 

【Python之路】第十九篇--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.