Python操作MySQL

用Python代码连接MySQL并发送命令

1.添加数据

python 复制代码
import pymysql

# 1.连接 MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="123123", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令
cursor.execute("insert into admin(username, password, mobile) values('abc', '123123', '12341235821')")  # 里边写数据库指令
conn.commit()

# 3.关闭
cursor.close()
conn.close()
  • 注意
    在发送指令时,不能用format去做SQL的拼接,会导致SQL注入,有安全隐患,应使用内置的excute方法

    python 复制代码
    # 1.用列表传
    sql = "insert into admin(username, password, mobile) values(%s, %s, %s)"  # 里边写数据库指令
    cursor.execute(sql, ["xyz", "qwe123", "122222222"])
    conn.commit()
    
    # 2.用字典传
    sql = "insert into admin(username, password, mobile) values(%(n1)s, %(n2)s, %(n3)s)"  # 里边写数据库指令
    cursor.execute(sql, {"n1": "abc", "n2": "qwe123", "n3": "123123123"})
    conn.commit()

2.获取数据

python 复制代码
import pymysql


# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="401025", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令
cursor.execute("select * from admin")  # 里边写数据库指令
data_list = cursor.fetchall()
for row_list in data_list:
    print(row_list)

# 3.关闭
cursor.close()
conn.close()
相关推荐
金銀銅鐵7 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1112 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0014 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵16 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf16 小时前
Agent 流程编排
后端·python·agent
copyer_xyf17 小时前
Agent RAG
后端·python·agent
copyer_xyf17 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf17 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python