python数据库操作

数据库基本操作

    • [一、 数据库操作](#一、 数据库操作)
      • [1. mysql 驱动安装:](#1. mysql 驱动安装:)
      • [2. mysql基本操作:](#2. mysql基本操作:)
    • 二、代码演示

一、 数据库操作

1. mysql 驱动安装:

复制代码
MySQL 是最流行的关系型数据库管理系统,如果你不熟悉 MySQL,可以阅读我们的 MySQL 教程。
本章节我们为大家介绍使用 mysql-connector 来连接使用 MySQL, mysql-connector 是 MySQL 官方提供的驱动器。
我们可以使用 pip 命令来安装 mysql-connector:
python -m pip install mysql-connector

2. mysql基本操作:

复制代码
创建连接
创建数据库
创建表
插入数据
批量插入数据
查询数据(like、where )
排序(order)
修改数据
删除数据
删除表

二、代码演示

py 复制代码
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# @Date : 2024/4/30 16:45
# @Author : water
# @Description : 数据库操作
"""
mysql 驱动安装:
    MySQL 是最流行的关系型数据库管理系统,如果你不熟悉 MySQL,可以阅读我们的 MySQL 教程。
    本章节我们为大家介绍使用 mysql-connector 来连接使用 MySQL, mysql-connector 是 MySQL 官方提供的驱动器。
    我们可以使用 pip 命令来安装 mysql-connector:
    python -m pip install mysql-connector
mysql:
    创建连接
    创建数据库
    创建表
    插入数据
    批量插入数据
    查询数据(like、where )
    排序(order)
    修改数据
    删除数据
    删除表

"""

import mysql.connector

#  创建数据库连接

db = mysql.connector.connect(
    host="172.22.1.199",
    user="root",
    password="Sxxc@2024",
    # mysql版本太低:报错;mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
    # auth_plugin="mysql_native_password",  # mysql8 可能支持caching_sha2_password
    database="mysql"
)

print(db)

#  创建数据库
cursor = db.cursor()
# cursor.execute("CREATE DATABASE test_db")
cursor.execute("show databases")
for x in cursor:
    print(x)

# 创建表,如果不指定,默认被创建到 mysql了;
cursor.execute("USE test_db")
# cursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
cursor.execute("SHOW TABLES")
for x in cursor:
    print(x)

print("主键设置")

# 创建表的时候我们一般都会设置一个主键(PRIMARY KEY),我们可以使用 "INT AUTO_INCREMENT PRIMARY KEY" 语句来创建一个主键,主键起始值为 1,逐步递增。
# 如果我们的表已经创建,我们需要使用 ALTER TABLE 来给表添加主键:

# cursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
cursor.execute(sql, val)
# db.commit()
print(cursor.rowcount, "记录插入成功。")

# 批量插入 :批量插入使用 executemany() 方法,该方法的第二个参数是一个元组列表,包含了我们要插入的数据:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [("Peter", "Lowstreet 4"),
       ("Amy", "Apple st 652"),
       ("Hannah", "Mountain 21"),
       ("Michael", "Valley 345"),
       ("Sandy", "Ocean blvd 2"),
       ("Betty", "Green Grass 1"),
       ("Richard", "Sky st 331"),
       ("Susan", "One way 98"),
       ("Vicky", "Yellow Garden 2"),
       ("Ben", "Park Lane 38"),
       ("William", "Central st 954"),
       ("Chuck", "Main Road 989"),
       ("Viola", "Sideway 1633")
       ]
cursor.executemany(sql, val)
# db.commit()
print(cursor.rowcount, "记录插入成功。ID: ", cursor.lastrowid)

# 查询数据

cursor.execute("SELECT * FROM customers")
results = cursor.fetchall()
for x in results:
    print(x)

print("读取一条数据")
# 读取一条数据
# cursor.execute("SELECT * FROM customers")
# result = cursor.fetchone()
# print(result)
print("where,读取数据")
# where 条件语句
cursor.execute("SELECT * FROM customers WHERE name like '%o%'")
results_like = cursor.fetchall()
for x in results_like:
    print(x)

print("排序")
# 排序
cursor.execute("SELECT * FROM customers ORDER BY name")
my_result = cursor.fetchall()
for x in my_result:
    print(x)

print("Limit")
cursor.execute("SELECT * FROM customers ORDER BY name LIMIT 10 offset 4")  # 从第5条开始读取前 10 条记录:
like_result = cursor.fetchall()
for x in like_result:
    print(x)

# 删除记录 :为了防止数据库查询发生 SQL 注入的攻击,我们可以使用 %s 占位符来转义删除语句的条件:
cursor.execute("DELETE FROM customers WHERE id = %s", (3,))  # 注意:要慎重使用删除语句,删除语句要确保指定了 WHERE 条件语句,否则会导致整表数据被删除。
db.commit()
print(cursor.rowcount, "条记录被删除")

# 更新表数据
cursor.execute("UPDATE customers SET address = 'Canyon 123' WHERE name = 'Michael'")
db.commit()
print(cursor.rowcount, "条记录被修改")

# 删除表
cursor.execute("DROP TABLE customers")
db.close()
相关推荐
ClouGence1 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
数据智能老司机3 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机4 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i5 小时前
django中的FBV 和 CBV
python·django
c8i5 小时前
python中的闭包和装饰器
python
DemonAvenger8 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
这里有鱼汤8 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩18 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥20 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust