python操作数据库

66 阅读1分钟

1,安装数据库集成工具

数据库集成工具 - 掘金 (juejin.cn)

2,

pip install -i  https://pypi.tuna.tsinghua.edu.cn/simple mysql-connector-python

image.png

3,简单的增删改查

import mysql.connector

# 建立数据库连接
conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="test"
)
# 创建游标对象
cursor = conn.cursor()

# 建表语句
create_table = """
CREATE TABLE IF NOT EXISTS students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255),
  age INT,
  grade VARCHAR(255)
)
"""
cursor.execute(create_table)

# 插入数据
insert_data = "INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)"
student_data = [
    ("Alice", 20, "A"),
    ("Bob", 19, "B"),
    ("Charlie", 21, "A"),
]
cursor.executemany(insert_data, student_data)
conn.commit()

# 查询数据
select_data = "SELECT * FROM students"
cursor.execute(select_data)
result = cursor.fetchall()
print("查询结果:")
for row in result:
    print(row[1])

# 更新数据
update_data = "UPDATE students SET age = %s WHERE name = %s"
new_age = 22
name = "Alice"
cursor.execute(update_data, (new_age, name))
conn.commit()

# 查询更新后的数据
cursor.execute(select_data)
result = cursor.fetchall()
print("查询更新后的数据:")
for row in result:
    print(row)

# 删除数据
delete_data = "DELETE FROM students WHERE name = %s"
name = "Bob"
cursor.execute(delete_data, (name,))
conn.commit()

# 查询删除后的数据
cursor.execute(select_data)
result = cursor.fetchall()
print("查询删除后的数据:")
for row in result:
    print(row)

# 关闭游标和数据库连接
cursor.close()
conn.close()

image.png