Home > Article > Backend Development > A practical guide to Python database operations: Make database operations your specialty
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()
cursor.execute("SELECT * FROM users") # 获取查询结果 result = cursor.fetchall() # 遍历查询结果 for row in result: print(row)
cursor.execute("INSERT INTO users (name, age) VALUES ("张三", 20)") # 提交事务 conn.commit()
cursor.execute("UPDATE users SET age = 21 WHERE name = "张三"") # 提交事务 conn.commit()
cursor.execute("DELETE FROM users WHERE name = "张三"") # 提交事务 conn.commit()
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!