大家在學習python過程中會遇到不會安裝pymysql模塊的情況,pymsql是python中操作MySQL的模塊,目前pymysql是支持python3.x的,下文中的安裝教程也是在python3.6.1 Mysql5.7.18的環(huán)境下進行的。Python如何安裝pymysql模塊?一起來看一下。
python
1、安裝模塊
pip3 install pymysql
2、python操作
1) 獲取查詢數(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)建游標
cursor = conn.cursor()
# 執(zhí)行SQL
cursor.execute("select * from student")
#獲取剩余結(jié)果的第一行數(shù)據(jù)
#row_1 = cursor.fetchone()
#獲取前n行數(shù)據(jù)
#row_2 = cursor.fetchmany(3)
#獲取所有查詢數(shù)據(jù)
row_3 = cursor.fetchall()
print(row_3)
# 提交,不然無法保存新建或者修改的數(shù)據(jù)
conn.commit()
# 關(guān)閉游標
cursor.close()
# 關(guān)閉連接
conn.close()
3、獲取新創(chuàng)建數(shù)據(jù)的自增id
最后插入的一條數(shù)據(jù)id
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "Yu"
import pymysql
conn = 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()
# 獲取自增id
new_id = cursor.lastrowid
print(new_id)
4、fetch數(shù)據(jù)類型
關(guān)于默認獲取的數(shù)據(jù)是元祖類型,如果想要或者字典類型的數(shù)據(jù),即:
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "Yu"
import pymysql
conn = pymysql.connect(host='127.0.0.1',port=3306, user='root', passwd='redhat', db='db3')
#游標設(shè)置為字典類型
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如何安裝pymysql模塊你學會了么?目前,pymysql支持python3.x,但與其用法幾乎相同的MySQLdb目前是不支持python3.x版本的,這一點需要注意。如果你有任何關(guān)于python的問題或者想了解python培訓課程,歡迎咨詢千鋒教育!