python连接数据库系列
2024-10-20 06:32:12
1.Python连接MySQL
具体详情参考:MySQL笔记
Python连接MySQL需要借助pymysql,安装pymysql
pip install pymysql
1.1 pymysql连接数据库
"""
支持python代码操作数据库MySQL
"""
pip3 install pymysql
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306
user = 'root',
password = '123456', # 还可以简写passwd = '123456'
database = 'db666', # 还可以简写db = 'db666'
charset = 'utf8' # 千万不要加横杆
)
# cursor = conn.cursor() # 括号内不加参数的话 那么查询出来的数据是元组的形式 数据不够明确 容易混乱
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 字典形式返回数据 数据有具体的描述信息 更加的合理方便
sql = 'select * from user'
affect_rows = cursor.execute(sql) # 返回值是当前sql语句执行的受影响的行数
cursor.fetchone() # 只能结果的一条 数据本身
cursor.fetchall() # 拿所有 列表套多个数据
cursor.fetchmany(n) # 指定获取几条
"""
上述三个方法在读取数据的时候有一个类似于文件指针的特点
"""
cursor.scroll(1,'relative') # 相对于光标所在的当前位置往后移动
cursor.scroll(1,'absolute') # 相对于数据开头往后移动
1.2 pymysql补充
# 1.针对增删改 pymysql需要二次确认才能真正的操作数据
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
passwd = '123456',
db = 'db1',
charset = 'utf8',
autocommit = True
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 增
sql = 'insert into user(name,password) values(%s,%s)'
# rows = cursor.execute(sql,('jackson',123))
rows = cursor.executemany(sql,[('xxx',123),('ooo',123),('yyy',123)])
print(rows)
# conn.commit() # 确认
# 修改
# sql = 'update user set name="jasonNB" where id=1'
# rows = cursor.execute(sql)
# print(rows)
# conn.commit() # 确认
# 删除
sql = 'delete from user where id=7'
rows = cursor.execute(sql)
print(rows)
conn.commit() # 确认
# 查
# sql = 'select * from user'
# cursor.execute(sql)
# print(cursor.fetchall())
"""
增删改查中
删改增它们的操作设计到数据的修改
需要二次确认
"""
# 还可以一次性插入N多条数据
rows = cursor.executemany(sql,[('xxx',123),('ooo',123)])
1.3 sql注入问题
"""
利用一些语法的特性 书写一些特点的语句实现固定的语法
MySQL利用的是MySQL的注释语法
select * from user where name='jason' -- jhsadklsajdkla' and password=''
select * from user where name='xxx' or 1=1 -- sakjdkljakldjasl' and password=''
"""
日常生活中很多软件在注册的时候都不能含有特殊符号
因为怕你构造出特定的语句入侵数据库 不安全
# 敏感的数据不要自己做拼接 交给execute帮你拼接即可
# 结合数据库完成一个用户的登录功能?
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
port = 3306,
user = 'root',
password = '123456',
database = 'db1',
charset = 'utf8' # 编码千万不要加-
) # 链接数据库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
username = input('>>>:')
password = input('>>>:')
sql = "select * from user where name=%s and password=%s"
# 不要手动拼接数据 先用%s占位 之后将需要拼接的数据直接交给execute方法即可
print(sql)
rows = cursor.execute(sql,(username,password)) # 自动识别sql里面的%s用后面元组里面的数据替换
if rows:
print('登录成功')
print(cursor.fetchall())
else:
print('用户名密码错误')
2.Python连接Redis
具体使用详情参考:Redis的使用
2.1 Python操作Redis之普通连接
# 1 pip3 install redis
# 简单使用
from redis import Redis
# conn=Redis()
#连接对象
conn=Redis(host='127.0.0.1', port=6379)
ret=conn.get('name')
print(ret)
2.2 Python操作Redis之连接池
###### t_redis_pool.py
#redis连接池
import redis
# pool必须是单例的
POOL = redis.ConnectionPool(host='127.0.0.1', port=6379,max_connections=100) # 造一个池子,最多能放100个连接 ####### t_redis_conn.py
#redis连接池
# import redis
# pool必须是单例的 所以利用模块导入(单例)
# pool = redis.ConnectionPool(host='127.0.0.1', port=6379,max_connections=100) # 造一个池子,最多能放100个连接
import redis
# 包内的py文件,如果想右键运行,导包的时候不能带点
from t_redis_pool import POOL # pycharm提示的错
r = redis.Redis(connection_pool=POOL) # 只要执行这一句话,就是从池中拿出一个连接
ret=r.get('name')
print(ret)
3.pymongo操作MongoDB
具体详情参考:MongoDB
import pymongo # 导入模块
# 1.建立连接
collection.insert_one({'name':''})
sudo ufw allow 27017 更新
-----------------------------------------------------------
import pymongo
# 建立连接
client = pymongo.MongoClient('127.0.0.1',27017) # 可以省略
# 指定数据库
db = client['python3']
# 指定集合
my_col = db['student']
# 数据操作 (怎删改查)
# 增
# my_col.insert({'name':'parker1','age':16})
# 增多个
my_col.insert_many([{'name':'parker1','age':13},{'name':'parker2','age':14},{'name':'parker3','age':16}])
# 查
# res = my_col.find_one()
# print(res)
# res = my_col.find()
# print(res)
# for i in res:
# print(i)
# 改
# my_col.update_one({'name':'parker1'},{'$set':{'age':100}})
# 查看
# res = my_col.find_one({'name':'parker1'})
# print(res)
# 删 删除一个
res = my_col.delete_one({'name':'parker3'})
print(res)
import pymongo
client = pymongo.MongoClient('127.0.0.1',27017)
db = client['mydb']
collection = db['stu']
collection.insert_one({'name':'aa','age':18})
collection.insert_many([
{'name':'bb','age':19},
{'name':'cc','age':20},
])
for i in collection.find():
print(i)
print(collection.find_one({'name':'bb'}))
4.Python连接Microsoft SQL_Server
41.pymssql
class Sqls:
def __init__(self, host, user, password, database):
self.conn = pymssql.connect(host=host, user=user, password=password, database=database,as_dict=True, charset='cp936')
self.cursor = self.conn.cursor() def execute(self,sql):
self.cursor.execute(sql)
return self.cursor.fetchall() class sqlsToMysql:
def main(self):
host = "host"
user = "user"
password = "password"
database = "database"
sqls = Sqls(host,user,password,database)
r = sqls.execute("select * from a")
for i in r:
print(i)
print(r) if __name__ == '__main__':
sqlsToMysql().main()
示例1
import pymssql conn = pymssql.connect(host="xxx.aus.amer.xx.com",
database='TestEnv',
user='Test1',
password='Test1',
as_dict=True,
timeout=30, charset=r"utf8"
)
cursor = conn.cursor()
sql = """SELECT [CASE_NBR]
FROM [CaseClosure_TestEnv].[dbo].[CC_AAS_Record]
"""
res = cursor.execute(sql)
print(cursor.fetchall())
最新文章
- Linux终端更改提示符
- Ubuntu apparmor何方神圣
- 纯js分页代码(简洁实用)
- 山寨小小军团开发笔记 之 Arrow Projectile
- java1.5新特性
- I2C Verilog的实现(二)
- freemaker的基本语法
- php递归创建目录
- javascript 函数声明问题
- LED驅動芯片 兩種恒流控制方式
- 修改ORACLE的语言参数
- MySQL中的concat函数
- 皮尔逊相似度计算的例子(R语言)
- MVC 01
- WPF中的CheckBox的_ (underscore / 下划线)丢失
- KVM管理平台openebula安装
- dep包安装与依赖库
- fatal error c1001 编译器中发生内部错误 OpenMesh6.3
- Linux 配置SFTP,配置用户访问权限
- Java 内存监控命令简介(零)
热门文章
- Kafka相关面试题及答案
- python之路24之 面向对象动静态方法、继承、派生
- 《STL源码剖析》Sort排序分析
- 解决angular11+zorro使用table组件排序失效以及分页组件失效问题,附完整DEMO代码
- 新下载了一个框架,然后npm install时候报错npm ERR! Maximum call stack size exceeded
- WPF开发经验-实现一种三轴机械手控件
- WPF中下拉框即可以选择项也可以作为只读文本框使用
- 【Regex】判断密码强度的正则表达式
- vue学习笔记(四)---- 品牌管理案例
- springboot返回数据null参数设为空字符串或空数组