I'm trying to create a batch script that will create a database when executed. If the database is already existing, the script should echo that it already exists. I have it working on Linux, but it's apparently much more different on Windows.
Here is the script:
#echo off
SET dbname=1234
SET user=1234
SET password=1234
SET hostinfo=test3
SET RESULT="mysql -u root -ppassword --skip-column-names -e SHOW DATABASES LIKE '%dbname%'"
if %RESULT% == "%dbname%" (
echo "The database already exists. You can use the reinstall function instead."
) else (
mysql -h localhost -u root -ppassword -e "CREATE USER '%user%'#'%%'"
mysql -h localhost -u root -ppassword -e "SET PASSWORD FOR '%user%'#'%%' = PASSWORD('%password%')"
mysql -h localhost -u root -ppassword -e "GRANT USAGE ON * . * TO '%user%'#'%%' IDENTIFIED BY '%password%' WITH MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0"
mysql -h localhost -u root -ppassword -e "CREATE DATABASE IF NOT EXISTS `%dbname%`"
mysql -h localhost -u root -ppassword -e "GRANT ALL PRIVILEGES ON `%dbname%` . * TO '%user%'#'%%'"
echo A new MySQL database has been created for you.
echo Username: %user%
echo Password: %password%
echo Database: %dbname%
echo Host: %hostinfo%:3306
)
The output is just the following:
Warning: Using a password on the command line interface can be insecure.
ERROR 1396 (HY000) at line 1: Operation CREATE USER failed for '1234'#'%'
Warning: Using a password on the command line interface can be insecure.
Warning: Using a password on the command line interface can be insecure.
Warning: Using a password on the command line interface can be insecure.
Warning: Using a password on the command line interface can be insecure.
A new MySQL database has been created for you.
Username: 1234
Password: 1234
Database: 1234
Host: test3:3306
How would I do this? It doesn't seem like the if else statement is working correctly...
Kind regards,
Dennis
please before if statement 'echo %RESULT% and %dbname%' it will help you to know why this problem happens
I'm suggesting to change the if to be if "%RESULT%" == "%dbname%"
The result variable include the string for the command but not executed .. so you have to execute it and set the out put into it.
Check this:
#echo off
SET dbname=1234
SET user=1234
SET password=1234
SET hostinfo=test3
SET RESULT="mysql -u root -ppassword --skip-column-names -e SHOW DATABASES LIKE '%dbname%'"
for /f "delims=" %%i in ('%RESULT%') do set RESULT=%%i
if %RESULT% == "%dbname%" (
echo "The database already exists. You can use the reinstall function instead."
) else (
mysql -h localhost -u root -ppassword -e "CREATE USER '%user%'#'%%'"
mysql -h localhost -u root -ppassword -e "SET PASSWORD FOR '%user%'#'%%' = PASSWORD('%password%')"
mysql -h localhost -u root -ppassword -e "GRANT USAGE ON * . * TO '%user%'#'%%' IDENTIFIED BY '%password%' WITH MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0"
mysql -h localhost -u root -ppassword -e "CREATE DATABASE IF NOT EXISTS `%dbname%`"
mysql -h localhost -u root -ppassword -e "GRANT ALL PRIVILEGES ON `%dbname%` . * TO '%user%'#'%%'"
echo A new MySQL database has been created for you.
echo Username: %user%
echo Password: %password%
echo Database: %dbname%
echo Host: %hostinfo%:3306
)
I did a similar batch before check this post
http://muhammadhamed.blogspot.com/2013/01/install-mysql-as-windows-service-from.html
I hope this could help!
Related
I can execute mysql passing in a file as follows.
mysql -u username -p < some_file
In a bash script I have a function which echoes output which I want to pass into the same command in a bash script.
some_function() {
echo "Some SQL"
}
How can I pass the output into mysql using pipes/redirection?
I have tried the following, but it fails with no such file or directory. How can I use the output from the function here instead.
mysql -u username -p < some_function
No need to use a pipe or a redirection in this case, you can use directly -e options to execute some SQL commands:
mysql -u username -p -e "SQL/MySQL commands"
Exemple on a specific database:
mysql -u username -p -e "use database_name; SHOW tables"
mysql -u username -p -e "SHOW tables" database_name
And you can also catch the output of a command or function and passing it as argument like this:
sql_command="$(your_function)"
mysql -u username -p -e "${sql_command}" database_name;
If you really want to use a pipe or a redirection (but I think it make no sense in this case):
$ mysql -u root -p database_name < <(echo "SHOW TABLES") # redirection
$ mysql -u root -p database_name <<< "$(echo "SHOW TABLES")" # another way to use redirection
$ echo "SHOW TABLES"|mysql -u root -p database_name # pipe
I am writing a script that will run on a Ubuntu 16.04.1 server. The purpose of the script is to install a wordpress site on the server. I took most of my scripting from this site.
I am trying to create and grant permissions on the database, however my script stops when I enter a mysql environment using mysql -u root -p. As well, variables created in the bash environment are not carried over to the mysql environment. Here is my script for this section.
echo "Please enter the Name of the Database(please make name relevant)"
read -p DBNAME
echo "Please enter the Name of the Database User(Please document username)"
read -p DBUSER
echo "Please enter a Database password(Please document password)"
read -p DBPASSWORD
a=\'
b=$a$DBPASSWORD$a
f='CREATE DATABASE '$DBNAME' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci'
g=$a$f$a
c='GRANT ALL ON '$DBNAME.*'TO '$DBUSER'#localhost'' IDENTIFIED BY '$b
d=$a$c$a
mysql -u root -p -e $g
mysql -u root -p -e $c
mysql -u root -p -e "FLUSH PRIVILEGES"
Any help integrating the environment changes together would be great
When defining f and c use double quotes. Single quotes don't allow your variables to expand.
You log the user in as root to mysql, but don't supply a password, so it will prompt. Perhaps ask for the root password as well.
Perhaps something like the following would do the trick:
echo "Please enter the Name of the Database(please make name relevant)"
read -p DBNAME
echo "Please enter the Name of the Database User(Please document username)"
read -p DBUSER
echo "Please enter a Database password(Please document password)"
read -p DBPASSWORD
echo "Please enter your database's root password"
read -p DBROOTPASSWORD
a=\'
b=$a$DBPASSWORD$a
f="CREATE DATABASE '$DBNAME' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
g=$a$f$a
c="GRANT ALL ON $DBNAME.* TO $DBUSER#localhost IDENTIFIED BY "$b
d=$a$c$a
mysql -u root -p"$DBROOTPASSWORD" -e $g
mysql -u root -p"$DBROOTPASSWORD" -e $c
mysql -u root -p"$DBROOTPASSWORD" -e "FLUSH PRIVILEGES"
In a simple script like this one:
set -x
# Check if db exists, if not we make it, make user, give privileges
if ! mysql -u root -p -e "use $db" 2>/dev/null; then
c1="CREATE DATABASE $db"
c2="GRANT ALL PRIVILEGES ON ${db}.* to '$username'#'localhost' IDENTIFIED BY '$password'"
c3="FLUSH PRIVILEGES"
mysql -u root -p -e "$c1; $c2; $c3"
else
echo 'DATABASE ExISTS, ABORTING'; exit $DB_EXISTS
fi
I am asked each time, bash sees mysql command, for my root credentials.
Is there a way to avoid that, so that once entered the root password, all
additional mysql commands execute seamlessly?
Try looking into adding password to ~/.my.cnf
[client]
user = root
password = XXXXXXXX
Check out :
How to execute a MySQL command from a shell script?
Specifying the --password argument
mysql -u root --password=my_mysql_pass db_name
Safer using a bash variable
mysql -u root --password=$MYSQL_PASS db_name
I'm under VPN and I don't have SSH access to remote server.
I can connect to remote database by console
mysql -u username -p -h remote.site.com
Now I'm trying to clone the remote database to local computer
mysqldump -u username -p -h remote.site.com mysqldump | mysql -u root -ppassword webstuff
And I've got error
mysqldump: Got error: 1045: Access denied for user 'webstaff'#'10.75.1.2'
(using password: YES) when trying to connect
How to copy mysql database from remote server to local computer?
Assuming the following command works successfully:
mysql -u username -p -h remote.site.com
The syntax for mysqldump is identical, and outputs the database dump to stdout. Redirect the output to a local file on the computer:
mysqldump -u username -p -h remote.site.com DBNAME > backup.sql
Replace DBNAME with the name of the database you'd like to download to your computer.
Check syntax and execute one command at a time, then verify output.
mysqldump -u remoteusername -p remotepassword -h your.site.com databasename > dump.sql
mysql -u localusername -p localpassword databasename < dump.sql
Once you've matched all passwords, you can use pipe.
Often our databases are really big and the take time to take dump directly from remote machine to other machine as our friends other have suggested above.
In such cases what you can do is to take the dump on remote machine using MYSQLDUMP Command
MYSQLDUMP -uuser -p --all-databases > file_name.sql
and than transfer that file from remote server to your machine using Linux SCP Command
scp user#remote_ip:~/mysql_dump_file_name.sql ./
This can have different reasons like:
You are using an incorrect password
The MySQL server got an error when trying to resolve the IP address of the client host to a name
No privileges are granted to the user
You can try one of the following steps:
To reset the password for the remote user by:
SET PASSWORD FOR some_user#ip_addr_of_remote_client=PASSWORD('some_password');
To grant access to the user by:
GRANT SELECT, INSERT, UPDATE, DELETE, LOCK TABLES ON YourDB.* TO user#Host IDENTIFIED by 'password';
Hope this helps you, if not then you will have to go through the documentation
Please check this gist.
https://gist.github.com/ecdundar/789660d830d6d40b6c90
#!/bin/bash
# copymysql.sh
# GENERATED WITH USING ARTUR BODERA S SCRIPT
# Source script at: https://gist.github.com/2215200
MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"
REMOTESERVERIP=""
REMOTESERVERUSER=""
REMOTESERVERPASSWORD=""
REMOTECONNECTIONSTR="-h ${REMOTESERVERIP} -u ${REMOTESERVERUSER} --password=${REMOTESERVERPASSWORD} "
LOCALSERVERIP=""
LOCALSERVERUSER=""
LOCALSERVERPASSWORD=""
LOCALCONNECTION="-h ${LOCALSERVERIP} -u ${LOCALSERVERUSER} --password=${LOCALSERVERPASSWORD} "
IGNOREVIEWS=""
MYVIEWS=""
IGNOREDATABASES="select schema_name from information_schema.SCHEMATA where schema_name != 'information_schema' and schema_name != 'mysql' and schema_name != 'performance_schema' ;"
# GET A LIST OF DATABASES
databases=`$MYSQL $REMOTECONNECTIONSTR -e "${IGNOREDATABASES}" | tr -d "| " | grep -v schema_name`
# COPY ALL TABLES
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"
IGNOREVIEWS=""
for view in $views; do
IGNOREVIEWS=${IGNOREVIEWS}" --ignore-table=$db.$view "
done
echo "TABLES "$db
$MYSQL $LOCALCONNECTION --batch -N -e "create database $db; "
$MYSQLDUMP $REMOTECONNECTIONSTR $IGNOREVIEWS --compress --quick --extended-insert --skip-add-locks --skip-comments --skip-disable-keys --default-character-set=latin1 --skip-triggers --single-transaction $db | mysql $LOCALCONNECTION $db
done
# COPY ALL PROCEDURES
for db in $databases; do
echo "PROCEDURES "$db
#PROCEDURES
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --routines --no-create-info --no-data --no-create-db --skip-opt --skip-triggers $db | \
sed -r 's/DEFINER=`[^`]+`#`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL TRIGGERS
for db in $databases; do
echo "TRIGGERS "$db
#TRIGGERS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --no-create-info --no-data --no-create-db --skip-opt --triggers $db | \
sed -r 's/DEFINER=`[^`]+`#`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL VIEWS
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"`
MYVIEWS=""
for view in $views; do
MYVIEWS=${MYVIEWS}" "$view" "
done
echo "VIEWS "$db
if [ -n "$MYVIEWS" ]; then
#VIEWS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick -Q -f --no-data --skip-comments --skip-triggers --skip-opt --no-create-db --complete-insert --add-drop-table $db $MYVIEWS | \
sed -r 's/DEFINER=`[^`]+`#`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
fi
done
echo "OK!"
Copy mysql database from remote server to local computer
I ran into the same problem. And I could not get it done with the other answers. So here is how I finally did it (yes, a beginner tutorial):
Step 1: Create a new database in your local phpmyadmin.
Step 2: Dump the database on the remote server into a sql file (here I used Putty/SSH):
mysqldump --host="mysql5.domain.com" --user="db231231" --password="DBPASSWORD" databasename > dbdump.sql
Step 3: Download the dbdump.sql file via FTP client (should be located in the root folder)
Step 4: Move the sql file to the folder of your localhost installation, where mysql.exe is located. I am using uniform-server, this would be at C:\uniserver\core\mysql\bin\, with XAMPP it would be C:\xampp\mysql\bin
Step 5: Execute the mysql.exe as follows:
mysql.exe -u root -pYOURPASSWORD YOURLOCALDBNAME < dbdump.sql
Step 6: Wait... depending on the file size. You can check the progress in phpmyadmin, seeing newly created tables.
Step 7: Done. Go to your local phpmyadmin to check if the database has been filled with the entire data.
Hope that helps. Good luck!
Note 1: When starting the uniformer-server you can specify a password for mysql. This is the one you have to use above for YOURPASSWORD.
Note 2: If the login does not work and you run into password problems, check your password if it contains special characters like !. If so, then you probably need to escape them \!.
Note 3: In case not all mysql data can be found in the local db after the import, it could be that there is a problem with the mysql directives of your dbdump.sql
Better yet use a oneliner:
Dump remoteDB to localDB:
mysqldump -uroot -pMypsw -h remoteHost remoteDB | mysql -u root -pMypsw localDB
Dump localDB to remoteDB:
mysqldump -uroot -pmyPsw localDB | mysql -uroot -pMypsw -h remoteHost remoteDB
C:\Users\>mysqldump -u root -p -h ip address --databases database_name -r sql_file.sql
Enter password: your_password
This answer is not remote server but local server. The logic should be the same. To copy and backup my local machine MAMP database to my local desktop machine folder, go to console then
mysqldump -h YourHostName -u YourUserNameHere -p YourDataBaseNameHere > DestinationPath/xxxwhatever.sql
In my case YourHostName was localhost. DestinationPath is the path to the download; you can drag and drop your desired destination folder and it will paste the path in.
Then password may be asked:
Enter password: xxxxxxxx
Is it possible to create mysql database from fabric dynamically.
This seems like it gets stuck at the password prompt
run('mysql -u %s -p %s -h %s ' % (env.mysqluser, env.mysqlpassword, env.mysqlhost), pty=True)
run('CREATE DATABASE %s; ' % (dataname), pty=True)
run('exit', pty=True)
There's a better way of doing this using mysqladmin:
run('mysqladmin -u %s -p%s create %s' % (user, password, dbname))
Try instead
run('echo "CREATE DATABASE %s;"|mysql --batch --user=%s --password=%s --host=%s' % (dataname, env.mysqluser, env.mysqlpassword, env.mysqlhost), pty=True)
I use the following one liner via command line
mysql -uroot -prootpassword -e "CREATE DATABASE dbname";
key is the -e switch.
if you like to have bash script with variables in db/user/pass and run it as ./myscript then
#!/bin/bash
DB="mydb"
USER="user1"
PASS="pass_bla"
mysql -uroot -prootpassword -e "CREATE DATABASE $DB CHARACTER SET utf8 COLLATE utf8_general_ci";
mysql -uroot -prootpassword -e "CREATE USER $USER#'127.0.0.1' IDENTIFIED BY '$PASS'";
mysql -uroot -prootpassword -e "GRANT SELECT, INSERT, UPDATE ON $DB.* TO '$USER'#'127.0.0.1'";