Running mysql command from bat file with redirection - mysql

I have the following batch file:
#ECHO on
cd "C:\Program Files\MariaDB\mariadb\bin"
mysql -u root < "C:\database_setup.sql"
When I run the command directly in the command line, it works fine. When I run this batch file I get that it's trying to execute:
mysql -u root 0<"C:\database_setup.sql"
To solve this, I tried to escape the less than sign with:
mysql -u root ^< "C:\database_setup.sql"
It appears to be correct in the console but it's dumping the mysql options instead of inserting the contents of database_setup.sql.
I'm thinking that this is because the "<" is actually be referred to as a string since I'm escaping it and not as the redirection operator.
How does one accomplish running this command in a batch file (which works fine directly in the console)?

The following workaround could help you:
mysql -u root -e "SOURCE C:\database_setup.sql"
Also the following should work:
type C:\database_setup.sql | mysql -u root

Related

Add date in Mysqldump when running cmd from Java and Shell

I would like to append date in file name when taking backup using mysqldump. I am storing the command in properties file and running it via ProcessBuilder and shell script. I have tried multiple ways to add the date (BTW all the answers here were only if we run the command directly in linux)
mysqldump -u <user> -p <database> | gzip > <backup>$(date +%Y-%m-%d-%H.%M.%S).sql.gz
Got the error: No table found for "+%Y-%m-%d-%H.%M.%S"
mysqldump -u root -ppassword dbName --result-file=/opt/backup/`date -Iminutes`.dbName.sql
Got the error: unknow option -I
Is there a way around for this to add date in the command itself? I cannot append the date in java method or shell script.
I can't tell from your question whether you're running in a shell. If so, try these three lines to generate your backup file.
DATE=`date +%Y-%m-%d-%H.%M.%S`
FILENAME=backup${DATE}.sql.gz
mysqldump -u user -p database | gzip > ${FILENAME}
Notice how you should surround the date command in the first line with backticks, not ${}, to get its result into the DATE shell variable.

Run mysql commands in bash script without logging in or adding -u root to every command

