9.1
本周主要是对数据库的学习
数据库表
一个数据库通常包含一个或多个表。每个表有一个名字标识(例如:"Websites"),表包含带有数据的记录(行)。
在本教程中,我们在 MySQL 的 RUNOOB 数据库中创建了 Websites 表,用于存储网站记录。
我们可以通过以下命令查看 "Websites" 表的数据:
mysql> use RUNOOB;
Database changed
mysql> set names utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM Websites;
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | 菜鸟教程 | http://www.runoob.com/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
+----+--------------+---------------------------+-------+---------+
5 rows in set (0.01 sec)
解析
- use RUNOOB; 命令用于选择数据库。
- set names utf8; 命令用于设置使用的字符集。
- SELECT * FROM Websites; 读取数据表的信息。
- 上面的表包含五条记录(每一条对应一个网站信息)和5个列(id、name、url、alexa 和country)。
SQL 语句
您需要在数据库上执行的大部分工作都由 SQL 语句完成。
下面的 SQL 语句从 "Websites" 表中选取所有记录:
实例
import mysql.connector
# 连接到数据库
conn = mysql.connector.connect(user='username', password='password', host='localhost', database='mydatabase')
# 创建游标对象
cursor = conn.cursor()
try:
# 开始事务
cursor.execute("START TRANSACTION")
# 执行一系列操作
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE account_id = 1") -- 转出账户减去100元
cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE account_id = 2") -- 转入账户加上100元
# 提交事务
cursor.execute("COMMIT")
except Exception as e:
# 发生异常时回滚事务
print("An error occurred:", e)
cursor.execute("ROLLBACK") //回滚事务 ROLLBACK 这样可以撤销之前的所有操作,包括第一个UPDATE语句的修改,从而保证数据的一致性。
finally:
# 关闭游标和连接
cursor.close()
conn.close()
浙公网安备 33010602011771号