【问题标题】:Connect to MySQL database via dplyr using stored credentials使用存储的凭据通过 dplyr 连接到 MySQL 数据库
【发布时间】:2016-02-10 12:17:05
【问题描述】:

我想使用dplyr 访问 MySQL 数据库,而不必将我的数据库密码存储在平面文本 R 代码中。因此,我更愿意参考我的.my.cnf 文件,但由于 src_mysql 具有主机、用户和密码的默认参数,我能找到的唯一方法是通过相当不优雅的方法:

test_db <- src_mysql("test",
                     default.file=path.expand("~/.my.cnf"),
                     host=NULL,
                     user=NULL,
                     password=NULL)

有没有更简洁的方法通过存储的凭据从dplyr 连接到 MySQL 数据库?

【问题讨论】:

    标签: r dplyr rmysql


    【解决方案1】:

    从 Hadley 对 pull request(2014 年 2 月,要求修改代码以允许阅读 my.cnf)和 documentation by Hadley(他建议使用 my.cnf 并且您应该传递 NULL 值)的回应看来传递 NULL 是期望的意图。

    如果这很麻烦,请考虑在您的 .Rprofile 中使用以下内容:

    src_mysql_from_cnf <- function(dbname,
                          dir="~/.my.cnf",
                          host=NULL,
                          user=NULL,
                          password=NULL,
                          ...) {
        if(!(file.exists(dir)))
            stop(sprintf("No such file '%s'",dir))
        dplyr::src_mysql(
            dbname,
            default.file=path.expand(dir),
            # explicitly passing null unless otherwise specified.
            host=host,
            user=user,
            password=password,
            ...)
    }
    

    那么你就可以了

    test_db <- src_mysql_from_cnf("test")
    

    【讨论】:

    • 您正在创建一个函数src_mysql,但在您的示例中将其称为src_mysql_from_cnf。不过我明白了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 2023-04-11
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多