国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Python pymysql模塊安裝并操作過程解析

瀏覽:110日期:2022-07-08 14:22:17

pymsql是Python中操作MySQL的模塊,其使用方法和MySQLdb幾乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。

本文環境 python3.6.1 Mysql 5.7.18

1、安裝模塊

pip3 install pymysql

2、python操作

1) 獲取查詢數據

#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysql# 創建連接conn = pymysql.connect(host=’127.0.0.1’, port=3306, user=’root’, passwd=’redhat’, db=’homework’,charset=’utf8’)# 創建游標cursor = conn.cursor()# 執行SQLcursor.execute('select * from student')#獲取剩余結果的第一行數據#row_1 = cursor.fetchone()#獲取前n行數據#row_2 = cursor.fetchmany(3)#獲取所有查詢數據row_3 = cursor.fetchall()print(row_3)# 提交,不然無法保存新建或者修改的數據conn.commit()# 關閉游標cursor.close()# 關閉連接conn.close()

2、獲取新創建數據的自增id

最后插入的一條數據id

#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = 'Yu'import pymysqlconn = pymysql.connect(host=’127.0.0.1’,port=3306, user=’root’, passwd=’redhat’, db=’db3’)cursor = conn.cursor()effect_row = cursor.executemany('insert into tb11(name,age) values(%s,%s)',[('yu','25'),('chao', '26')])conn.commit()cursor.close()conn.close()# 獲取自增idnew_id = cursor.lastrowidprint(new_id)

3、fetch數據類型

關于默認獲取的數據是元祖類型,如果想要或者字典類型的數據,即:

#! /usr/bin/env python# -*- coding:utf-8 -*-# __author__ = 'Yu'import pymysqlconn = pymysql.connect(host=’127.0.0.1’,port=3306, user=’root’, passwd=’redhat’, db=’db3’)#游標設置為字典類型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute('select * from tb11')row_1 = cursor.fetchone()print(row_1)conn.commit()cursor.close()conn.close()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 大兴区| 潞西市| 长顺县| 阿拉善右旗| 平谷区| 屏南县| 刚察县| 五常市| 益阳市| 江口县| 旅游| 南靖县| 鸡东县| 巫溪县| 永兴县| 湖北省| 扶余县| 招远市| 揭东县| 营口市| 会泽县| 虞城县| 龙海市| 永福县| 阿荣旗| 苍山县| 滦平县| 松阳县| 连州市| 平原县| 冷水江市| 彭水| 沙田区| 金堂县| 荆州市| 庆元县| 高尔夫| 武平县| 东乡| 扶余县| 罗田县|