The following works for me:
mysql -u 'root' -h 8.8.8.88 mo -e 'UPDATE `path_last_updated`
SET timestamp="2012-01-03 00:00:00"'
However, the following does not:
TIMESTAMP=`date "+%Y-%m-%d-%T"`
mysql -u 'root' -h 8.8.8.88 mo -e 'UPDATE `path_last_updated`
SET timestamp=$TIMESTAMP'
How would I insert the timestamp from unix into my mysql table?
Update:
TIMESTAMP=`date "+%Y-%m-%d %T"`
mysql -u 'root' -h 8.8.8.88 mo -e "UPDATE `path_last_updated`
SET timestamp='$TIMESTAMP'"
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near 'SET
timestamp='2013-01-31 15:46:00'' at line 1
Shell variable interpolation only works between double quotes ("), not single ('). You've also got backticks in there, which in a double-quoted string will be treated as an embedded shell command.
Try:
mysql -u 'root' -h 8.8.8.88 mo -e "UPDATE \`path_last_updated\`
SET timestamp='$TIMESTAMP'"
Also, fwiw, you have an extra dash (-) in your format for the date command, between the %d and %T.
ALTER TABLE to make it easier:
ALTER TABLE path_last_updated ADD date_entered timestamp DEFAULT CURRENT_TIMESTAMP
And then in shell:
mysql -u 'root' -h 8.8.8.88 mo -e "UPDATE path_last_updated SET timestamp=DEFAULT"
Related
please help, whats wrong?
sudo -u root /etc/scripts/mysql.sh root 111111
#!/bin/bash
mysql --host=localhost --user=root --password=111111
mysql 1<< EOF
INSERT INTO
table1(id)
SELECT MAX(id) + 1 FROM table1;
EOF
You should just invoke MySQL once and specify the default database:
#!/bin/bash
mysql --host=localhost --user=root --password=111111 1 << EOF
INSERT INTO
table1(id)
SELECT MAX(id) + 1 FROM table1;
EOF
Use below script:
#!/bin/bash
USER='root'
PASS='root123'
mysql -u$USER -p$PASS mydb -e"insert into table1 (id) select (max(id) + 1) from table1;"
Note: As you are executing sql from same server so no need of localhost.
Now use as from directory where your script exists-
sh myscript.sh
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 =(
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 ','"
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
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
mysql -e "use databasename;insert into TABLENAME values ('POST',........);"
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 acutesign 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','sumantasilwal10#gmail.com','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.
I'm executing the following query, to update the data in my database:
mysql -u root -ppassword -e "UPDATE table SET data = 1 WHERE id = 5"
Is there a way to execute the same query, but with the SELECT statement ? Of course there is, but how can I fetch the returned value then? Is that even possible?
mysql -u root -ppassword -e "UPDATE table SET data = 1 WHERE id = 5; SELECT data FROM table WHERE id = 5"
We have a simple sql script which needs to be executed against a MySQL database and we would like print log statements on the progress of the script (e.g. Inserted 10 records into foo or Deleted 5 records from bar). How do we do this?
I would like to know the syntax to be used for insert/update/delete statements.
How do I know about the number of rows affected by my statement(s).
I would also like to control printing them using a ECHO off or on command at the top of the script.
The script should be portable across Windows / Linux OS.
This will give you are simple print within a sql script:
select 'This is a comment' AS '';
Alternatively, this will add some dynamic data to your status update if used directly after an update, delete, or insert command:
select concat ("Updated ", row_count(), " rows") as '';
I don't know if this helps:
suppose you want to run a sql script (test.sql) from the command line:
mysql < test.sql
and the contents of test.sql is something like:
SELECT * FROM information_schema.SCHEMATA;
\! echo "I like to party...";
The console will show something like:
CATALOG_NAME SCHEMA_NAME DEFAULT_CHARACTER_SET_NAME
def information_schema utf8
def mysql utf8
def performance_schema utf8
def sys utf8
I like to party...
So you can execute terminal commands inside an sql statement by just using \!, provided the script is run via a command line.
\! #terminal_commands
Just to make your script more readable, maybe use this proc:
DELIMITER ;;
DROP PROCEDURE IF EXISTS printf;
CREATE PROCEDURE printf(thetext TEXT)
BEGIN
select thetext as ``;
END;
;;
DELIMITER ;
Now you can just do:
call printf('Counting products that have missing short description');
What about using mysql -v to put mysql client in verbose mode ?
For mysql you can add \p to the commands to have them print out while they run in the script:
SELECT COUNT(*) FROM `mysql`.`user`
\p;
Run it in the MySQL client:
mysql> source example.sql
--------------
SELECT COUNT(*) FROM `mysql`.`user`
--------------
+----------+
| COUNT(*) |
+----------+
| 24 |
+----------+
1 row in set (0.00 sec)
You can use print -p -- in the script to do this example :
#!/bin/ksh
mysql -u username -ppassword -D dbname -ss -n -q |&
print -p -- "select count(*) from some_table;"
read -p get_row_count1
print -p -- "select count(*) from some_other_table;"
read -p get_row_count2
print -p exit ;
#
echo $get_row_count1
echo $get_row_count2
#
exit
I'm trying to make a bash script that creates a mysql user and database but I can't find a way to feed the sql into mysql, I'm trying with this format:
mysql < echo "query"
But that is not working, see the example below:
mysql --host=localhost --user=user --password=password < echo "CREATE USER 'testuser'#'localhost' IDENTIFIED BY 'jakdJxct8W';
CREATE DATABASE IF NOT EXISTS 'testuser_dev' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON 'testuser_dev' . * TO 'testuser'#'localhost';
CREATE DATABASE IF NOT EXISTS 'testuser_qa' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON 'testuser_qa' . * TO 'testuser'#'localhost';"
How to feed mysql with the queries?
Try like this:
echo "select 1" | mysql
Try using a here document like this:
mysql --host=localhost --user=user --password=password << END
CREATE USER 'testuser'#'localhost' IDENTIFIED BY 'jakdJxct8W';
CREATE DATABASE IF NOT EXISTS 'testuser_dev' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON 'testuser_dev' . * TO 'testuser'#'localhost';
CREATE DATABASE IF NOT EXISTS 'testuser_qa' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON 'testuser_qa' . * TO 'testuser'#'localhost';
END
Alternatively place all you commands in text file and run it:
mysql --host=localhost --user=user --password=password < commands.sql
mysql --batch --silent -e 'SHOW TABLES';
Batch and silent are handy if you are planning to pipe the output
The reason your attempt did not work was because the < expects a file name and you fed it a string. You would have to do something like
echo "YOURQUERYSTRINGHERE">tmpfile
mysql --host=localhost --user=user --password=password dbname <tmpfile
ken's suggestion of
mysql --host=localhost --user=user --password=password -e "QUERY" dbname
can work, but if you try to use bash variables in your query you can fall foul of parameter expansion. eg
QUERY="select * from $MYTABLE WHERE name=\"silly#place.com\";"
mysql --host=localhost --user=user --password=password -e "$QUERY" mydbname
may not do what you expect.
One option is use
echo "$QUERY"|mysql --host=localhost --user=user --password=password mydbname
which works if the query string contains appropriate quoting. Another option is the "here" document as suggested by dogbane.
Have you tried mysql -e query?
cat <<EOD | mysql [-u user] [-ppassword] [database]
select 1;
select 2;
select 3;
EOD
in your case
cat <<EOD | mysql -u root -p
CREATE DATABASE IF NOT EXISTS testuser_dev DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON testuser_dev.* TO "testuser"#"localhost";
CREATE DATABASE IF NOT EXISTS testuser_qa DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON testuser_qa.* TO "testuser"#"localhost";
FLUSH PRIVILEGES;
EOD
For big queries in a bash script, you can try:
read -d '' SQL_QUERY_1 << EOF
SELECT prod.id as id, prod.title as title, comp.name as company, pho.id as photo_id, pho.image as photo_name
FROM products as prod
JOIN accounts as comp
ON comp.id = prod.account_id
JOIN photos as pho
ON pho.id = prod.featured_photo_id;
EOF
echo ${SQL_QUERY_1} | mysql