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()
相关推荐
莫忘初心丶2 分钟前
python flask 使用教程 快速搭建一个 Web 应用
前端·python·flask
听封4 分钟前
✨ 索引有哪些缺点以及具体有哪些索引类型
数据库·mysql
利瑞华8 分钟前
数据库索引:缺点与类型全解析
数据库·oracle
V+zmm1013412 分钟前
自驾游拼团小程序的设计与实现(ssm论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计
ChinaRainbowSea23 分钟前
1. Linux下 MySQL 的详细安装与使用
linux·数据库·sql·mysql·adb
我是苏苏25 分钟前
C#基础:使用Linq进行简单去重处理(DinstinctBy/反射)
开发语言·c#·linq
小小码农(找工作版)26 分钟前
C#前端开发面试题
开发语言·c#
不爱学英文的码字机器33 分钟前
Python爬虫实战:从零到一构建数据采集系统
开发语言·爬虫·python
我是哈哈hh34 分钟前
【JavaScript进阶】作用域&解构&箭头函数
开发语言·前端·javascript·html
鹿鸣悠悠39 分钟前
Python 类和对象详解
开发语言·python