Python pymysql模塊安裝并操作過(guò)程解析
pymsql是Python中操作MySQL的模塊,其使用方法和MySQLdb幾乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
本文環(huán)境 python3.6.1 Mysql 5.7.18
1、安裝模塊
pip3 install pymysql
2、python操作
1) 獲取查詢(xún)數(shù)據(jù)
#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysql# 創(chuàng)建連接conn = pymysql.connect(host=’127.0.0.1’, port=3306, user=’root’, passwd=’redhat’, db=’homework’,charset=’utf8’)# 創(chuàng)建游標(biāo)cursor = conn.cursor()# 執(zhí)行SQLcursor.execute('select * from student')#獲取剩余結(jié)果的第一行數(shù)據(jù)#row_1 = cursor.fetchone()#獲取前n行數(shù)據(jù)#row_2 = cursor.fetchmany(3)#獲取所有查詢(xún)數(shù)據(jù)row_3 = cursor.fetchall()print(row_3)# 提交,不然無(wú)法保存新建或者修改的數(shù)據(jù)conn.commit()# 關(guān)閉游標(biāo)cursor.close()# 關(guān)閉連接conn.close()
2、獲取新創(chuàng)建數(shù)據(jù)的自增id
最后插入的一條數(shù)據(jù)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數(shù)據(jù)類(lèi)型
關(guān)于默認(rèn)獲取的數(shù)據(jù)是元祖類(lèi)型,如果想要或者字典類(lèi)型的數(shù)據(jù),即:
#! /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’)#游標(biāo)設(shè)置為字典類(lèi)型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()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. 得到XML文檔大小的方法3. 如何在jsp界面中插入圖片4. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法5. phpstorm斷點(diǎn)調(diào)試方法圖文詳解6. ASP常用日期格式化函數(shù) FormatDate()7. JavaScrip簡(jiǎn)單數(shù)據(jù)類(lèi)型隱式轉(zhuǎn)換的實(shí)現(xiàn)8. XML入門(mén)的常見(jiàn)問(wèn)題(二)9. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式10. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法
