首页 > 解决方案 > 使用 optuna 从 python 成功访问 MySQL 数据库

问题描述

由于optuna文档没有说明 MySQL 需要哪些模块,因此我在我的 Windows 10 机器上安装了 MySQL 的所有内容。我在我的 PC 上查找了 MySQL(安装过程中没有显示安装发生在哪个文件夹中)并将 Path 变量更新为

C:\Program Files\MySQL\MySQL 服务器 8.0\bin

我已经成功创建了mysqltestexample数据库。

在此处输入图像描述

使用 python SQL 连接器,我可以使用以下命令重现输出:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="Start123"
)

print(mydb)


mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
  print(x) 

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="Start123",
  database="mysqltesteexample"
) 

连接到mysqltesteexample不会引发错误 - 所以一切似乎都很好。但是,optuna无法连接到我的数据库

我的 python 脚本看起来像这样。这是optuna文档中的代码,我只是更改了测试数据库的名称。

study0 = optuna.create_study(storage="mysql://root@localhost/mysqltesteexample",study_name="distributed-example")
study0 = optuna.create_study(storage="mysql+pymysql://root:Start123@localhost:3306/mysqltesteexample",study_name="distributed-example")

根据https://docs.sqlalchemy.org/en/14/core/engines.html修改 URL 字符串的所有尝试都失败并出现以下错误:ImportError: Failed to import DB access module for the specified storage URL. Please install appropriate one. 您能帮我完成吗?提前谢谢你,请不要太苛刻。

标签: pythonmysql

解决方案


最后,我做到了。我必须从 cmd 安装一些进一步的软件包:

py -3.8 -m easy_install mysql-python
py -3.8 -m pip install mysqlclient

Python 包 - 有据可查,因为它们令人眼花缭乱


推荐阅读