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

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

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

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

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

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

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

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!

Related labels:
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