I would like to automate the setup of a database and I would like to do it by using a python script to execute some commands in a linux terminal.
But I cannot see any way of executing commands in the terminal after connection to mysql database.
Below you can see a part of the script:
from time import sleep
from os import system
print("Setting up the database...\n")
system("sudo mysql -u root")
sleep(2)
This starts mysql, and after this none of the commands I try to execute from python get executed.
For example, I would like to run commands like these:
system("CREATE DATABASE mydatabase;")
system("CREATE USER 'user'#'localhost' IDENTIFIED BY '[PASSWORD]';")
system("GRANT ALL PRIVILEGES ON mydatabase.* TO 'user'#'localhost';")
Is this possible?
Edit 1: Potential solution as suggested by #AndHeFallen:
In python I create an sql file named db.sql, then run this in the terminal:
with open("db.sql","w") as db:
db.write("CREATE DATABASE mydatabase;\n")
db.write("CREATE USER 'user'#'localhost' IDENTIFIED BY '[PASSWORD]';\n")
db.write("GRANT ALL PRIVILEGES ON mydatabase.* TO 'user'#'localhost';\n")
system("sudo mysql -u root < db.sql")
I don't think it's possible to do that. If you want to interact with your MySQL database with a Python script, you'll need to connect directly to your db with an api like MySQLdb. (I may be wrong but the way you want to do may cause security issues)
I tried to deploy web application on my server and I am getting this mysql database exception
Access denied for user 'root'#'localhost' (using password: YES) (Mysql::Error)
I tried to access the database from the command prompt using mysql -u root -p I am able to do all the database operations.
what is the error
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:771)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3649)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1176)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2558)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:620)
at java.sql.DriverManager.getConnection(DriverManager.java:200)
at com.mpigeon.DbConnection.DbConn(DbConnection.java:26)
at com.mpigeon.CheckLoginHome.doGet(CheckLoginHome.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
You need to grant access to root from localhost. Check this ubuntu help
try using root like..
mysql -uroot
then you can check different user and host after you logged in by using
select user,host,password from mysql.user;
check you are putting blank space in password.
From my answer here, thought this might be useful:
I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:
Step 1: Identify the Database Version
$ mysql --version
You'll see some output like this with MySQL:
$ mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
Or output like this for MariaDB:
mysql Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.
Step 2: Stopping the Database Server
To change the root password, you have to shut down the database server beforehand.
You can do that for MySQL with:
$ sudo systemctl stop mysql
And for MariaDB with:
$ sudo systemctl stop mariadb
Step 3: Restarting the Database Server Without Permission Checking
If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.
To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.
Start the database without loading the grant tables or enabling networking:
$ sudo mysqld_safe --skip-grant-tables --skip-networking &
The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.
Now you can connect to the database as the root user, which should not ask for a password.
$ mysql -u root
You'll immediately see a database shell prompt instead.
MySQL Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
MariaDB Prompt
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Now that you have root access, you can change the root password.
Step 4: Changing the Root Password
mysql> FLUSH PRIVILEGES;
Now we can actually change the root password.
For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:
mysql> ALTER USER 'root'#'localhost' IDENTIFIED BY 'new_password';
For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
mysql> SET PASSWORD FOR 'root'#'localhost' = PASSWORD('new_password');
Make sure to replace new_password with your new password of choice.
Note: If the ALTER USER command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET to reset the root password instead.
[IMPORTANT] This is the specific line that fixed my particular issue:
mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
Remember to reload the grant tables after this.
In either case, you should see confirmation that the command has been successfully executed.
Query OK, 0 rows affected (0.00 sec)
The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
Step 5: Restart the Database Server Normally
The tutorial goes into some further steps to restart the database, but the only piece I used was this:
For MySQL, use:
$ sudo systemctl start mysql
For MariaDB, use:
$ sudo systemctl start mariadb
Now you can confirm that the new password has been applied correctly by running:
$ mysql -u root -p
The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.
Conclusion
You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.
I faced the same error after upgrading MySQL server from 5.1.73 to 5.5.45
There is another way to fix that error.
In my case I was able to connect to MySQL using root password but MySQL actively refused to GRANT PRIVILEGES to any user;
Connect to MySQL as root
mysql -u root -p
then enter your MySQL root password;
Select database;
use mysql;
Most probably there is only one record for root in mysql.user table allowing to connect only from localhost (that was in my case) but by the default there should be two records for root, one for localhost and another one for 127.0.0.1;
Create additional record for root user with Host='127.0.0.1' if it's not there;
SET #s = CONCAT('INSERT INTO mysql.user SELECT ',
REPLACE((SELECT GROUP_CONCAT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'user' AND TABLE_SCHEMA = 'mysql')
,"Host","'127.0.0.1'"),
' FROM mysql.user WHERE User="root"');
PREPARE stmt FROM #s;
EXECUTE stmt;
Additionally to that you can execute mysql_upgrade -u -p
to see if everything is ok.
This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.
But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:
1) Run with --skip-grant-tables as said above.
If it doesnt works then add the string skip-grant-tables in section [mysqld] of /etc/mysql/mysql.conf.d/mysqld.cnf. Then do sudo service mysql restart.
2) Run mysql -u root -p, then (change "PWD"):
update mysql.user
set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password"
where User='root' and Host='localhost';
flush privileges;
quit
then sudo service mysql restart. Check: mysql -u root -p.
Before restart remove that string from file mysqld.cnf, if you set it there.
#bl79 is the author of this answer, i've just reposted it, because it does help!
My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.
I solved this problem by deleting the empty users creating by MySQL. I only have root user and my own user. I deleted the rest.
Update the empty password in the table mysql.user of mysql
use mysql;
select host,user,password from mysql.user;
update mysql.user set password = PASSWORD('123456') where password = '';
flush privileges;
Update user table in mysql DB. And set some password where it is blank, i was using root user so i set password for root user.
update mysql.user set password = PASSWORD('123456') where password = '';
flush privileges;
And then again tried from ATG CIM by providing password and it worked fine.
http://i.stack.imgur.com/3Lchp.png
I got this problem today while installing SugarCRM (a free CRM).
The system was not able to connect to the database using the root user. I could definitively log in as root from the console... so what was the problem?
I found out that in my situation, I was getting exactly the same error, but that was because the password was sent to mysql directly from the $_POST data, in other words, the < character from my password was sent to mysql as < which means the password was wrong.
Everything else did not help a bit. The list of users in mysql were correct, including the anonymous user (which appears after the root entries.)
I googled a lot but did not find a definite answer to my problem. I used KeyPass to generate a strong password and could use it successfully on mysql workbench to connect but not from the command line. So I changed the psw to an easy one and it worked on the command line. I have managed to create a strong password that was able to connect from the terminal. So my advise is, try with an easy password first before trying all kind of things.
I was running UTs and I started receiving error messages. I am not sure what was the problem. But when I changed my encoding style in INTELLIJ to UTF8 it started working again.
access denied for user 'root'#'localhost' (using password yes)
hibernate
this is my URL
db.url=jdbc:mysql://localhost:3306/somedb?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8&characterEncoding=utf8
Add a user option in msyql.
GRANT PROXY ON ''#'' TO 'root'#'localhost' WITH GRANT OPTION;
and this link will be useful.
So I just set-up an ubuntu server on amazon and installed mysql. It is working with:
mysql -u root -p
And then the mysql_password. I have added via command line a database and tables. But now I wonder how I can access this database with python locally (and eventually remotely).
If I try locally something like:
db = MySQLdb.connect(host="localhost", user="root", passwd="mysql_password", db="dbname")
I get the following error:
_mysql_exceptions.OperationalError: (1049, "Unknown database 'dbname'")
However, the database dbname does exist at /var/lib/mysql. So how to access this via python (first locally and eventually remotely)?
Solved it, it was a spelling mistake in dbname
This is my first time using PostgreSQL, I'm used to using MySQL where once you install MySQL server on Ubuntu for the first time, it'll ask you for a MySQL username and password. Once that's finished you can connect to it simply by providing:
MySQL Host: 127.0.0.1
Username: root
Password: 123pie
And from there you're ready to open up your favorite DB software like sequel pro and connect to it via SSH using the localhost IP of MySQL like shown above.
However right now my client is using PostgreSQL and so I need to learn how to set it up fast.
So far I've done this:
pip install psycopg2==2.4.5
Looks like this is just a library required for Django and Python to open up a PostgreSQL database. It doesn't look like something identical to MySQL Server.
Is installing PostgreSQL Server the next thing that I have to do? After I install that via the command line, is it exactly the same as setting up MySQL server?
I've never used PostgreSQL, I expect that it's very identical to using MySQL?
There's a nice, detailed guide on the Ubuntu-specific setup for PostgreSQL on the ubuntu community wiki. That should be your starting point.
For most applications it is sufficient to create a PostgreSQL user for the web server's username:
sudo -u postgres createuser www-data
then create a database owned by that user for the app to use:
sudo -u postgres createdb -O www-data test_django
and configure the app to connect with username www-data to the test_django database with no password. PostgreSQL on most distros, including Ubuntu, defaults to peer authentication where it requires you to have the same unix username as the postgres user you're connecting as, and doesn't require a password.
If the app forces you to supply a password and won't accept a blank one, or if you want the app to use a username different to the user that the web server runs as (i.e. to isolate multiple web apps from each other a bit), you need to add an entry to pg_hba.conf specifying md5 password authentication for that database/username combo - or just all users for all dbs.
I'm running MySQL 5.1 under Windows 7. If I start the MySQL Command Line Client and type:
show databases;
it returns:
information_schema
aircraft_taxiing
dvd_collection
eqndb
mydb
mysql
test
test_db
all of which are in the directory in my.ini:
datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"
If I open a command prompt window and type mysql it only returns:
information_schema
test
test_db.
What happened to the rest of the databases? I've been trying to connect Python to MySQL using MySQLdb and can open any of the three databases, but none of the missing ones.
My goal is to make the Python connection in the end, but I'd like to understand what's going on at the command prompt, too.
It depends on the user you are logging in as. If your user doesn't have any priviledges on those databases, you won't be able to see them.