tag (mysql)

archive

create/export and load/import csv files with mysqldump in mysql May
27
1
0

I'm often asked to create csv files to import into other applications. If you're using MySQL it's handy to be able to create a CSV on the fly with mysqldump. This is easily achieved with the following command:

mysqldump -u <user> -p --tab=<directory> --fields-enclosed-by='"' --fields-terminated-by=',' <database> <table>

This creates a .sql dump file and a .txt csv in the directory that you specified with [--tab]. The second part of this operation (the .txt csv creation) will be performed by the MySQL user, so it'll need to have write permissions in the [--tab] directory. Also, the mysql user needs to have the appropriate permissions (I believe it's the FILE privileges).

Alternatively you can import a csv into the database with the following command while logged into the mysql shell using the appropriate database:

LOAD DATA LOCAL INFILE '/path/to/my.csv' INTO TABLE <table>
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(<field1>, <field2>, <field3>);

comments

mysql cheatsheet Mar
22
1
0

Here's some of the MySQL commands that I regularly use. I'm posting this so I have a place to quickly look these up, but perhaps someone else might find these useful as well.

# login
mysql -u root -p

USE database_name;
SHOW tables;
DESCRIBE table_name 

# create database
CREATE DATABASE django_project;
SHOW DATABASES;

# create user
CREATE USER username IDENTIFIED BY 'pass1';

# grant access
GRANT ALL ON django_project.* TO username;

# Export A MySQL Database
mysqldump -u username -p database_name > FILE.sql
mysqldump --user=XXXXXXXX --password=XXXXXXX -A > /PATH/TO/DUMPFILE.SQL
mysqldump --user=XXXXXXXX --password=XXXXXXX DB_NAME1 DB_NAME2 > /PATH/TO/DUMPFILE.SQL
mysqldump --user=XXXXXXXX --password=XXXXXXXX DB_NAME --tables TABLE_NAME > /PATH/TO/DUMPFILE.SQL

# Import A MySQL Database
mysql -u username -p database_name < FILE.sql
mysql --verbose --user=XXXXXXXX --password=XXXXXXXX DB_NAME < /PATH/TO/DUMPFILE.SQL

LOAD DATA LOCAL INFILE '/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, filed2, field3);

# duplicate table
CREATE TABLE newname SELECT * FROM sourcename

# alter table
ALTER TABLE profiles_category ASS header varchar(100) NOT NULL AFTER icon;
ALTER TABLE profiles_category MODIFY icon varchar(100) NOT NULL; modify attributes
ALTER TABLE profiles_category CHANGE icon image varchar(100) NOT NULL;    rename
ALTER TABLE profiles_category DROP icon;

# update table
UPDATE profiles_category SET header='name' WHERE id=1;

comments