When using python to perform database operations, we often encounter some common errors and problems. These errors and problems not only affect the quality and operating efficiency of the code, but also make it difficult to debug and maintain. To help you avoid these problems, this article will provide some valuable tips and tricks to help you improve your database operational skills, thereby improving work efficiency and project quality.
import Mysql.connector # 建立数据库连接 connection = mysql.connector.connect(host="localhost", database="mydb", user="user", passWord="password") # 创建游标 cursor = connection.cursor() # 使用参数化查询来查询数据 sql = "SELECT * FROM users WHERE username=%s" param = ("john",) # 执行查询 cursor.execute(sql, param) # 获取查询结果 result = cursor.fetchall() # 打印查询结果 for row in result: print(row) # 关闭游标和数据库连接 cursor.close() connection.close()
with
statement to manage transactions. import mysql.connector # 建立数据库连接 connection = mysql.connector.connect(host="localhost", database="mydb", user="user", password="password") # 创建游标 cursor = connection.cursor() # 启动事务 cursor.start_transaction() try: # 执行SQL语句 sql = "UPDATE users SET balance=balance+100 WHERE username=%s" param = ("john",) cursor.execute(sql, param) # 提交事务 connection.commit() except: # 回滚事务 connection.rollback() # 关闭游标和数据库连接 cursor.close() connection.close()
ConnectionPool
class in the pymysql
library to create a connection pool. from pymysql import ConnectionPool # 创建连接池 connection_pool = ConnectionPool(host="localhost", database="mydb", user="user", password="password", max_connections=5) # 获取连接 connection = connection_pool.get_connection() # 创建游标 cursor = connection.cursor() # 执行SQL语句 sql = "SELECT * FROM users WHERE username=%s" param = ("john",) cursor.execute(sql, param) # 获取查询结果 result = cursor.fetchall() # 打印查询结果 for row in result: print(row) # 关闭游标和连接 cursor.close() connection.close()
sqlalchemy
library to use the ORM framework. from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # 创建引擎 engine = create_engine("mysql+pymysql://user:password@localhost/mydb") # 创建会话 Session = sessionmaker(bind=engine) session = Session() # 定义模型 Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) username = Column(String(20)) balance = Column(Integer) # 查询数据 user = session.query(User).filter_by(username="john").first() # 更新数据 user.balance += 100 session.commit() # 关闭会话 session.close()
mysqldump
command to back up the database. mysqldump -u user -p password mydb > backup.sql
The above is the detailed content of Shortcuts to Python database operations: avoid detours and reach the peak of database operations. For more information, please follow other related articles on the PHP Chinese website!