(目录)


可以尝试一下VSCode的ChatGPT插件 image.png

一、Python3连接MySQL数据库

  • Windows下打开服务管理器的命令:services.msc
  • Windows下MySQL8.0 starting the server失败解决办法:https://blog.csdn.net/LYD203/article/details/122269317
  • Ubuntu22.04安装MySQL8可以参考:https://blog.csdn.net/c_learner_/article/details/125238004
  • Python3连接MySQL数据库可参考:https://www.runoob.com/python3/python3-mysql.html

安装PyMySQL 驱动

pip install PyMySQL

1. 查询

import pymysql

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# SQL 查询语句
cond = "137%"
sql = f"select * from test_info where u_tel like '{cond}'"
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表,results是元组
    # cursor.fetchone()获取单条数据
    results = cursor.fetchall()
    for row in results:
        id = row[0]
        u_name = row[1]
        u_tel = row[2]
        u_mark = row[3]
        # 打印结果
        print("编号=%s, 姓名=%s, 电话=%s, 描述=%s" % (id, u_name, u_tel, u_mark))
except:
    print("Error: unable to fetch data")

# 关闭数据库连接
db.close()

获取结果集的函数:

  • fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
  • fetchall(): 接收全部的返回结果行.
  • rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

其他说明:

  • 一般在退出数据库连接后需要对连接和cursor对向完成关闭,释放资源。
cursor.close()
db.close()
  • DB-API的主要函数 connect() 创建数据库连接。 cursor() 管理查询 execute()和executemany() 运行一个或多个SQL命令 fetchone()、fetchmany()和fetchall() 获取execute()的结果

2. 修改

import pymysql

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# SQL 更新语句
sql = "update test_info set u_tel = '%s' where u_name = '%s'" % ("13800138000", "王五")
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 发生错误时回滚
    db.rollback()

# 关闭数据库连接
db.close()

3. 新增

import pymysql

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# SQL 插入语句(也可以使用\来续行)
u_name = "武松"
u_tel = "13876980999"
u_mark = "武术家"

sql = f"""insert into test_info(id,
         u_name, u_tel, u_mark)
         values (default, '{u_name}', '{u_tel}', '{u_mark}')"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()

# 关闭数据库连接
db.close()

为了防止SQL注入攻击,可以使用占位符(placeholder)来形成SQL语句。

import pymysql

# 连接到数据库
conn = pymysql.connect(
    host="localhost",
    user="root",
    password="123456",
    db="test",
    charset="utf8mb4",
    cursorclass=pymysql.cursors.DictCursor,
)

try:
    with conn.cursor() as cursor:  # 上下文管理器,自动关闭游标
        # 创建一个带有占位符的SQL语句——这里的占位符是%s(其他的占位符如%d、%f等也可以)
        sql = "insert into `test_info` (`id`, `u_name`, `u_tel`, `u_mark`) values (default, %s, %s, %s)"
        # 执行SQL语句,传入参数。注意,参数是通过execute()方法的第二个参数传入的,它是一个元组。
        name = "鲁智深"
        tel = "13768980998"
        mark = "大力士"
        cursor.execute(sql, (name, tel, mark))

    # 提交事务
    conn.commit()

finally:
    # 关闭数据库连接
    conn.close()

在这个示例中,%s 被用作占位符,实际的值通过 cursor.execute 方法的第二个参数传递。这样可以确保参数被正确地转义,从而防止SQL注入攻击。确保占位符的数量与传递的参数数量一致,并且类型匹配。

4. 删除

import pymysql

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# SQL 删除语句
who = "张三"
sql = "delete from test_info where u_name = '%s'" % who
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 提交修改
    db.commit()
except:
    # 发生错误时回滚
    db.rollback()

# 关闭数据库连接
db.close()

二、异步方法连接MySQL数据库

模块aiomysql基于PyMySQL,提供与PyMySQL相同的API,但具备异步能力。 官网:https://aiomysql.readthedocs.io/en/stable/index.html 安装aiomysql

pip install aiomysql
或者
pip install -i https://mirrors.aliyun.com/pypi/simple aiomysql

使用的基本例子

import asyncio
import aiomysql

loop = asyncio.get_event_loop()


async def test_example():
    conn = await aiomysql.connect(
        host="127.0.0.1", port=3306, user="root", password="123456", db="test", loop=loop
    )

    cur = await conn.cursor()
    await cur.execute("select * from test_info")
    # print(cur.description)
    r = await cur.fetchall()
    print(r)
    await cur.close()
    conn.close()


loop.run_until_complete(test_example())

三、asyncio并发应用

asyncio 是 Python 3.4 引入的标准库之一,用于编写异步代码。如果您使用的是 Python 3.4 以上版本,则不需要额外安装 asyncio,因为它已经是 Python 的一部分。

  • 批量并发ping 安装软件包
pip install ping3 [-i https://mirrors.aliyun.com/pypi/simple]

代码如下:

import asyncio
from ping3 import ping


async def ping_host(host):
    result = ping(host)
    if (result is None) or (result == False):
        print(f"{host} 不可达")
    else:
        print(f"{host} 延迟: {result} 秒")


async def batch_ping(hosts):
    tasks = [ping_host(host) for host in hosts]
    await asyncio.gather(*tasks)


if __name__ == "__main__":
    hosts = ["192.168.1." + str(i) for i in range(1, 255)]
    asyncio.run(batch_ping(hosts))

四、python3使用ssh连接主机

安装软件包

pip install paramiko [-i https://mirrors.aliyun.com/pypi/simple] 

示例代码如下:

import paramiko

# 账号信息
hostname = "192.168.52.22"
port = 22
username = "test"
password = "123456"
command = "last"

# 创建SSH客户端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接SSH服务器
ssh.connect(hostname, port, username, password)

# 发送命令并获取回显
stdin, stdout, stderr = ssh.exec_command(command)

# 一次性读取所有回显
# output = stdout.read().decode()
# print(output)

# 逐行读取输出
for line in stdout:
    if "2000" in line:  # 过滤输出
        print(line, end="")  # 取消自动换行

# 关闭SSH连接
ssh.close()

引入多进程执行命令的例子——加快命令执行速度

# 账号信息
hostname = "192.168.52.22"
port = 22
username = "test"
password = "123456"
cmds = ["last", "netstat -ntpl", "df -hT"]


def ssh_cmd(hostname, port, username, password, cmd, logfile):
    import paramiko
    import os

    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # 连接SSH服务器
    ssh.connect(hostname, port, username, password)

    pid = os.getpid()
    print(f"命令 {cmd} pid={pid} 开始执行...")

    # 发送命令并获取回显
    stdin, stdout, stderr = ssh.exec_command(cmd)

    # 一次性读取所有回显
    output = stdout.read().decode()
    with open(logfile, "w") as f:
        f.write(output)
        f.flush()

    # 关闭SSH连接
    ssh.close()
    print(f"命令 {cmd} pid={pid} 执行完成!")


import multiprocessing

# 多进程执行命令
if __name__ == "__main__":
    for i in range(len(cmds)):
        p = multiprocessing.Process(
            target=ssh_cmd,
            args=(hostname, port, username, password, cmds[i], f"cmds_{i}.log"),
        )
        p.start()
        p.join()