[英]How to automatically create table and structure for a database using XML in Cakephp
[英]How to Create a MySQL Table Structure in a different database using PHP
我有2個獨立的和不同的數據庫:
我試圖使用PHP而不是phpMyAdmin將表從SOURCE_DATABASE復制到TARGET_DATABASE(因為它在phpMyAdmin中工作正常)。
我有以下PHP:
$linkSource = mysql_connect( SERVER, SOURCE_USERNAME, SOURCE_PASSWORD );
mysql_select_db( SOURCE_DATABASE, $linkSource );
$linkTarget = mysql_connect( SERVER, TARGET_USERNAME, TARGET_PASSWORD );
mysql_select_db( TARGET_DATABASE, $linkTarget );
mysql_query( 'CREATE TABLE `targetDB.targetTable` LIKE `sourceDB.sourceTable` ) or die( mysql_error() );
是否可以使用第一個數據庫(源)中的表結構在第二個數據庫(目標)中創建表?
PhpMyAdmin和PHP是用於此目的的錯誤工具。 使用命令行shell。 像這樣的東西:
mysqldump -u root -p database1 > database1.sql
mysql -u root -p database < database1.sql
它的工作速度要快10倍,我保證。 此外,數據庫將關注數據一致性而不是您。
如果您真的想在PHP中使用它,請使用php命令行shell 。
如果您仍然希望在PHP WITHOUT命令行shell中執行此操作,我可以建議執行此類操作:
$query = "show tables from source_database";
$tables = $dbSource->getColumn($query)//get one column from database
foreach($tables as $tableName) {
$query = "show create table ".$tableName;//← it will return query to clone table structure
$createTableSchema = $dbSource->getRow($query);//← get assoc array of one row
$dbTarget->query($createTableSchema['Create Table']);//← here is your silver bullet
}
PS以及當(如果)將數據從一個表復制到另一個表時,您應該知道該語句
insert into table () values (values1), (values2), (values3);
比...快得多
insert into table () values (values1);
insert into table () values (values2);
insert into table () values (values3);
但是插入multy行與max_allowed_packet
propery字段有關。 如果你的查詢比這個字段更大(是的,查詢字符串可以分配1GB的內存),MySQL將拋出異常。 因此,要構建Insert multy查詢,您應該獲取max_allowed_packet
並根據此大小生成此查詢。 此外,為了加快性能,您可以從目標表中disable keys
。 (別忘了enable keys
,哈哈)
您可以使用MySQL的“SHOW CREATE TABLE”函數來獲取源表的結構,然后執行它在目標連接中為您提供的CREATE TABLE語句。
$result = mysql_query("SHOW CREATE TABLE sourceTable", $linkSource);
$create_table = mysql_result($result, 0, 1);
mysql_query($create_table, $linkTarget);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.