Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into mysql from linux terminal

Tags:

linux

bash

mysql

I have a question. i can insert into mysql database from linux terminal a record with this command:

mysql dbTest insert into tablename values(1,"b","c")

Now i have a file in Linux with some records for example:

$cat file

2, "c", "e"
3, "r", "q"
4, "t", "w"
5, "y", "e"
6, "u", "r"
7, "g", "u"
8, "f", "j"
9, "v", "k"

i don't know how can i insert all records to the file to mysql database from linux terminal.

I intent with a bash file but i don't know =(

like image 716
Code Geas Coder Avatar asked Jan 22 '26 06:01

Code Geas Coder


2 Answers

Doing a series of inserts is not the best choice performance-wise. Since your input data exist as CSV you'd be better off doing a bulk load as @Kevin suggested:

mysql dbTest -e "LOAD DATA INFILE './file' INTO TABLE tablename FIELDS TERMINATED BY ','"
like image 151
Ansgar Wiechers Avatar answered Jan 24 '26 21:01

Ansgar Wiechers


You can create a custom sql file using sed.

From a terminal execute the following code:

sed 's/\(^[0-9"]*, [a-z"]*, [a-z]*$\)/INSERT INTO tablename VALUES(\1);/g' source_file > sql_script.sql

After you can easily use the source command to insert the records.

$ mysql -u mysqlusername -p -h host
Enter password: your_secret_password

Mysql > use yourdatabasename
Mysql > source sql_script.sql
like image 22
slackmart Avatar answered Jan 24 '26 23:01

slackmart