Comments on Storedprocedures get truncate on mysqldump - mysql

How to include comments in stored procedures while taking mysql database back up. I am using mysql 5.5.16 server with following command:
mysql -u root -p mydb<mydbbakup.sql
I have also tried from sql yog with no success.
UPDATE:
The problem is with restore command. While opening the dump file with notepad all the comments in stored procedures are there. Any extra attributes needed for following restore command?
mysql -u root -p mydb<mydbbakup.sql;

To restore the dump file, and include the comments, use the --comments option for mysql. For example:
mysql --comments -u root -p mydb<mydbbakup.sql
Alternatively, you can add this to your ~/.my.cnf file:
echo "[mysql]" >>~/.my.cnf
echo "comments=true" >>~/.my.cnf

Related

How do I import an SQL file using the command line in MySQL?

I have a .sql file with an export from phpMyAdmin. I want to import it into a different server using the command line.
I have a Windows Server 2008 R2 installation. I placed the .sql file on the C drive, and I tried this command
database_name < file.sql
It is not working. I get syntax errors.
How can I import this file without a problem?
Do I need to create a database first?
Try:
mysql -u username -p database_name < file.sql
Check MySQL Options.
Note 1: It is better to use the full path of the SQL file file.sql.
Note 2: Use -R and --triggers with mysqldump to keep the routines and triggers of the original database. They are not copied by default.
Note 3 You may have to create the (empty) database from MySQL if it doesn't exist already and the exported SQL doesn't contain CREATE DATABASE (exported with --no-create-db or -n option) before you can import it.
A common use of mysqldump is for making a backup of an entire database:
mysqldump db_name > backup-file.sql
You can load the dump file back into the server like this:
Unix
mysql db_name < backup-file.sql
The same in the Windows command prompt:
mysql -p -u [user] [database] < backup-file.sql
PowerShell
cmd.exe /c "mysql -u root -p db_name < backup-file.sql"
MySQL command line
mysql> use db_name;
mysql> source backup-file.sql;
Regarding the time taken for importing huge files: most importantly, it takes more time because the default setting of MySQL is autocommit = true. You must set that off before importing your file and then check how import works like a gem.
You just need to do the following thing:
mysql> use db_name;
mysql> SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;
Among all the answers, for the problem above, this is the best one:
mysql> use db_name;
mysql> source file_name.sql;
Easiest way to import into your schema:
Login to mysql and issue below mention commands.
mysql> use your_db_name;
mysql> source /opt/file.sql;
We can use this command to import SQL from the command line:
mysql -u username -p password db_name < file.sql
For example, if the username is root and password is password. And you have a database name as bank and the SQL file is bank.sql. Then, simply do like this:
mysql -u root -p password bank < bank.sql
Remember where your SQL file is. If your SQL file is in the Desktop folder/directory then go the desktop directory and enter the command like this:
cd ~/Desktop
mysql -u root -p password bank < bank.sql
And if you are in the Project directory and your SQL file is in the Desktop directory. If you want to access it from the Project directory then you can do like this:
cd ~/Project
mysql -u root -p password bank < ~/Desktop/bank.sql
If you already have the database, use the following to import the dump or the sql file:
mysql -u username -p database_name < file.sql
if you don't you need to create the relevant database(empty) in MySQL, for that first log on to the MySQL console by running the following command in terminal or in cmd
mysql -u userName -p;
And when prompted provide the password.
Next, create a database and use it:
mysql>create database yourDatabaseName;
mysql>use yourDatabaseName;
Then import the sql or the dump file to the database from
mysql> source pathToYourSQLFile;
Note: if your terminal is not in the location where the dump or sql file exists, use the relative path in above.
Open the MySQL command line
Type the path of your mysql bin directory and press Enter
Paste your SQL file inside the bin folder of mysql server.
Create a database in MySQL.
Use that particular database where you want to import the SQL file.
Type source databasefilename.sql and Enter
Your SQL file upload successfully.
A solution that worked for me is below:
Use your_database_name;
SOURCE path_to_db_sql_file_on_your_local;
While most answers here just mention the simple command
mysql -u database_user -p [db_name] < database_file.sql
today it's quite common that databases and tables have utf8-collation where this command is not sufficient.
Having utf8-collation in the exported tables it's required to use this command:
mysql -u database_user -p --default-character-set=utf8 [db_name] < database_file.sql
An according export can be done with
mysqldump -u database_user -p --default-character-set=utf8 [db_name] > database_file.sql
Surely this works for other charsets too, how to show the right notation can be seen here:
https://dev.mysql.com/doc/refman/5.7/en/show-collation.html
One comment mentioned also that if a database never exists an empty database had to be created first. This might be right in some cases but depends on the export file. If the exported file includes already the command to create the database then the database never has to be created in a separate step, which even could cause an error on import. So on import, it's advisable to have a look first in the file to know which commands are included there, on export, it's advisable to note the settings, especially if the file is very large and hard to read in an editor.
There are still more parameters for the command which are listed and explained here:
https://dev.mysql.com/doc/refman/5.7/en/mysql-command-options.html
If you use another database version consider searching for the corresponding version of the manual too. The mentioned links refer to MySQL version 5.7.
EDIT:
The same parameters are working for mysqldump too. So while the commands for export and import are different, the mentioned parameters are not.
Nevertheless there exists a special site in the manual that describes the options for mysqldump: https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html
To dump a database into an SQL file use the following command.
mysqldump -u username -p database_name > database_name.sql
To import an SQL file into a database (make sure you are in the same directory as the SQL file or supply the full path to the file), do:
mysql -u username -p database_name < database_name.sql
I think it's worth mentioning that you can also load a gzipped (compressed) file with zcat like shown below:
zcat database_file.sql.gz | mysql -u username -p -h localhost database_name
Go to the directory where you have the MySQL executable. -u for username and -p to prompt for the password:
C:\xampp\mysql\bin>mysql -u username -ppassword databasename < C:\file.sql
To import a single database, use the following command.
mysql -u username -p password dbname < dump.sql
To import multiple database dumps, use the following command.
mysql -u username -p password < dump.sql
To import a database, use the following command.
mysql> create new_database;
mysql> use new_database;
mysql> source (Here you need to import the path of the SQL file);
E.g.:
mysql> source E:/test/dump.sql;
You need to use forward slashes (/) even on Windows, e.g., E:/test/dump.sql instead of E:\test\dump.sql
Or double backslashes (\\) because of escaping, i.e., E:\\test\\dump.sql
mysql --user=[user] --password=[password] [database] < news_ml_all.sql
I kept running into the problem where the database wasn't created.
I fixed it like this:
mysql -u root -e "CREATE DATABASE db_name"
mysql db_name --force < import_script.sql
For exporting a database:
mysqldump -u username -p database_name > file.sql
For importing a database:
mysql -u username -p database_name < file.sql
For importing multiple SQL files at one time, use this:
# Unix-based solution
for i in *.sql ; do mysql -u root -pPassword DataBase < $i ; done
For simple importing:
# Unix-based solution
mysql -u root -pPassword DataBase < data.sql
For WAMP:
REM mysqlVersion - replace with your own version
C:\wamp\bin\mysql\mysqlVersion\bin\mysql.exe -u root -pPassword DataBase < data.sql
For XAMPP:
C:\xampp\mysql\bin\mysql -u root -pPassword DataBase < data.sql
You do not need to specify the name of the database on the command line if the .sql file contains CREATE DATABASE IF NOT EXISTS db_name and USE db_name statements.
Just make sure you are connecting with a user that has the permissions to create the database, if the database mentioned in the .sql file does not exist.
Import a database
Go to drive:
d:
MySQL login
c:\xampp\mysql\bin\mysql -u root -p
It will ask for pwd. Enter it:
pwd
Select the database
use DbName;
Provide the file name
\.DbName.sql
Use:
mysql -u root -p password -D database_name << import.sql
Use the MySQL help for details - mysql --help.
I think these will be useful options in our context:
[~]$ mysql --help
mysql Ver 14.14 Distrib 5.7.20, for osx10.12 (x86_64) using EditLine wrapper
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Usage: mysql [OPTIONS] [database]
-?, --help Display this help and exit.
-I, --help Synonym for -?
--bind-address=name IP address to bind to.
-D, --database=name Database to use.
--delimiter=name Delimiter to be used.
--default-character-set=name Set the default character set.
-f, --force Continue even if we get an SQL error.
-p, --password[=name] Password to use when connecting to server.
-h, --host=name Connect to host.
-P, --port=# Port number to use for connection or 0 for default to, in order of preference, my.cnf, $MYSQL_TCP_PORT, /etc/services, built-in default (3306).
--protocol=name The protocol to use for connection (tcp, socket, pipe,
-s, --silent Be more silent. Print results with a tab as separator, each row on new line.
-v, --verbose Write more. (-v -v -v gives the table output format).
-V, --version Output version information and exit.
-w, --wait Wait and retry if connection is down.
What is fun, if we are importing a large database and not having a progress bar. Use Pipe Viewer and see the data transfer through the pipe
For Mac, brew install pv
For Debian/Ubuntu, apt-get install pv.
For others, refer to pv - Pipe Viewer
pv import.sql | mysql -u root -p password -D database_name
1.45GiB 1:50:07 [339.0KiB/s] [=============> ] 14% ETA 11:09:36
1.46GiB 1:50:14 [ 246KiB/s] [=============> ] 14% ETA 11:09:15
1.47GiB 1:53:00 [ 385KiB/s] [=============> ] 14% ETA 11:05:36
Go to the directory where you have MySQL.
c:\mysql\bin\> mysql -u username -p password database_name <
filename.sql
Also to dump all databases, use the -all-databases option, and no databases’ name needs to be specified anymore.
mysqldump -u username -ppassword –all-databases > dump.sql
Or you can use some GUI clients like SQLyog to do this.
You can try this query.
Export:
mysqldump -u username –-password=your_password database_name > file.sql
Import:
mysql -u username –-password=your_password database_name < file.sql
and detail following this link:
https://chartio.com/resources/tutorials/importing-from-and-exporting-to-files-using-the-mysql-command-line/
Add the --force option:
mysql -u username -p database_name --force < file.sql
The following command works for me from the command line (cmd) on
Windows 7 on WAMP.
d:/wamp/bin/mysql/mysql5.6.17/bin/mysql.exe -u root -p db_name < database.sql
Providing credentials on the command line is not a good idea. The above answers are great, but neglect to mention
mysql --defaults-extra-file=etc/myhost.cnf database_name < file.sql
Where etc/myhost.cnf is a file that contains host, user, password, and you avoid exposing the password on the command line. Here is a sample,
[client]
host=hostname.domainname
user=dbusername
password=dbpassword
Import into the database:
mysql -u username -p database_name < /file path/file_name.sql
Export from the database:
mysqldump -u username -p database_name > /file path/file_name.sql
After these commands, a prompt will ask for your MySQL password.
Similarly to vladkras's answer to How do import an SQL file using the command line in MySQL?.
Key differences for me:
The database has to exist first
No space between -p and the password
shell> mysql -u root -ppassword #note: no space between -p and password
mysql> CREATE DATABASE databasename;
mysql> using databasename;
mysql> source /path/to/backup.sql
I am running Fedora 26 with MariaDB.
I thought it could be useful for those who are using Mac OS X:
/Applications/xampp/xamppfiles/bin/mysql -u root -p database < database.sql
Replace xampp with mamp or other web servers.

Restoring a MySQL table back to the database

I have a trouble in restoring MySQL table back to the database from command line. Taking backup of a table is working with mysqldump.Taking backup and restoring of a database is also working properly. I have used:
mysql -uroot -p DatabaseName TableName < path\TableName.sql
Thanks in advance
Ah, I think I see the problem here.
Your backup script looks fine. tbl_name works correctly as the optional 2nd argument.
To restore, you should simply run
mysql -uroot -p DatabaseName < path\TableName.sql
Running man mysql would have shown you the correct arguments and options
mysql [options] db_name
As your backup script only contains one table, only that table will be restored into your database.
Taking backup
mysqldump -u -p mydatabase table1 > database_dump.sql
restoring from backup flie need not include table name
mysql -u -p mydatabase < database_dump.sql
Best way to restore your database:
open cmd at bin folder
login to mysql:
mysql -uroot -pyour_password
show databases;
use db_name;
now hit source and put the complete path from address bar where your sql file is stored and hit ;
for example :
source db_name.sql;
Copy your db.sql file to your Mysql Server if you are in a remote machine:
$rsync -Cravzp --progress db.sql user#192.168.10.1:/home/user
Now you can go to your remote server as:
$ssh -l user 192.168.10.1
In the Mysql Server you must to do this:
user#machine:~$mysql -h localhost -u root -p
Obs: The file db.sql must be in the same place (/home/user).
Now type this command in you Mysql Server:
mysql>'\'. db.sql + Enter. Obs: Remove all ' from this command to work

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

Dump all databases and reimport on another server?

It's quite simple really, I just can't figure out the syntax.
I want to replicate my server setup on another server.
I can dump all my databases with
mysqldump -uroot -p --alldatabases > all.sql
But how do I import ALL of those into a brand new mysql setup on another server?
mysql -u root -p < all.sql
will do
From command line:
mysql -uroot < all.sql
ps. If you want to see what statement is executed right now you should -v.
if the database servers are both near enough the same version, you could simply rsync the /var/lib/mysql directory over.
rsync /var/lib/mysql root#destination.server.com:/var/lib/ -a
Edit: Please note that there are some issues with this approach which require some additional steps:
http://verens.com/2016/05/11/quick-method-to-clone-a-mysql-database/
mysql -u root -p
that command will open the mysql interactive console, where you'd do this:
source all.sql
execute the dump file from shell (dump file should contain the CREATE DATABASE syntax)
mysql -uroot < /path/to/file.sql
or execute from mysql
source /path/to/file.sql

mysql database backup with mysqldump

I want to backup my database using mysql dump. This is the code I run in Command prompt when the location is mysql bin.
mysqldump -u root -pabc Db -r C:\Documents and Settings\All Users\Desktop\ttttt.sql
abc is the password. and I try to backup to a .sql file in desktop. I use mysql 5.5.
But the following error occured. mysqldump: Couldn't find table: "and"
But there is no table called 'and' in database and I didn't create such a table.But the error say about a 'and' table. How can I back up mysql database without this error.
Try instead:
mysqldump -u root -pabc Db -r "C:\Documents and Settings\All Users\Desktop\ttttt.sql"
Your command shell is breaking apart the pathname into multiple arguments. The quotes tell the shell to pass it all as a single argument to the mysqldump program.
I think there is some problem with syntax of command you are running. try something like this :
mysqldump -u root -p dbName > path\nameOfFile.sql
It will automatically ask for your password. You don't need to write it in command.