First, we will see an example of getting the database version. For that, we will create a get_database_version.py script and write the following content in it:
import MySQLdb as mdb
import sys
con_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
cur_obj = con_obj.cursor()
cur_obj.execute("SELECT VERSION()")
version = cur_obj.fetchone()
print ("Database version: %s " % version)
con_obj.close()
It is very important to follow the previous steps before running this script; they should not be skipped.
Run the script and you will get the following output:
student@ubuntu:~/work/mysql_testing$ python3 get_database_version.py
Output:
Database version: 5.7.24-0ubuntu0.18.04.1
In the preceding example, we got the database version. For that, first we imported the MySQLdb module. Then we wrote the connection string. In the connection string, we mentioned our username, password, and database name. Next, we created a cursor object that is used for executing a SQL query. In execute(), we passed an SQL query. fetchone() retrieves the next row of query result. Next, we printed the result. The close() method closes the database connection.