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()
相关推荐
前端付豪10 分钟前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
这里有鱼汤15 分钟前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
北方有星辰zz18 分钟前
数据结构:栈
java·开发语言·数据结构
程序员岳焱18 分钟前
Java 与 MySQL 性能优化:MySQL分区表设计与性能优化全解析
后端·mysql·性能优化
源码站~26 分钟前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐
天天摸鱼的java工程师28 分钟前
MySQL表设计实战指南:从业务场景到表结构优化
java·后端·mysql
MessiGo31 分钟前
Python 爬虫实战 | 国家医保
python
我是唐青枫41 分钟前
C#.NET NLog 详解
开发语言·c#·.net
chanalbert1 小时前
Spring 6 源码深度掘金:66+核心原理与高频面试攻坚指南
python·spring·面试
Mr_Xuhhh1 小时前
网络基础(1)
c语言·开发语言·网络·c++·qt·算法