php 在 PDO 中的多个数据库之间切换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9588775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Switch between multiple database in PDO
提问by hablema
I'm new to PDO. I would like to know if there is anything similar to mysql_select_db in PDO, so that i can switch between different databases during runtime without the need for creating a new object.
我是 PDO 的新手。我想知道 PDO 中是否有类似于 mysql_select_db 的东西,以便我可以在运行时在不同的数据库之间切换,而无需创建新对象。
采纳答案by Ing
There is not, you will need to create two PDO objects for the separate connections if you would like to use both at runtime.
没有,如果您想在运行时同时使用这两个对象,则需要为单独的连接创建两个 PDO 对象。
Edit: Interesting point by @laz below (which I'm guessing is the cause of negative votes on my answer). I was thinking under the assumption that the databases were on separate servers tbh, in which case my answer stands.
编辑:下面@laz 的有趣观点(我猜这是对我的答案投反对票的原因)。我在考虑数据库位于不同的服务器 tbh 的假设下,在这种情况下,我的答案成立。
回答by Laz
I know that I am a couple of months late but you should be able to switch between databases from within your query.
我知道我迟到了几个月,但您应该能够从查询中在数据库之间切换。
examples:
例子:
$sql = "SELECT * FROM dbname.tablename";
$sql = "SELECT * FROM anotherdbname.anothertablename"
So even if your original $pdo object was used 'blahblah' as the dbname, you should still be okay based on the select examples I provided.
因此,即使您的原始 $pdo 对象被用作 'blahblah' 作为 dbname,根据我提供的选择示例,您仍然应该没问题。
回答by BlindAndFurious
It looks like PDO does not have database switching because not every database engine supports it.
看起来 PDO 没有数据库切换,因为不是每个数据库引擎都支持它。
AFAIK PostgreSQL does not have database switching, but offer schemas and u can switch between those.
AFAIK PostgreSQL 没有数据库切换,但提供模式,你可以在这些模式之间切换。
However if you're using mysql check if this works for you:
但是,如果您使用的是 mysql,请检查这是否适合您:
$pdo = new PDO('mysql:dbname=db1;host=127.0.0.1','user','pass');
$sql = 'select count(*) from table_name';
$res = $pdo->query($sql);
print_r($res->fetchAll());
$pdo->exec('USE db2');
$res = $pdo->query($sql);
print_r($res->fetchAll());
回答by Matthew
You actually do not need to specify the database upon connection at all. As long as you specify the database in every query, as Laz stated, this will work:
您实际上根本不需要在连接时指定数据库。只要您在每个查询中指定数据库,正如 Laz 所说,这将起作用:
$dbh = new PDO('mysql:host=127.0.0.1','USER','PASS');
$query = "SELECT * FROM database1.table1";
$query = "SELECT * FROM database2.table1";
回答by shotex
you don't even need to specify the database in every query, just use msyql syntax
您甚至不需要在每个查询中指定数据库,只需使用 msyql 语法
USE db_name
and then write your requests
然后写下你的请求