sql,CREATE DATABASE my_database;,USE my_database;,,CREATE TABLE users (, id INT AUTO_INCREMENT PRIMARY KEY,, username VARCHAR(50) NOT NULL,, email VARCHAR(100) NOT NULL,, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,);,
``sql,CREATE DATABASE my_database;,USE my_database;,,CREATE TABLE users (, id INT AUTO_INCREMENT PRIMARY KEY,, username VARCHAR(50) NOT NULL,, email VARCHAR(100) NOT NULL,, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,);,
``python,# 导入数据库连接模块,import sqlite3,,# 连接到SQLite数据库,conn = sqlite3.connect('example.db'),cursor = conn.cursor(),,# 开始一个事务,conn.execute("BEGIN TRANSACTION;"),,try:, # 执行一些数据库操作, cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)"), cursor.execute("UPDATE accounts SET balance = balance 100 WHERE user_id = 1"), cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE user_id = 2"),, # 提交事务, conn.commit(),except Exception as e:, # 如果发生错误,回滚事务, conn.rollback(), print(f"An error occurred: {e}"),finally:, # 关闭连接, conn.close(),
``,,这段代码演示了如何在Python中使用SQLite库创建一个数据库事务,包括开始事务、执行操作、提交或回滚事务以及关闭连接。你可以根据需要修改数据库操作部分。Powered By Z-BlogPHP 1.7.3