一、 数据库操作
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)
修改数据
删除数据
删除表
二、代码演示
"""
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",
database="mysql"
)
print(db)
cursor = db.cursor()
cursor.execute("show databases")
for x in cursor:
print(x)
cursor.execute("USE test_db")
cursor.execute("SHOW TABLES")
for x in cursor:
print(x)
print("主键设置")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
cursor.execute(sql, val)
print(cursor.rowcount, "记录插入成功。")
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)
print(cursor.rowcount, "记录插入成功。ID: ", cursor.lastrowid)
cursor.execute("SELECT * FROM customers")
results = cursor.fetchall()
for x in results:
print(x)
print("读取一条数据")
print("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")
like_result = cursor.fetchall()
for x in like_result:
print(x)
cursor.execute("DELETE FROM customers WHERE id = %s", (3,))
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()