Python 操作mysql

來源:互聯網
上載者:User

標籤:bsp   exec   關閉   select   color   升級   返回   預設   安裝   

pymysql

需要安裝pymysql模組才能在python中使用MySQL

安裝

pip3 install pymysql

若安裝失敗,需要升級pip版本

python -m pip install --upgrade pip

使用

1.執行mysql

 1 import pymysql 2    3 # 建立串連 4 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘) 5 # 建立遊標 6 cursor = conn.cursor() 7    8 # 執行SQL,並返回收影響行數  effect_row可列印 9 effect_row = cursor.execute("update hosts set host = ‘1.1.1.2‘")10   11 # 執行SQL,並返回受影響行數12 # effect_row = cursor.execute("update hosts set host = ‘1.1.1.2‘ where nid > %s", (1,))13   14 # 執行SQL,並返回受影響行數15 # effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])16   17   18 # 提交,不然無法儲存建立或者修改的資料19 conn.commit()20   21 # 關閉遊標22 cursor.close()23 # 關閉串連24 conn.close()

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

增加多條資料用 executemany()     傳的資料應為列表/元組中的元組,如[(),(),()]

自增ID: cursor.lastrowid

 1 import pymysql 2    3 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘) 4 cursor = conn.cursor() 5 cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) 6 conn.commit() 7 cursor.close() 8 conn.close() 9   10 # 擷取最新自增ID11 new_id = cursor.lastrowid

3.擷取查詢資料

 1 import pymysql 2    3 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘) 4 cursor = conn.cursor() 5 cursor.execute("select * from hosts") 6    7 # 擷取第一行資料 8 row_1 = cursor.fetchone() 9   10 # 擷取前n行資料11 # row_2 = cursor.fetchmany(3)12 # 擷取所有資料13 # row_3 = cursor.fetchall()14   15 conn.commit()16 cursor.close()17 conn.close()

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

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

4. fench資料類型

預設擷取的資料是元群組類型,要想字典類型則要把遊標設定為字典類型

 1 import pymysql 2    3 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘) 4    5 # 遊標設定為字典類型 6 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 7 r = cursor.execute("call p1()") 8    9 result = cursor.fetchone()10   11 conn.commit()12 cursor.close()13 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.