Forums

Access MySQL DB from python script

Hi,

I am trying to fetch data from db.

command = "mysql -N -u<username> -p<password> -hmysql.server <databaseName> -e "
selectSql = "Some select Statement"
responseData=execute_command_local(command+"\""+selectSql+"\"")

def execute_command_local(command):
    results = os.popen(command).read()
    return results.strip("\n")

But I am recieving this error

ERROR 1044 (42000): Access denied for user  '<username>'@'%' to database '<username>'

Any help would be appreciated.

Thank You in advance.

your database name on PythonAnywhere always contains a prefix formed of your username plus the character "$". So make sure you specify the database name as 'username$databasename'. You may need to add quotes.

In other news, if you're working with mysql from a python script, you will probably find life easier if you use one of the db-api libraries, like mysql-connector or mysql-db (we have both installed for python 2, and you can install options for python 3 as well).

More info:

https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

https://www.pythonanywhere.com/wiki/UsingMySQL

http://mysql-python.sourceforge.net/MySQLdb.html#some-examples

This was really helpful! It resolved my error.

Thanks Harry

hooray! but, seriously, don't use os.popen to run sql commands from python. use one of the mysql libraries. your life will be much easier :)

Yes Harry, I realized that and I am currently changing my code. I am migrating to 'mysql.connector'

I really appreciate your effort. Thank You very much!

:) we're here if you need any help!