I'm writing a bash script to do some db stuff. New to MySQL. I'm on Mac and have MySQL installed via homebrew.
Am using username "root" right now and there isn't a pw set. I included the pw syntax below just to help others out that may have a pw.
My goal is to have mysql commands be as "clean" as possible in my bash script
Not a hige deal, but would like to do this if possible.
Example
# If I can do it without logging in (*ideal)
mysql CREATE DATABASE dbname;
# Or by logging in with - mysql -u root -pPassword
CREATE DATABASE dbname;
# Instead of
mysql -u root -pPassword -e"CREATE DATABASE dbname";
Tried to simplify it. I have a handful of things I gotta do, so would rather keep my code cleaner if possible. I tried logging in with the bash script, but the script stopped once logged into MySQL and didn't run any commands.
Another option I was considering (but don't really like) would be just to keep username and pw string in a var and call it for every commmand like so
# Set the login string variable
login_details="-u root -p password -e"
# example command
mysql $login_details"CREATE DATABASE dbname";
So any ideas?
Write a new bash script file and run this file after putting all your commands into it. Don't forget to give right username and password in your bash script.
For bash script:
#!/bin/bash
mysql -u root -pSeCrEt << EOF
use mysql;
show tables;
EOF
If you want to run single mysql command.
mysql -u [user] -p[pass] -e "[mysql commands]"
Example:
mysql -h 192.168.1.10 -u root -pSeCrEt -e "show databases"
To execute multiple mysql commands:
mysql -u $user -p$passsword -Bse "command1;command2;....;commandn"
Note: -B is for batch, print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file. Batch mode results in nontabular output format and escaping of special characters. -s is silent mode. Produce less output. -e is to execute the statement and quit

Run sql script using batch file from command prompt

D:
cd Tools/MySQL5/bin
mysql -u root mysql
use xyz;
source C:/Users/abc/Desktop/xyz.sql;
\q
When I run the above lines in command prompt it works fine but when I save it as a batch file and run the file it connects to mysql but doesn't perform the sql scripts.
Now what I see is wrong here is that while executing the above commands one by one in your prompt, once you run mysql -u root mysql, you are in the mysql console. So your source command would work there but would not work in your batch since you are not in mysql console while running the batch file.
Solution:
What you can do for this is, instead of using source in mysql you can use
mysql dbname < filename
in your batch file in place of
mysql -u root mysql
use xyz;
source C:/Users/abc/Desktop/xyz.sql;
This link can assist you further if needed
This should work
mysql -u root xyz < C:/Users/abc/Desktop/xyz.sql;
It sources the SQL commands from your file
You could write something like this
mysql -u dbUsername yourDatabase -e "SELECT * FROM table;"
Or to run repeating tasks create a runtasks.bat file, save under the root of your project then write your cmd tasks inside
mysql -u dbUser -e "DROP DATABASE IF EXISTS testDatabase;"
mysql -u dbUser -e "CREATE DATABASE testDatabase;"
php index.php migration latest #runs your migration files
cd application\tests
phpunit
This would work.
mysql.exe -u user_name -p -h _host_ _schema_ -e "select 1 from dual;"
This will also give you output on same command terminal

How to run SQL script in MySQL?

I want to execute a text file containing SQL queries, in MySQL.
I tried to run source /Desktop/test.sql and received the error:
mysql> . \home\sivakumar\Desktop\test.sql ERROR: Failed to open file
'\home\sivakumar\Desktop\test.sql', error: 2
Any idea on what I am doing wrong?
If you’re at the MySQL command line mysql> you have to declare the SQL file as source.
mysql> source \home\user\Desktop\test.sql;
You have quite a lot of options:
use the MySQL command line client: mysql -h hostname -u user database < path/to/test.sql
Install the MySQL GUI tools and open your SQL file, then execute it
Use phpmysql if the database is available via your webserver
you can execute mysql statements that have been written in a text file using the following command:
mysql -u yourusername -p yourpassword yourdatabase < text_file
if your database has not been created yet, log into your mysql first using:
mysql -u yourusername -p yourpassword
then:
mysql>CREATE DATABASE a_new_database_name
then:
mysql -u yourusername -p yourpassword a_new_database_name < text_file
that should do it!
More info here: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html
My favorite option to do that will be:
mysql --user="username" --database="databasename" --password="yourpassword" < "filepath"
I use it this way because when you string it with "" you avoiding wrong path and mistakes with spaces and - and probably more problems with chars that I did not encounter with.
With #elcuco comment I suggest using this command with [space] before so it tell bash to ignore saving it in history, this will work out of the box in most bash.
in case it still saving your command in history please view the following solutions:
Execute command without keeping it in history
extra security edit
Just in case you want to be extra safe you can use the following command and enter the password in the command line input:
mysql --user="username" --database="databasename" -p < "filepath"
All the top answers are good. But just in case someone wants to run the query from a text file on a remote server AND save results to a file (instead of showing on console), you can do this:
mysql -u yourusername -p yourpassword yourdatabase < query_file > results_file
Hope this helps someone.
I came here searching for this answer as well, and here is what I found works the best for me: Note I am using Ubuntu 16.x.x
Access mysql using:
mysql -u <your_user> - p
At the mysql prompt, enter:
source file_name.sql
Hope this helps.
Give the path of .sql file as:
source c:/dump/SQL/file_name.sql;
mysql> source C:\Users\admin\Desktop\fn_Split.sql
Do not specify single quotes.
If the above command is not working, copy the file to c: drive and try again.
as shown below,
mysql> source C:\fn_Split.sql
instead of redirection I would do the following
mysql -h <hostname> -u <username> --password=<password> -D <database> -e 'source <path-to-sql-file>'
This will execute the file path-to-sql-file
Never is a good practice to pass the password argument directly from the command line, it is saved in the ~/.bash_history file and can be accessible from other applications.
Use this instead:
mysql -u user --host host --port 9999 database_name < /scripts/script.sql -p
Enter password:
mysql -uusername -ppassword database-name < file.sql
So many ways to do it.
From Workbench: File > Run SQL Script -- then follow prompts
From Windows Command Line:
Option 1: mysql -u usr -p
mysql> source file_path.sql
Option 2: mysql -u usr -p '-e source file_path.sql'
Option 3: mysql -u usr -p < file_path.sql
Option 4: put multiple 'source' statements inside of file_path.sql (I do this to drop and recreate schemas/databases which requires multiple files to be run)
mysql -u usr -p < file_path.sql
If you get errors from the command line, make sure you have previously run
cd {!!>>mysqld.exe home directory here<<!!}
mysqld.exe --initialize
This must be run from within the mysqld.exe directory, hence the CD.
Hope this is helpful and not just redundant.
From linux 14.04 to MySql 5.7, using cat command piped with mysql login:
cat /Desktop/test.sql | sudo mysql -uroot -p
You can use this method for many MySQL commands to execute directly from Shell. Eg:
echo "USE my_db; SHOW tables;" | sudo mysql -uroot -p
Make sure you separate your commands with semicolon (';').
I didn't see this approach in the answers above and thought it is a good contribution.
Very likely, you just need to change the slash/blackslash:
from
\home\sivakumar\Desktop\test.sql
to
/home/sivakumar/Desktop/test.sql
So the command would be:
source /home/sivakumar/Desktop/test.sql
use the following from mysql command prompt-
source \\home\\user\\Desktop\\test.sql;
Use no quotation. Even if the path contains space(' ') use no quotation at all.
Since mysql -u yourusername -p yourpassword yourdatabase < text_file did not work on a remote server (Amazon's EC2)...
Make sure that the Database is created first.
Then:
mysql --host=localhost --user=your_username --password=your_password your_database_name < pathTofilename.sql
For future reference, I've found this to work vs the aforementioned methods, under Windows in your msql console:
mysql>>source c://path_to_file//path_to_file//file_name.sql;
If your root drive isn't called "c" then just interchange with what your drive is called. First try backslashes, if they dont work, try the forward slash. If they also don't work, ensure you have your full file path, the .sql extension on the file name, and if your version insists on semi-colons, ensure it's there and try again.
If you are here LOOKING FOR A DRUPAL ENVIRONMENT
You can run with drush command on your project directory
drush sqlc
If you are trying this command :
mysql -u root -proot -D database < /path/to/script.sql
You may get an error like this : if you have special characters, mainly '`'
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 '/path/to/script.sql' at line 1
So I would suggest to use a command like this :
echo "source /path/to/script.sql" | mysql -u root -proot -D database
This command will execute source /path/to/script.sql once connected to the server, which execute your script.
I had this error, and tried all the advice i could get to no avail.
Finally, the problem was that my folder had a space in the folder name which appearing as a forward-slash in the folder path, once i found and removed it, it worked fine.
I use Bash's Here Strings for an instant SQL execution:
mysql -uroot -p <<<"select date(now())"
https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Strings

How do you use MySQL's source command to import large files in windows

I have a large (~150mb) sql file that I am trying to import. It is too large to do it through PHPMyAdmin even splitting it into many pieces and it is too large to import through a php script as it times out after 30 seconds of processing the script. So I'm looking for how to directly import the file from MySQL command line.
Searching online shows that I want to either use database_name < file_name.sql or source file_name.sql but I can't get either of these to work.
Using < gives the generic MySQL syntax error while using source give a slightly more promising failed to open file 'file_name.sql', error: 2 so I am inclined to think that the source command is on the right track.
I am in windows and am using xampp as a localhost server (note I'm only trying to import this file on the localhost so that I can execute the sql). I've tried placing the file in xampp\mysql\bin and xampp\mysql\data\database_name.
Any suggestions of how to import this .sql file into MySQL either from the MySQL command line or by any other means would be greatly appreciated.
On Windows this should work (note the forward slash and that the whole path is not quoted and that spaces are allowed)
USE yourdb;
SOURCE D:/My Folder with spaces/Folder/filetoimport.sql;
With xampp I think you need to use the full path at the command line, something like this, perhaps:
C:\xampp\mysql\bin\mysql -u {username} -p {databasename} < file_name.sql
Don't use "source", it's designed to run a small number of sql queries and display the output, not to import large databases.
I use Wamp Developer (not XAMPP) but it should be the same.
What you want to do is use the MySQL Client to do the work for you.
Make sure MySQL is running.
Create your database via phpMyAdmin or the MySQL shell.
Then, run cmd.exe, and change to the directory your sql file is
located in.
Execute: mysql -u root -p database_name_here < dump_file_name_here.sql
Substitute in your database name and dump file name.
Enter your MySQL root account password when prompted (if no password set, remove the "-p" switch).
This assumes that mysql.exe can be located via the environmental path, and that sql file is located in the directory you are running this from. Otherwise, use full paths.
Option 1. you can do this using single cmd where D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this
You can try this:
mysql -u root -p test < /test.sql
Another option
D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql
Option 1 for wampp
D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql
change your folder and mysql version
Option 2 Suppose your current path is which is showing command prompt
C:\Users\shafiq;
then change directory using cd..
then goto your mysql directory where your xampp installed. Then cd.. for change directory. then go to bin folder.
C:\xampp\mysql\bin;
C:\xampp\mysql\bin\mysql -u {username} -p {database password}.then please enter when you see enter password in command prompt.
choose database using
mysql->use test (where database name test)
then put in source sql in bin folder.
then last command will be
mysql-> source test.sql (where test.sql is file name which need to import)
then press enter
This is full command
C:\Users\shafiq;
C:\xampp\mysql\bin
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
mysql-> use test
mysql->source test.sql
C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql
That worked for me to import 400MB file into my database.
For importing a large SQL file using the command line in MySQL.
First go to file path at the command line.
Then,
Option 1:
mysql -u {user_name} -p{password} {database_name} < your_file.sql
It's give a warning mesaage : Using a password on the command line interface can be insecure.
Done.Your file will be imported.
Option 2:
mysql -u {user_name} -p {database_name} < your_file.sql
in this you are not provide sql password then they asked for password just enter password and your file will be imported.
use mysql source command to avoid redirection failures, especially on windows.
mysql [-u <username>] [-p<password>] <databasename> -e "source /path/to/dump.sql"
where e for "Execute command"
On Windows, please remember to use double quote for sql command.
However, either backslash \ or slash / will work on Windows.
Hello I had the same problem but I tried many different states and I came to it:
SOURCE doesn't work with ; at the end in my case:
SOURCE D:\Barname-Narmafzar\computer programming's languages\SQL\MySQL\dataAug-12-2019\dataAug-12-2019.sql;
and the error was:
ERROR: Unknown command '\B'.
'>
it also didn't work with a quotation for the address.
But it works without ; at the end:
SOURCE D:\Barname-Narmafzar\computer programming's languages\SQL\MySQL\dataAug-12-2019\dataAug-12-2019.sql
But remember to use USE database_name; before that.
I think it's so because the SOURCE or USE or HELP are for the Mysql itself and they are not such query codes although when you write HELP it says:
"Note that all text commands must be first on line and end with ; ".
but here doesn't work.
I should say that I have done it in CMD and I didn't try it in Mysql Workbench.
That was it
This is the result
On my Xampp set-up I was able to use the following to import a database into MySQL:
C:\xampp\mysql\bin\mysql -u {username goes here} -p {leave password blank} {database name} < /path/to/file.sql [enter]
My personal experience on my local machine was as follows:
Username: Root
Database Name: testdatabase
SQL File Location: databasebackup.sql is located on my desktop
C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql
That worked for me to import my 1GB+ file into my database.
Username as root without password
mysql -h localhost -u root databasename < dump.sql
I have faced the problem on my local host as i don't have any password for root user. You can use it without -p password as above. If it ask for password, just hit enter.
On windows:
Use explorer to navigate to the folder with the .sql file.
Type cmd in the top address bar. Cmd will open.
Type:
"C:\path\to\mysql.exe" -u "your_username" -p "your password" < "name_of_your_sql_file.sql"
Wait a bit and the sql file will have been executed on your database.
Confirmed to work with MariaDB in feb 2018.