如何从 Perl MySQL DBI 句柄获取数据库名称?
我已使用 Perl DBI 连接到 MySQL 数据库。 我想知道我连接到哪个数据库。
我认为我不能使用:
$dbh->{Name}
因为我调用 USE new_database
和 $dbh->{Name}
仅报告我最初连接到的数据库。
有什么技巧或者我需要跟踪数据库名称吗?
I've connected to a MySQL database using Perl DBI. I would like to find out which database I'm connected to.
I don't think I can use:
$dbh->{Name}
because I call USE new_database
and $dbh->{Name}
only reports the database that I initially connected to.
Is there any trick or do I need to keep track of the database name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试只执行查询
据我所知,DBH 可以访问您最初连接的 DSN,但在您进行更改后就无法访问。 (可能有更好的方法来切换数据库。)
Try just executing the query
From what I could find, the DBH has access to the DSN that you initially connected with, but not after you made the change. (There's probably a better way to switch databases.)
$dbh->{Name}
从数据库句柄返回数据库名称。如果您在连接 dbh 后连接到另一个数据库,使用 mysql 查询“USE db_name”,并且您没有设置新的 perl DBI 数据库句柄,当然,$dbh->{Name} 将返回您之前连接的第一个数据库到...这不是自发的生成。
因此,要在设置数据库句柄后获取连接的数据库名称 - 对于 DBI mysql:
$dbh->{Name}
returns the db name from your db handle.If you connected to another db after connected with your dbh, using mysql query "USE db_name", and you did not setup a new perl DBI db handle, of course, $dbh->{Name} will return the first you previously connected to... It's not spontaneic generation.
So to get the connected db name once the db handle is set up - for DBI mysql:
你可以问mysql:
更新:显然 select DATABASE() 是一个更好的方法:)
You can ask mysql:
Update: obviously select DATABASE() is a better way to do it :)
当您创建连接对象时,它是针对某个数据库的。 无论如何,就 DBI 而言。 我不相信执行 SQL
USE database_name
根本不会影响您的连接实例。 也许连接对象有一个 select_db (我的 DBI 生锈了)函数,或者您必须为连接实例创建一个到新数据库的新连接才能正确报告它。When you create a connection object it is for a certain database. In DBI's case anyway. I I don't believe doing the SQL
USE database_name
will affect your connection instance at all. Maybe there is a select_db (My DBI is rusty) function for the connection object or you'll have to create a new connection to the new database for the connection instance to properly report it.FWIW - 可能不多 - DBD::Informix 跟踪当前数据库,如果您执行 CREATE DATABASE 等操作,该数据库可能会更改。
$dbh->{Name}
属性由 DBI 规范指定为建立句柄时使用的名称。 因此,有一个特定于 Informix 的属性$dbh->{ix_DatabaseName}
提供实际的当前数据库名称。 请参阅:perldoc DBD::Informix
。您可以考虑请求 DBD::MySQL 的维护者添加类似的属性。
FWIW - probably not much - DBD::Informix keeps track of the current database, which can change if you do operations such as CREATE DATABASE. The
$dbh->{Name}
attribute is specified by the DBI spec as the name used when the handle is established. Consequently, there is an Informix-specific attribute$dbh->{ix_DatabaseName}
that provides the actual current database name. See:perldoc DBD::Informix
.You could consider requesting the maintainer(s) of DBD::MySQL add a similar attribute.