Home  >  Article  >  Backend Development  >  A complete guide to Python database operations: let the data play music for you

A complete guide to Python database operations: let the data play music for you

WBOY
WBOYforward
2024-02-19 14:03:33886browse

A complete guide to Python database operations: let the data play music for you

1. Establish a database connection

import pyMysql

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", passWord="123456", database="test")

# 创建游标对象
cursor = db.cursor()

2. Execute SQL query statement

# 执行查询语句
sql = "SELECT * FROM user"
cursor.execute(sql)

# 获取查询结果
results = cursor.fetchall()

# 遍历结果并打印
for row in results:
print(row)

3. Insert data

# 插入数据
sql = "INSERT INTO user (name, age) VALUES (%s, %s)"
cursor.execute(sql, ("John", 25))

# 提交事务
db.commit()

4. Update data

# 更新数据
sql = "UPDATE user SET age = %s WHERE name = %s"
cursor.execute(sql, (26, "John"))

# 提交事务
db.commit()

5. Delete data

# 删除数据
sql = "DELETE FROM user WHERE name = %s"
cursor.execute(sql, ("John",))

# 提交事务
db.commit()

6. Close the database connection

# 关闭游标对象
cursor.close()

# 关闭数据库连接
db.close()

Conclusion:

pythonDatabase operation is an art and a science. Master this art, and you will be like a skilled conductor, leading the data to play a beautiful movement. In the world of Python, data are no longer cold numbers, but lively notes, waiting for you to use code to touch their heartstrings. Let us work together to compose a data symphony using Python code, and let the data play a beautiful melody for you!

The above is the detailed content of A complete guide to Python database operations: let the data play music for you. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete