且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用连接字符串从python连接到mysql数据库

更新时间:2023-11-07 16:11:16

不能,MySQLdb.connect 只支持前一个选项.

You can't, MySQLdb.connect only supports the former option.

当然,您可以将连接字符串解析为其组成部分,并将其用作 .connect() 函数的一组关键字参数:

You can, of course, parse the connection string into it's constituents and use that as a set of keyword parameters for the .connect() function:

connectParams = dict(entry.split('=') for entry in connectString.split(';'))
mdb.connect(**connectParams)

然而,上面的拆分方法相当幼稚;您可能需要一个更复杂的方法来删除不支持的选项,转换某些参数值(想想 use_unicodeTrueFalse)并允许转义 ;= 字符,它们是参数值的一部分.请参阅.connect() 文档a> 用于支持的关键字参数.

The above splitting method is rather naive however; you probably would need a more sophisticated method that would remove unsupported options, convert certain parameter values (think use_unicode and True or False) and allow for escaping of ; and = characters where they are part of a parameter value. Refer to the .connect() documentation for supported keyword arguments.