如何使用 Ruby 的 DBI 创建数据库?
我正在开发一个小型 Ruby 应用程序,我希望它能够与 PostgreSQL 和 MySQL 一起使用。
Ruby/DBI 似乎是最直接的方法;我不想安装像ActiveRecord之类的重量级ORM。不幸的是,如果您已经有数据库,那么 Ruby/DBI 似乎可以让连接变得简单,但我不知道如何在没有数据库的情况下连接到服务器并发出 CREATE DATABASE 命令。
到目前为止,我有这个:
dbh = DBI.connect("DBI::Pg", "username", "password")
但当我尝试连接时出现此错误:无效的数据源名称
。知道我能做什么吗?
另外,如果我可以获得“无数据库句柄”,我想知道是否有一个 DBI 方法可以 select_db
并放入数据库中以执行进一步的查询。但这是次要的,没有它我也可以生活。
I'm developing a small Ruby application that I'd like to work with both PostgreSQL and MySQL.
It seems like Ruby/DBI is the most straightforward way to do this; I don't want to install a heavyweight ORM like ActiveRecord or something. Unfortunately, it seems like Ruby/DBI makes it simple to connect if you already have a database but I can't figure out how to connect to a server without a DB and issue the CREATE DATABASE
command.
So far I have this:
dbh = DBI.connect("DBI::Pg", "username", "password")
but I get this error when I try and connect: Invalid Data Source Name
. Any idea of what I can do?
Also, if I can get a 'databaseless handle' I was wondering if there was a DBI method to select_db
and drop into a database to execute further queries. That's secondary though and I can live without it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该有一个
postgres
数据库,以便您可以尝试:然后从那里执行您的
CREATE DATABASE
。另外,connect
应该是:其中,
Driver
是数据库驱动程序(区分大小写),database_conn_args
通常是数据库名称。You should have a
postgres
database so you could try:And then execute your
CREATE DATABASE
from there. Also, the first argument toconnect
is supposed to be:Where
Driver
is the database driver (case sensitive) anddatabase_conn_args
is usually the database name.