技术文摘
Python 写入 MySQL 数据库的方法有哪些
Python 写入 MySQL 数据库的方法有哪些
在数据处理和开发的领域中,将 Python 与 MySQL 数据库相结合是常见的需求。Python 凭借其丰富的库和简洁的语法,能方便地与 MySQL 交互并写入数据。下面就为大家介绍几种常见的方法。
使用 MySQL Connector/Python
MySQL Connector/Python 是 MySQL 官方提供的 Python 驱动程序。首先要确保安装该库,使用 pip install mysql-connector-python 即可。
使用时,先建立数据库连接,示例代码如下:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
连接成功后,创建游标对象,通过游标执行 SQL 插入语句。例如向名为 employees 的表中插入数据:
mycursor = mydb.cursor()
sql = "INSERT INTO employees (name, age, department) VALUES (%s, %s, %s)"
val = ("John", 30, "Sales")
mycursor.execute(sql, val)
mydb.commit()
使用 PyMySQL
PyMySQL 也是一个流行的选择,它是纯 Python 实现的 MySQL 客户端库。同样先安装:pip install pymysql。
连接数据库的代码类似:
import pymysql
conn = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
插入数据的操作如下:
cursor = conn.cursor()
sql = "INSERT INTO employees (name, age, department) VALUES (%s, %s, %s)"
val = ("Jane", 25, "Marketing")
cursor.execute(sql, val)
conn.commit()
使用 SQLAlchemy
SQLAlchemy 是一个强大的数据库抽象层库,支持多种数据库。安装命令:pip install sqlalchemy。
使用 SQLAlchemy 连接 MySQL 并写入数据,代码示例如下:
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql+pymysql://your_username:your_password@localhost/your_database')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Employees(Base):
__tablename__ = 'employees'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
department = Column(String)
new_employee = Employees(name="Bob", age=35, department="IT")
session.add(new_employee)
session.commit()
以上这些方法各有特点,MySQL Connector/Python 是官方驱动,稳定性好;PyMySQL 纯 Python 实现,方便安装;SQLAlchemy 则提供了强大的数据库抽象层,适用于复杂的数据库操作场景。开发者可根据项目需求灵活选择。
TAGS: MySQL数据库 数据库交互 写入方法 Python写入MySQL
- 分析Vue响应式系统对应用性能的影响
- Vue 与 Canvas:图片颜色调整及滤镜效果的实现方法
- 前端开发必知:借助 Vue 与网易云 API 达成音乐播放记录功能
- Vue技术:借助网易云API实现音乐MV播放功能分享
- 借助 Vue 错误捕获机制提升应用异常处理性能的方法
- 解析Vue组件通讯中的数据筛选方案
- Vue 与 Axios 达成异步数据请求的同步化处理
- Vue 与网易云 API 打造智能化音乐收藏夹的方法
- 基于Vue与Axios的前端数据请求性能监控及统计分析
- Vue 与 Element-plus 实现表单验证与数据处理的方法
- Vue 的 Keep-Alive 组件助力优化应用缓存性能的方法
- 借助Vue与Axios打造灵活可靠的前端数据请求模块
- Vue 利用 keep-alive 优化组件性能的途径
- Vue 提升应用渲染性能的方法
- Vue 与 Axios 前端数据请求性能优化策略