How to import a CSV file into MySQL, PostgreSQL, SQL Server and SQLite (4 ways)
You have a customers.csv from a spreadsheet, a CRM export or a client, and you need it in a database table. Every database has a fast built-in loader for this, but each one has its own syntax and its own permission gotcha. Here are the four options I reach for, from fastest to most portable. The file used in every example: id,name,email,signup_date,active 1,"Khan,…
Importing a CSV file into a database can be done using various methods, each with its own syntax and considerations. Here are four common approaches, ranked from fastest to most portable:
1. MySQL / MariaDB: Use the LOAD DATA LOCAL INFILE command. This method is suitable when the CSV file is located on the same machine as the MySQL server. The command specifies the file path, the table name, and the field and line terminators. Quoted commas are handled with OPTIONALLY ENCLOSED BY '"' and IGNORE 1 LINES skips the header row. Booleans need to be converted using a user variable and SET statement. Note that LOCAL must be enabled on both the server and client sides.
2. PostgreSQL: Utilize the \copy command. This approach works by copying the CSV file directly from your machine to the PostgreSQL server. The command specifies the source file, the table name, and the FORMAT 'csv' and HEADER true options to handle the header row. PostgreSQL can directly parse true/false and date values, eliminating the need for conversion.
3. SQL Server: Leverage the BULK INSERT command. This method requires the CSV file to be located on the SQL Server machine, not on the client machine. The command specifies the source file, the table name, and the FORMAT 'CSV' option to recognize CSV format. The FIRSTROW = 2 option skips the header row, and FIELDQUOTE = '"' handles quoted fields. Booleans are stored as BIT columns, so they need to be converted from true/false to 1/0 or loaded into a staging table before the final INSERT.
4. SQLite: Use the .import command. This command imports the CSV file directly into the SQLite database. The command specifies the database file, the path to the CSV file, and the --skip 1 option to exclude the header row. If the table doesn't exist, SQLite creates it based on the header row, treating all columns as TEXT. When the table already exists, the --skip option drops the header row.
In situations where these methods don't work, such as with managed databases lacking file access or for small datasets, generating INSERT statements is a portable option. However, manually writing these statements can be time-consuming. To simplify the process, a browser tool can be used to generate the INSERT statements automatically, handling escaping, batching, and data types. This tool ensures compatibility across different databases and simplifies the import process.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to