MySQL Tutorial
MySQL Installation and Configuration
MySQL Database Operations
Database Design
MySQL Data Types
MySQL Storage Engines
MySQL Basic Operations of Tables
MySQL Constraints
MySQL Operators
MySQL Function
MySQL Manipulate Table Data
MySQL View
MySQL Indexes
MySQL Stored Procedure
MySQL Trigger
MySQL Transactions
MySQL Character Set
MySQL User Management
MySQL Database Backup and Recovery
MySQL Log
MySQL Performance Optimization
LOAD DATA
is a MySQL statement that allows you to import data from a text file into a table in your database. It's faster than using INSERT
statements for importing large amounts of data. In this tutorial, we'll show you how to use LOAD DATA
to import data from a CSV (Comma-Separated Values) file into a MySQL table.
Prerequisites:
Tutorial:
Create a CSV file named sample_data.csv
with the following content:
1,John,Doe,35 2,Jane,Smith,28 3,Mark,Johnson,23 4,Emily,Jones,30
This sample file represents a table with four columns: id
, first_name
, last_name
, and age
.
Log in to the MySQL command-line client:
mysql -u [username] -p
Replace [username]
with your MySQL username, and enter your password when prompted.
Create a new database, if necessary:
CREATE DATABASE IF NOT EXISTS sample_db;
Use the new database:
USE sample_db;
Create a new table to hold the data from the CSV file:
CREATE TABLE users ( id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), age INT );
Use the LOAD DATA
statement to import data from the CSV file into the users
table:
LOAD DATA LOCAL INFILE '/path/to/sample_data.csv' INTO TABLE users FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';
Replace /path/to/sample_data.csv
with the actual path to your CSV file.
Run a SELECT
statement to verify that the data has been imported correctly:
SELECT * FROM users;
You should see the following output:
+----+------------+-----------+-----+ | id | first_name | last_name | age | +----+------------+-----------+-----+ | 1 | John | Doe | 35 | | 2 | Jane | Smith | 28 | | 3 | Mark | Johnson | 23 | | 4 | Emily | Jones | 30 | +----+------------+-----------+-----+
EXIT;
Now you've successfully imported data from a CSV file into a MySQL table using the LOAD DATA
statement. This method can be adapted for other file formats, such as TSV (Tab-Separated Values), by adjusting the FIELDS TERMINATED BY
option.
Recovering MySQL database from binary logs:
mysqlbinlog
to convert binary logs to SQL statements:mysqlbinlog binary-log-file | mysql -u username -p
MySQL InnoDB recovery process:
systemctl stop mysql mv /var/lib/mysql/ibdata1 /var/lib/mysql/ibdata1.bak systemctl start mysql
Recovering dropped tables in MySQL:
CREATE TABLE recovered_table AS SELECT * FROM backup_table;