Reputation: 1979
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 =(
Upvotes: 3
Views: 24603
Reputation: 4924
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
Upvotes: 1
Reputation: 1
Install Mysql :
sudo apt-get install mysql-server
Goto Mysql shell:
mysql -u root -p
password:******
Show Database( if already exist):
show databases;
Create a databases:
create database employees;
Access the created database:
use employees;</code>
Create a table (Be careful on "``" and " " : use acute
sign in each field):
create table `employees`( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(64) DEFAULT NULL,`last_name` varchar(64) DEFAULT NULL, `email` varchar(64) DEFAULT NULL, `department` varchar(64) DEFAULT NULL, `salary` DECIMAL(10,2) DEFAULT NULL, PRIMARY KEY(`id`))
ENGINE = InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET = latin1;
Add Information to a table:
INSERT INTO `employees` (`id`,`first_name`,`last_name`,`email`,`department`,`salary`)
VALUES (1, 'Sumanta','Silwal','[email protected]','Computer Design', '5000.00');
Look the created tale:
select * from employees;
Note: use "`" sign in each field like employees, id, first_name, last_name, email, department and salary.
**Enjoy coding.
Upvotes: 0
Reputation: 200193
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 ','"
Upvotes: 3
Reputation: 396
mysql -e "use databasename;insert into TABLENAME values ('POST',........);"
Upvotes: 0
Reputation: 1106
Using awk you could use the existing file and insert values from bash itself:
awk 'BEGIN {print "mysql -u root -p dbTest << EOF"} {print "insert into tablename values (" $0 ");"} END {print "EOF"}' file |bash -v
Upvotes: 0