Home > Backend Development > Python Tutorial > 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
Release: 2024-02-19 14:03:33
forward
931 people have browsed it

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()
Copy after login

2. Execute SQL query statement

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

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

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

3. Insert data

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

# 提交事务
db.commit()
Copy after login

4. Update data

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

# 提交事务
db.commit()
Copy after login

5. Delete data

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

# 提交事务
db.commit()
Copy after login

6. Close the database connection

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

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

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!

source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template