Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a table from one mysql database to another mysql database

I need to copy a table from one database to another. This will be a cronjob. Which one is the best way to do it? PHP script or Shell Script. The problem with PHP, both databases has different usernames and passwords so I can't do it like this.

CREATE TABLE db1.table1 SELECT * FROM db2.table1 

Should I just connect first DB get all records and insert all to new database using WHILE loop or there is a better way?

I prefer a shell script to do this instead of PHP script.

Thanks

like image 724
Ergec Avatar asked Oct 14 '10 11:10

Ergec


People also ask

How do I copy a table from one database to another?

Steps that need to be followed are:Launch SQL Server Management Studio. Select and right-click on the Source Database, go to Tasks > Export Data. Import/Export Wizard will be opened and click on Next to proceed. Enter the data source, server name and select the authentication method and the source database.

How do I copy a table from one schema to another schema in MySQL?

1) Use the ALTER TABLE ... RENAME command and parameter to move the table to the target schema. 2) Use the CREATE TABLE ... CLONE command and parameter to clone the table in the target schema.

How do I move from one database to another in MySQL?

Change or switch DATABASE in MySQL To change or switch DATABASE, run the same USE database_name query with the new database name that you wish to work on. In the example shown above, USE db3; changes the database, from db2 to db3, on which your SQL queries effect on.


2 Answers

If you need to copy the table on the same server you can use this code:

USE db2;  CREATE TABLE table2 LIKE db1.table1;  INSERT INTO table2       SELECT * FROM db1.table1; 

It's copy+pasted from here: codingforums.com

It's not my solution, but I find it useful.

like image 181
Radu Damian Avatar answered Oct 04 '22 07:10

Radu Damian


I'd dump it. Much less complicated than anything PHP based.

mysqldump -u user1 -ppassword1 databasename > dump.sql mysql -u user2 -ppassword2 databasename < dump.sql 

MySQL reference: 4.5.4. mysqldump — A Database Backup Program

like image 40
Pekka Avatar answered Oct 04 '22 07:10

Pekka