Log in to the MySQL server without a database name in PyQt

advertisements

I am creating a PyQt application that stores its data in a MySQL database. I want my application to be able to auto-create the database on first run. However, I couldn't find any function to connect to the MySQL Server without specifying a database name.

I know that MySQL Server provides the functionality to connect to it without specifying a database name, as per the MySQL documentation:

For mysql, the first nonoption argument is taken as the name of the default database. If there is no such option, mysql does not select a default database.

How do I do this from my PyQt application?

Additionally, some online resources have suggested connecting to the MySQL server by specifying the names of one of the default databases created by MySQL. How do I create a new database in such a case?


You can connect to the mysql database as the mysql admin user, that should always be present in a healthy mysql environment. Then you can create a new database, close the connection and reconnect to the newly created database:

import MySQLdb
db=MySQLdb.connect(user=MySQLADMIN,password=MYSQLADMINPASSWORD,db="mysql")
c = db.connect()
c.execute("""CREATE DATABASE yourdatabasename;""")
c.execute("""GRANT ALL PRIVILEGES ON yourdatabasename.* TO 'yourusername' IDENTIFIED BY 'youruserpassword';""")
c.close()

db = MySQLdb.connect(user=yourusername,password=youruserpassword,db="yourdatabasename")
c = db.connect()
<your dbase code here>