MySQL/Language/Import/export

Aside from mysqldump (cf. MySQL/Administration), you can also export / import raw data.

Export data edit

Data can be exported using the "INTO OUTFILE" keyword

 SELECT * FROM destinataire INTO OUTFILE '/tmp/test' WHERE id IN (41, 141, 260, 317, 735, 888, 1207, 2211);

Beware that the MySQL daemon itself will write the file, not the user you run the MySQL client with. The file will be stored on the server, not on your host. Moreover, the server will need write access to the path you specify (usually, the server can _not_ write in your home directory, e.g.). Hence why we (unsecurely) used /tmp in the examples.

You can also use the command line to export data

mysql < query.txt > output.txt

where query.txt contains an sql-query and the output will be stored in output.txt

Import data edit

In another database/computer/etc. the data can be imported:

 LOAD DATA INFILE '/tmp/test' INTO TABLE destinataire;

additional options are

 FIELDS TERMINATED BY '\t'
 LINES TERMINATED BY '\n'
 IGNORE 1 LINES

to specify how the document is set up and whether there is a header. The columns in the data file can be mapped to the columns of the database table if they do not correspond and it is thus also possible to omit certain columns using a dummy variable:

 LOAD DATA LOCAL INFILE
 '/tmp/test'
 INTO TABLE destinataire 
 FIELDS TERMINATED BY '\t'
 LINES TERMINATED BY '\n'
 IGNORE 1 LINES 
 ( 
 @dummy,
 name,
 phone_number,
 @dummy,
 @dummy,
 @dummy,
 @dummy,
 @dummy,
 @dummy,
 @dummy
 )

In this example, we only need the second and third column of the data file and store these values in the name and phone_number column of our database table.

Content precisions edit

To import a .sql which creates a user and its database, one should know if this user already exists on the server, because MySQL doesn't have any DROP USER IF EXISTS. On the contrary it works with the databases:

DROP DATABASE IF EXISTS `base1`;
CREATE DATABASE `base1` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `base1`;
--DROP USER `user1`@'localhost';
CREATE USER 'user1'@'localhost' IDENTIFIED BY 'p@ssword1';
GRANT USAGE ON *.* TO 'user1'@'localhost' IDENTIFIED BY 'p@ssword1';
GRANT ALL PRIVILEGES ON `base1`.* TO 'user1'@'localhost';

PS: if this commande returns "DROP DATABASE" statements are disabled with PhpMyAdmin, modify config.default.php by switching $cfg['AllowUserDropDatabase'] to true, and empty the navigator cache.