利用PyMySQL连接MySQL
连接数据库
复制 | import pymysql |
| |
| |
| db = pymysql.connect(host='localhost', user='root', password='123456', port=3306) |
| |
| |
| cursor = db.cursor() |
| |
| |
| cursor.execute('SELECT VERSION()') |
| |
| |
| data = cursor.fetchone() |
| print('Database version:', data) |
| |
| |
| cursor.execute("CREATE DATABASE reptile DEFAULT CHARACTER SET utf8mb4") |
| db.close() |
| |
| |
| |
| |
| Database version: ('8.0.16',) |
| |
创建表
复制 | import pymysql |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| cursor = db.cursor() |
| sql = '''CREATE TABLE |
| IF NOT EXISTS students |
| ( |
| id VARCHAR(255) NOT NULL, |
| name VARCHAR(255) NOT NULL, |
| age INT NOT NULL, |
| PRIMARY KEY (id) |
| )''' |
| |
| cursor.execute(sql) |
| db.close() |
| |
| |
插入数据
方式1
复制 | import pymysql |
| |
| id = '20180001' |
| user = 'Lee Hua' |
| age = 20 |
| |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| |
| cursor = db.cursor() |
| sql = '''INSERT INTO students(id, name, age) VALUES(%s %s %s)''' |
| |
| try: |
| |
| cursor.execute(sql, (id, user, age)) |
| |
| db.commit() |
| |
| except: |
| |
| db.rollback() |
| |
| db.close() |
| |
| |
| |
方式2
复制 | import pymysql |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| cursor = db.cursor() |
| |
| |
| data = { |
| 'id': '20180002', |
| 'user': 'Lao wang', |
| 'age': 19 |
| } |
| table_name = 'students' |
| keys = ', '.join(data.keys()) |
| values = ', '.join(['%s'] * len(data)) |
| sql = '''INSERT INTO {table_name}({keys}) VALUES({values})'''.format(table_name=table_name, keys=keys, values=values) |
| |
| |
| |
| try: |
| tuple_ = tuple(data.values()) |
| if cursor.execute(sql, tuple_): |
| print('成功插入数据') |
| db.commit() |
| |
| except: |
| print('插入数据失败') |
| db.rollback() |
| |
| db.close() |
更新数据
复制 | import pymysql |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| cursor = db.cursor() |
| |
| sql = 'UPDATA students SET age = %s WHERE name = %s' |
| try: |
| cursor.execute(sql, (25, 'Bob')) |
| db.commit() |
| except: |
| db.rollback() |
| |
| db.close() |
实现去重(如果数据存在,则更新数据;如果数据不存在,则插入数据。)
复制 | import pymysql |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| cursor = db.cursor() |
| |
| |
| data = { |
| 'id': '20180002', |
| 'user': 'Lao wang', |
| 'age': 19 |
| } |
| table_name = 'students' |
| keys = ', '.join(data.keys()) |
| values = ', '.join(['%s'] * len(data)) |
| update = ', '.join( |
| [" {key} = %s".format(key=key) for key in data] |
| ) |
| sql = '''INSERT INTO {table_name}({keys}) VALUES({values}) ON DUPLICATE KEY update'''.format(table_name=table_name, keys=keys, values=values) |
| |
| |
| try: |
| tuple_ = tuple(data.values()) |
| if cursor.execute(sql, tuple_): |
| print('成功插入数据') |
| db.commit() |
| |
| except: |
| print('插入数据失败') |
| db.rollback() |
| |
| db.close() |
删除数据
复制 | import pymysql |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| cursor = db.cursor() |
| |
| table = 'students' |
| condition = 'age > 20' |
| sql = 'DELETE FROM {table} WHERE {conditon}'.format(table=table, conditon=condition) |
| try: |
| cursor.execute(sql) |
| db.commit() |
| except: |
| db.rollback() |
| |
| db.close() |
| |
| |
| |
查询数据
复制 | import pymysql |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| cursor = db.cursor() |
| |
| sql = 'SELECT * FROM students WHERE age >= 20' |
| try: |
| cursor.execute(sql) |
| print('Count:', cursor.rowcount) |
| one = cursor.fetchone() |
| print('One:', one) |
| result = cursor.fetchall() |
| print('Result:', result) |
| print('Result Type:', type(result)) |
| for row in result: |
| print(row) |
| except: |
| print('Error') |
复制 | |
| Count: 0 |
| One: None |
| Result: () |
| Result Type: <class 'tuple'> |
一次性查询所有数据
复制 | import pymysql |
| |
| db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile') |
| cursor = db.cursor() |
| |
| sql = 'SELECT * FROM students WHERE age >= 20' |
| try: |
| cursor.execute(sql) |
| print('Count:', cursor.rowcount) |
| row = cursor.fetchone() |
| while row: |
| print('Row:', row) |
| row = cursor.fetchone() |
| except: |
| print('Error') |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)