Home  >  Article  >  Backend Development  >  A practical guide to Python database operations: Make database operations your specialty

A practical guide to Python database operations: Make database operations your specialty

PHPz
PHPzforward
2024-02-20 09:33:03792browse

A practical guide to Python database operations: Make database operations your specialty

  1. Connect to the database
In

python, you can use third-party libraries such as pyMysql or psycopg2 to connect to the database. Taking pymysql as an example, the code to connect to the database is as follows:

import pymysql

# 创建连接对象
conn = pymysql.connect(
host="127.0.0.1",# 数据库主机地址
port=3306,# 数据库端口
user="root",# 数据库用户名
passWord="password",# 数据库密码
database="test",# 数据库名称
)

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

    Execute query
You can use the execute() method to execute query statements. For example, the code to query all user data is as follows:

cursor.execute("SELECT * FROM users")

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

# 遍历查询结果
for row in result:
print(row)

    Insert data
You can use the execute() method to insert data. For example, the code to insert a new user data is as follows:

cursor.execute("INSERT INTO users (name, age) VALUES ("张三", 20)")

# 提交事务
conn.commit()

    update data
You can use the execute() method to update data. For example, the code to update a user data is as follows:

cursor.execute("UPDATE users SET age = 21 WHERE name = "张三"")

# 提交事务
conn.commit()

    delete data
You can use the execute() method to delete data. For example, the code to delete a piece of user data is as follows:

cursor.execute("DELETE FROM users WHERE name = "张三"")

# 提交事务
conn.commit()

    Close connection
After the operation is completed, the connection object and cursor object need to be closed. code show as below:

cursor.close()
conn.close()

The above is the detailed content of A practical guide to Python database operations: Make database operations your specialty. 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