首先,需要使用 pip 安装 PyMySQL 库:
pip install pymysql 使用 PyMySQL.connect() 方法可以建立到 MySQL 数据库的连接:
import pymysql # 配置数据库连接参数 config = { 'host': 'localhost', # 数据库服务器地址 'port': 3306, # 数据库服务器端口 'user': 'your_username', # 数据库用户名 'password': 'your_password', # 数据库密码 'database': 'your_database', # 要操作的数据库名 'charset': 'utf8mb4' # 使用的字符集 } # 建立连接 connection = pymysql.connect(**config) 游标(Cursor)用于执行 SQL 语句和获取查询结果:
# 创建游标对象 cursor = connection.cursor() 使用游标的 execute() 方法可以执行 SQL 语句:
# 执行查询语句 cursor.execute("SELECT * FROM your_table") # 获取所有查询结果 results = cursor.fetchall() for row in results: print(row) # 执行非查询语句(如 INSERT、UPDATE、DELETE) cursor.execute("INSERT INTO your_table (column1, column2) VALUES (value1, value2)") 对于非查询类的 SQL 语句,需要提交事务以确保更改生效:
connection.commit() 使用 try...except 语句来处理可能发生的异常:
try: # 尝试执行一些操作 pass except pymysql.MySQLError as e: print(e) connection.rollback() # 发生错误时回滚事务 finally: cursor.close() # 关闭游标 connection.close() # 关闭连接 操作完成后,应关闭游标和数据库连接:
cursor.close() connection.close() 下面是一个使用 PyMySQL 执行查询和插入操作的完整示例:
import pymysql # 配置数据库连接参数 config = { 'host': 'localhost', 'port': 3306, 'user': 'your_username', 'password': 'your_password', 'database': 'your_database', 'charset': 'utf8mb4' } # 建立连接 connection = pymysql.connect(**config) try: # 创建游标对象 with connection.cursor() as cursor: # 执行查询 cursor.execute("SELECT * FROM your_table") print("Query results:", cursor.fetchall()) # 执行插入操作 cursor.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s)", ('value1', 'value2')) # 提交事务 connection.commit() except pymysql.MySQLError as e: print("Error: ", e) connection.rollback() finally: # 关闭连接 connection.close() 请注意,上述示例中的 'your_username', 'your_password', 'your_database' 和 'your_table' 需要替换为实际的数据库登录信息和表名。
上一篇:Animate.css的使用
下一篇:ftp服务器怎么登出_登出