日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

pymsql学习笔记

發(fā)布時間:2023/11/27 生活经验 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 pymsql学习笔记 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
pymsql學(xué)習(xí)筆記

1. 執(zhí)行SQL

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql# 創(chuàng)建連接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
# 創(chuàng)建游標
cursor = conn.cursor()# 執(zhí)行update,并返回收影響行數(shù), print(effect_row)返回受影響的行數(shù)
effect_row = cursor.execute("update hosts set host = '1.1.1.2'")# 執(zhí)行update,后面括號內(nèi)容就是插入變量,%s,%d使用方式一樣
#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))# 執(zhí)行SQL,并返回受影響行數(shù)
#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])# 提交,不然無法保存新建或者修改的數(shù)據(jù)
conn.commit()# 關(guān)閉游標
cursor.close()
# 關(guān)閉連接
conn.close()

2、獲取新創(chuàng)建數(shù)據(jù)自增ID

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysqlconn = 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
new_id = cursor.lastrowid

3、獲取查詢數(shù)據(jù),使用fetch來獲取查詢的結(jié)果

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor()
cursor.execute("select * from hosts")# 獲取第一行數(shù)據(jù)
row_1 = cursor.fetchone()# 獲取前n行數(shù)據(jù)
# row_2 = cursor.fetchmany(3)
# 獲取所有數(shù)據(jù)
# row_3 = cursor.fetchall()conn.commit()
cursor.close()
conn.close()

注:在fetch數(shù)據(jù)時按照順序進行,可以使用cursor.scroll(num,mode)來移動游標位置,如:

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

4、fetch數(shù)據(jù)類型

關(guān)于默認獲取的數(shù)據(jù)是元祖類型,如果想要或者字典類型的數(shù)據(jù),即:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')# 游標設(shè)置為字典類型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
r = cursor.execute("call p1()")result = cursor.fetchone()conn.commit()
cursor.close()
conn.close()  

fetchone只選擇一個執(zhí)行,如果執(zhí)行兩次fetchone會獲取下一個結(jié)果,好像迭代器一樣
fetchmany選擇多個執(zhí)行,fechmany(3)一次拿三次
fetchall選擇全部執(zhí)行

cursor.scroll(-1, mode='relative')  # 相對的位置向上移動游標
cursor.scroll(2, mode='absolute')  # 絕對的位置向下移動游標

?


?

MySQL 其他注意事項:

1. syntax = NULL 這是錯誤的寫法,正確應(yīng)該為 IS NULL,作為判斷

2. inter join vs outer join

?

posted on 2017-10-17 05:36 ecwork 閱讀(...) 評論(...) 編輯 收藏

轉(zhuǎn)載于:https://www.cnblogs.com/ecwork/p/7679753.html

總結(jié)

以上是生活随笔為你收集整理的pymsql学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。