本文主要是介绍python基础-pymysql,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
-
- 安装模块
- 基础用法
- %占位符封装sql语句
- 传递参数形式
- 增、删、改
- 增加数据库数据
- 删除数据库数据
- 修改数据库数据
- 查询
- 批量操作
- 获取插入的数据id
- 链接池
- 加锁
-
安装模块
pip install pymysql
或者如下的方式
基础用法
创建数据库如下:
CREATE TABLE `test` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` char(10) NOT NULL,`age` int(11) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
表如下:
import pymysql
# 获取用户输入
# name = input("用户名>>:")
# pwd = input("密码>>:")# 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from test WHERE id > 3;"
ret = cursor.execute(sql)
# 关闭光标和连接
cursor.close()
conn.close()print("%s row in set (0.00 sec)" % ret)
输出结果如下:
4 row in set (0.00 sec)
%占位符封装sql语句
import pymysql
# 获取用户输入name = input("用户名>>:")
pwd = input("密码>>:")# 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from test WHERE name='%s' and age=%s;" % (name, pwd)
print(sql)
ret = cursor.execute(sql) # 获取影响的行数
# 关闭光标和连接
cursor.close()
conn.close()
if ret:print("登陆成功")
else:print("登录失败")
运行结果如下:
用户名>>:xiao
密码>>:11
select * from test WHERE name='xiao' and age=11;
登陆成功
传递参数形式
import pymysql
# 获取用户输入
name = input("用户名>>:")
pwd = input("密码>>:")# 校验用户输入的用户名和密码是否正确
# 去数据库里取数据做判断
# 1. 连上数据库
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 光有链接还不行,需要获取光标,让我能够输入SQL语句并执行
cursor = conn.cursor()
# 2. 执行SQL语句 --> select * from userinfo where name=name and pwd=pwd
sql = "select * from test WHERE name=%s and age=%s;"
print(sql)
# 让pymysql拼接字符串
ret = cursor.execute(sql, [name, pwd]) # 获取影响的行数
# 关闭光标和连接
cursor.close()
conn.close()
if ret:print("登陆成功")
else:print("登录失败")
输出如下:
用户名>>:xiao
密码>>:11
select * from test WHERE name=%s and age=%s;
登陆成功
注意的是:
sql = “select * from test WHERE name=%s and age=%s;”
如果改成如下:
sql = "select * from test WHERE name='%s' and age=%s;"
报错如下:
或者如下的方式:
import pymysqlconn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='test')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# cursor.execute("select id,name from users where name=%s and pwd=%s",['safly','123',])
cursor.execute("select id,user from user where user =%(user)s and pwd=%(pwd)s",{'user':'alex','pwd':'123'})
obj = cursor.fetchone()
conn.commit()
cursor.close()
conn.close()print(obj)
输出如下:
{‘id’: 1, ‘user’: ‘safly’}
增、删、改
增加数据库数据
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "insert into test(name, age) VALUE (%s, %s);"username = "Egon2"
#以下2种均可
password = "324"
password = 324
try:# //insert into 表名 (列名1,列名2,列名3) values (值1,值2,值3),(值1,值2,值3)# 执行SQL语句cursor.execute(sql, (username, password))conn.commit() # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()
删除数据库数据
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "delete from test where name=%s"
username = "Egon2"
try:# 执行SQL语句cursor.execute(sql, (username,))conn.commit() # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()
修改数据库数据
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "update test set age=%s where name=%s"print(sql)
username = "xiao"
age = 11111111
try:# 执行SQL语句cursor.execute(sql, (age, username))conn.commit() # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()
查询
目前数据库数据如下:
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "select * from test;"# 执行SQL语句
ret = cursor.execute(sql)
print("-->",ret)
# 一次取一条
print(cursor.fetchone())
print(cursor.fetchone())
print(cursor.fetchmany(3))# 一次取所有
print(cursor.fetchall())
# 一起取三条# 进阶用法# # 移动取数据的光标
cursor.scroll(-2) # 默认是相对移动
print(cursor.fetchone())
# # 按照绝对位置去移动
cursor.scroll(4, mode="absolute")
print(cursor.fetchone())
cursor.close()
conn.close()
输出如下:
--> 9
(1, '小李', 1)
(2, '小王', 2)
((4, 'xsiao', 11), (5, 'xffdfdiao', 11), (13, 'Egon2', 324))
((14, 'wyf', 324), (15, 'aaa', 324), (16, 'ewtr', 324), (17, 'ewtr', 324))
(16, 'ewtr', 324)
(13, 'Egon2', 324)
批量操作
批量插入数据库数据
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "insert into test (name, age) VALUES (%s, %s);"
user1 = "wyf1"
pwd1 = 11
user2 = "wyf2"
pwd2 = 22data = ((user1, pwd1), (user2, pwd2))try:# 执行SQL语句# cursor.execute(sql, (user1, pwd1))# cursor.execute(sql, (user2, pwd2))cursor.executemany(sql, data)conn.commit() # 把修改提交到数据库
except Exception as e:conn.rollback()cursor.close()
conn.close()
获取插入的数据id
import pymysql# 连接
conn = pymysql.connect(host="localhost",database="safly", user="root", password="root", charset="utf8") # 不是utf-8
# 获取光标
cursor = conn.cursor()
# 写sql语句
sql = "insert into test (name, age) VALUES (%s, %s);"
user1 = "Egon3"
pwd1 = 234try:# 执行SQL语句cursor.execute(sql, (user1, pwd1))conn.commit() # 把修改提交到数据库# 拿到我插入这条数据的IDlast_id = cursor.lastrowidprint("--> 刚才插入的那条数据的ID值是:", last_id)
except Exception as e:conn.rollback()cursor.close()
conn.close()
输出如下:
--> 刚才插入的那条数据的ID值是: 22
链接池
import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(creator=pymysql, # 使用链接数据库的模块maxconnections=6, # 连接池允许的最大连接数,0和None表示不限制连接数mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建maxcached=5, # 链接池中最多闲置的链接,0和None不限制maxshared=3, # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错maxusage=None, # 一个链接最多被重复使用的次数,None表示无限制setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]ping=0, # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = alwayshost='127.0.0.1',port=3306,user='root',password='root',database='test',charset='utf8'
)def func():conn = POOL.connection()cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)cursor.execute('select * from user ')result = cursor.fetchall()cursor.close()conn.close()return resultret = func()
print(ret)
输出[{'user': 'alex', 'pwd': '123', 'id': 1}]
加锁
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
import threading
from threading import RLockLOCK = RLock()
CONN = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='root',database='test',charset='utf8')def task(arg):with LOCK:cursor = CONN.cursor()cursor.execute('select * from user ')result = cursor.fetchall()cursor.close()print(result)for i in range(10):t = threading.Thread(target=task, args=(i,))t.start()
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
(('safly', '123', 1),)
这篇关于python基础-pymysql的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!