板凳-------Mysql cookbook学习 (六)
2025年Pytorch-gpu版本安装(各种情况适用自己的安装需求,亲测绝对有效,示例安装torch2.6.0,过程详细面向小白)_torch gpu版本-CSDN博客
https://blog.csdn.net/OpenSeek/article/details/145795127
2.2 查错
import sys
import MySQLdb
try:conn = MySQLdb.connect (db = "cookbook",host = "localhost",user = "cbuser", passwd = "cbpass")print ("Connected")
except MySQLdb.Error as e:print ("Cannot connect to server")print ("Error code:", e.args[0])print ("Error message:", e.args[1])sys.exit(1)conn.close()
print ("Disconnected")
import sys
import MySQLdbtry:conn = MySQLdb.connect(db="cookbook",host="localhost",user="cbuser",passwd="cbpass")print("Connected")
except MySQLdb.Error as e:print(f"Connection failed: Error {e.args[0]} ({e.args[1]})")sys.exit(1)
finally:if 'conn' in locals():conn.close()
print("Disconnected")
以下是你的 Python 脚本的逐行分析及常见问题解决方案:
代码功能
尝试连接 MySQL 数据库 cookbook,若成功则关闭连接,若失败则输出错误信息。
常见错误及解决方案
1. MySQL 服务未启动
• 现象:抛出 Can't connect to MySQL server on 'localhost' 错误。
• 解决:
o Windows:打开服务管理器(services.msc),启动 MySQL 服务。
o Linux/macOS:运行 sudo systemctl start mysql。
2. 数据库凭证错误
• 现象:抛出 Access denied for user 'cbuser'@'localhost' 错误。
• 解决:
1. 确认数据库名、用户名、密码是否正确。
2. 使用命令行测试连接:
bash
复制
mysql -u cbuser -p cbpass cookbook
3. 如果密码错误,重置密码:
sql
复制
ALTER USER 'cbuser'@'localhost' IDENTIFIED BY 'new_password';
3. 用户权限不足
• 现象:抛出 Host 'localhost' is not allowed to connect 错误。
• 解决:授予用户权限:
sql
复制
GRANT ALL PRIVILEGES ON cookbook.* TO 'cbuser'@'localhost' IDENTIFIED BY 'cbpass';
FLUSH PRIVILEGES;
4. MySQLdb 库未正确安装
• 现象:抛出 ModuleNotFoundError: No module named 'MySQLdb'。
• 解决:
o Python 3:安装 mysqlclient:
bash
复制
pip install mysqlclient
o Windows:需安装 MySQL Connector/C 并确保环境变量包含 libmysql.dll。
5. 连接参数错误
• 现象:抛出 Unknown MySQL server host 或 Can't connect to local MySQL server。
• 解决:
o 检查 host 是否为 localhost 或 127.0.0.1。
o 指定端口(默认 3306):
python
复制
conn = MySQLdb.connect(db="cookbook",host="localhost",port=3306,user="cbuser",passwd="cbpass"
)
调试建议
1. 打印完整错误信息:修改异常捕获代码,输出详细错误:
python
复制
except MySQLdb.Error as e:print(f"Error {e.args[0]}: {e.args[1]}")
2. 手动测试连接:用命令行工具验证数据库是否可达:
bash
复制
mysql -h localhost -u cbuser -p cbpass cookbook
3. 检查防火墙:确保本地防火墙未阻止 MySQL 端口(默认 3306)。
________________________________________
修正后的代码
python
复制
import sys
import MySQLdbtry:conn = MySQLdb.connect(db="cookbook",host="localhost",user="cbuser",passwd="cbpass")print("Connected")
except MySQLdb.Error as e:print(f"Connection failed: Error {e.args[0]} ({e.args[1]})")sys.exit(1)
finally:if 'conn' in locals():conn.close()print("Disconnected")
________________________________________
关键检查点
问题类型 检查方法
MySQL 服务状态 sudo systemctl status mysql
用户权限 SHOW GRANTS FOR 'cbuser'@'localhost';
密码正确性 mysql -u cbuser -p
Python 库安装 pip show mysqlclient
从你的 pip3 show torch 输出可以看出,当前安装的 PyTorch 版本为 1.13.1+cpu,而 Hugging Face Transformers 库要求 PyTorch ≥ 2.6。以下是针对 Windows 系统和 Conda 环境的完整解决方案:
1. 升级 PyTorch 到 2.6+
步骤 1:卸载旧版本 PyTorch
在终端中运行以下命令(以管理员身份运行):pip uninstall torch torchvision torchaudio -y
步骤 2:通过 Conda 安装 PyTorch 2.6+(CPU 版本)
由于你使用的是 Conda 环境,建议通过 Conda 安装以解决依赖冲突:conda activate myenv # 激活你的 Conda 环境(如 base)
conda install pytorch=2.6 torchvision torchaudio cpuonly -c pytorch -c conda-forge
(无法安装!!!!)
1. 更换国内镜像源加速
步骤 1:配置清华镜像源
在终端中运行以下命令:conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --set show_channel_urls yes
步骤 2:清除缓存
conda clean -i
2. 使用 Mamba 加速依赖解析
Mamba 是 Conda 的替代工具,依赖解析速度更快:步骤 1:安装 Mamba
conda install -n base -c conda-forge mamba
步骤 2:通过 Mamba 安装 PyTorch
mamba install pytorch=2.6 torchvision torchaudio cpuonly -c pytorch -c conda-forge
3. 创建干净的 Conda 环境
如果现有环境存在依赖冲突,新建一个环境:conda create -n pytorch26 python=3.10
conda activate pytorch26
conda install pytorch=2.6 torchvision torchaudio cpuonly -c pytorch -c conda-forge
4. 分步安装依赖(备用方案)
如果自动安装失败,手动指定依赖版本:conda install numpy=1.24.3 typing-extensions=4.7.1
conda install pytorch=2.6 torchvision=0.17.0 torchaudio=2.0.0 cpuonly -c pytorch
5. 验证安装
安装完成后运行以下命令:python -c "import torch; print(torch.__version__)" # 应输出 2.6.0+C:\Users\lenovo>pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
Successfully installed torch-1.13.1+cpu torchaudio-0.13.1+cpu torchvision-0.14.1+cpu
2.3 编写库文件如何将公共操作代码放入库文件中。假设不想将库文件被语言处理器默认搜索的目录是放在windows 下使用c:\lib\mcb
%run c:/lib/mcb/connect.pyConnected
Disconnected
封装(或模块化)并不是一个“解决文案”而是一项编程技术。不用再在每个程序里重复编写相同的代码。仅调用库中的一个行程序,程序都可以在recipes发行包的lib 目录下找到。
通过调用库里面的程序编写连接到数据库的程序,只需要做出变化的位置局部化:仅需要修改受影响的库程序。
代码封装提升安全性。
库文件自身并不能独立使用,都是通过一个简短的“test harness”程序来说明的。拷贝一份文件在connect 和disconnect 调用之间加入你自己的代码。
Cell 1: Run the script using %run
%run c:/lib/mcb/Cookbook.py
#! c:/lib/mcb/Cookbook.py
Cell 2: Use the loaded function
import sys
import MySQLdbtry:conn = connect()print("Connected to database")
except MySQLdb.Error as e:print(f"Connection failed: Error {e.args[0]} ({e.args[1]})")sys.exit(1)
finally:if 'conn' in locals():conn.close()print("Disconnected")
Connected to database
Disconnected
2.4 发起语句并检索结果
mysql> select * from profile;
+----+---------+------------+-------+-----------------------+------+
| id | name | birth | color | foods | cats |
+----+---------+------------+-------+-----------------------+------+
| 1 | Fred | 1970-04-13 | black | lutefisk,fadge,pizza | 0 |
| 2 | Mort | 1969-09-30 | white | burrito,curry,eggroll | 3 |
| 3 | Brit | 1957-12-01 | red | burrito,curry,pizza | 1 |
| 4 | Carl | 1973-11-02 | red | eggroll,pizza | 4 |
| 5 | Sean | 1963-07-04 | blue | burrito,curry | 5 |
| 6 | Alan | 1965-02-14 | red | curry,fadge | 1 |
| 7 | Mara | 1968-09-17 | green | lutefisk,fadge | 1 |
| 8 | Shepard | 1975-09-02 | black | curry,pizza | 2 |
| 9 | Dick | 1952-08-20 | green | lutefisk,fadge | 0 |
| 10 | Tony | 1960-05-01 | white | burrito,pizza | 0 |
| 11 | Alison | 1973-01-12 | blue | eggroll | 4 |
| 12 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 13 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 14 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 15 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 16 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 17 | Amabel | NULL | NULL | NULL | NULL |
+----+---------+------------+-------+-----------------------+------+
17 rows in set (0.01 sec)
mysql> update profile set cats = cats + 1 where name = 'Fred'-> ;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from profile;
+----+---------+------------+-------+-----------------------+------+
| id | name | birth | color | foods | cats |
+----+---------+------------+-------+-----------------------+------+
| 1 | Fred | 1970-04-13 | black | lutefisk,fadge,pizza | 1 |
| 2 | Mort | 1969-09-30 | white | burrito,curry,eggroll | 3 |
| 3 | Brit | 1957-12-01 | red | burrito,curry,pizza | 1 |
| 4 | Carl | 1973-11-02 | red | eggroll,pizza | 4 |
| 5 | Sean | 1963-07-04 | blue | burrito,curry | 5 |
| 6 | Alan | 1965-02-14 | red | curry,fadge | 1 |
| 7 | Mara | 1968-09-17 | green | lutefisk,fadge | 1 |
| 8 | Shepard | 1975-09-02 | black | curry,pizza | 2 |
| 9 | Dick | 1952-08-20 | green | lutefisk,fadge | 0 |
| 10 | Tony | 1960-05-01 | white | burrito,pizza | 0 |
| 11 | Alison | 1973-01-12 | blue | eggroll | 4 |
| 12 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 13 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 14 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 15 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 16 | De'Mont | 1973-01-12 | NULL | eggroll | 4 |
| 17 | Amabel | NULL | NULL | NULL | NULL |
+----+---------+------------+-------+-----------------------+------+
17 rows in set (0.00 sec)
SQL 语句分两大类:
不返回结果集的语句。包括 insert, delect and update.这类语句通常以某种方式改变了数据库。
返回结果集的语句。 例如 select, show explain and describe.
Python 处理一个语句, 用数据库连接对象获得一个游标对象,使用游标的execute()方法向服务器发送语句。
cursor = conn.cursor()
cursor.execute("update profile set cats = cats + 1 where name = 'Fred'")
print("Number of rows updated: %d " % cursor.rowcount)
Number of rows updated: 1
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile") # 修正 SQL 语句(移除多余的单引号)while True: # 更规范的写法row = cursor.fetchone()if row is None: # 删除分号,使用 is None 更规范breakprint("id: %s, name: %s, cats: %s" % (row[0], row[1], row[2]))
print("Number of rows returned: %d " % cursor.rowcount)
cursor.close()
id: 1, name: Fred, cats: 1
id: 2, name: Mort, cats: 3
id: 3, name: Brit, cats: 1
id: 4, name: Carl, cats: 4
id: 5, name: Sean, cats: 5
id: 6, name: Alan, cats: 1
id: 7, name: Mara, cats: 1
id: 8, name: Shepard, cats: 2
id: 9, name: Dick, cats: 0
id: 10, name: Tony, cats: 0
id: 11, name: Alison, cats: 4
id: 12, name: De'Mont, cats: 4
id: 13, name: De'Mont, cats: 4
id: 14, name: De'Mont, cats: 4
id: 15, name: De'Mont, cats: 4
id: 16, name: De'Mont, cats: 4
id: 17, name: Amabel, cats: None
Number of rows returned: 17
从错误信息来看,你的代码中存在 语法错误:在 if row == None 后误加了分号 ;。以下是修正后的代码:
关键修正点
1. 删除多余的分号:
原代码中 if row == None; 的分号 ; 导致语法错误,Python 中 if 条件后不需要分号。
2. 优化 SQL 语句:
修正 SQL 中的冗余单引号(profile' → profile),避免语法错误。
3. 更规范的循环写法:
将 while 1 改为 while True,提高代码可读性。
4. 使用 is None 替代 == None:
在 Python 中,判断 None 更推荐使用 is None。
________________________________________
完整代码解释
代码行 作用
cursor.execute(...) 执行 SQL 查询,获取 profile 表中的 id, name, cats 字段
while True 无限循环,直到 fetchone() 返回 None(无更多数据)
row = cursor.fetchone() 逐行获取查询结果
if row is None: break 如果没有更多数据,退出循环
print(...) 格式化输出查询结果
cursor.rowcount 获取受影响的行数(此处为查询结果的行数)
另一个行获取 方法fetchall()以一个行序列的方式返回整个结果集。
cursor = conn.cursor()
cursor.execute("SELECT id, name, cats FROM profile") # 修正 SQL 语句(移除多余的单引号)
rows = cursor.fetchall()
for row in rows:print("id: %s, name: %s, cats: %s" % (row[0], row[1], row[2]))
print("Number of rows returned: %d " % cursor.rowcount)
cursor.close()
结果同上
通过访问列名来访问行值,创建游标对象时指定DictCursor游标类型,
这使得行作为命名元素的Python字典对象返回
确保正确导入 DictCursor
from MySQLdb.cursors import DictCursor
创建 DictCursor
cursor = conn.cursor(DictCursor)
cursor.execute(“SELECT id, name, cats FROM profile”)
修复变量名:循环变量应为 row,而非 rows
for row in cursor.fetchall():# 使用字典键访问字段print("id: %s, name: %s, cats: %s" % (row["id"], row["name"], row["cats"]))print("Number of rows returned: %d " % cursor.rowcount)
cursor.close()
结果同上
2.5 处理语句中的特殊字符和null值 133/951 Saturday, May 24, 2025