-1

all, I'm trying to verify a given MySQL server's connectivity through Python, provided with host, username, password, and schema. I tried to use subprocess module, Ex.

subprocess.check_call(['mysql', '-u', 'root'])

but it will bring up mysql in the terminal, which is not what I want. I also tried mysqldb, but it does not support Python 3+.

Is there a way to test out a MySQL server's parameters through Python? At least I want to know if it connects. It would be better if I could know more detail about the failure of connection.

Thanks!

1

3 Answers 3

1

According to this question, you can check out PyMySQL for Python 3.3+

If you really want to use subprocess, you can add the '-e' flag to execute a command in mysql.

subprocess.check_call(['mysql', '-u', 'root', '-ppass', '-e', "show databases;"])
Sign up to request clarification or add additional context in comments.

1 Comment

I guess I will try PyMySQL.
0


import pymysql

def MySQLCheck(*args, **kwargs):
    try:
        conn = pymysql.connect(*args, **kwargs)
        cursor = conn.cursor()
        cursor.execute("show databases;")
        r = cursor.fetchall()
        conn.close()
        return r
    except Exception as e: return e

Usage examples:

>>> print(MySQLCheck(host="localhost", user="root", password="pass"))
(2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
>>> # Later, when I started the server:
(1045, "Access denied for user 'root'@'localhost' (Using password: YES)")
>>> # Later, when I started MySQL server with "--skip-grant-tables" option:
(('information_schema',), ('drupal',), ('forum',), ('mysql',), ('p

erformance_schema',), ('phpmyadmin',), ('plugin',), ('test',))

Please note that returned values of MySQLCheck() may be an exception or a tuple if all went fine and query got executed.

To install PyMySQL for Python3 on Ubuntu/Debian do:

$ sudo apt-get install python3-setuptools
$ sudo easy_install3 pip
$ sudo pip3.2 install PyMySQL

I hope this is an answer you needed.

4 Comments

I'm not sure what your code does, but I tried it and it doesn't do much. What I really I want to know is that if the given parameters of a MySQL server is valid, i.e. if it connects. Thanks tho.
That was an example. I'll produce some working code later today and post it. I am in a hurry at the moment.
Did you try PyMSQL instead of MySQLdb? It should work.
@JACK Yey! PyMySQL works on Python 3 with no problems. In fact it has a Python 3 version. I edited my answer completely and put up code I think you need. Good luck!
0

You can use something like this. A config file with your connection parameters and a try statement with error checking.

Create a file called config.py

config = {
  'user': 'username',
  'password': 'password',
  'host': 'host_name or ip',
  'database': 'database',
  'raise_on_warnings': True,
}

Using mysql.connenctor

try:
   cnx = mysql.connector.connect(**config)

   cursor = cnx.cursor()

        query = ("select statement")         

        cursor.execute(query)

   cursor.close()
   cnx.close()

except mysql.connector.Error as err:
   if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
   elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exists")
   else:
        print(err)
else:
   cnx.close()

2 Comments

Does it support both python 2.x and python 3.x?
See dev.mysql.com/doc/connector-python/en/…. Yes, both are supported. Syntax may be slightly different with 3.x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.