The ability to create users is obviously an administrative task. By default, this means that one must log in as root, or any other user who has administrative rights, to use them. If your Python program does not login as root, it will not be able to affect user creation. Therefore, one's connection credentials must read accordingly:
import MySQLdb
mydb = MySQLdb.connect(host = 'localhost',
user = 'root',
passwd = 'rootsecret')
cursor = mydb.cursor()
From here, one can similarly form the statement to the other CREATE statements that we have used.
statement = """CREATE USER 'exemplar'@'localhost' IDENTIFIED BY 'MoreSecurity'"""
cursor.execute(statement)
In a Python shell, passing the statement through cursor.execute() will return 0L.
If you execute this code in a Python program file, you will not get
such feedback (unless you overtly tell Python to print it). But for
debugging purposes, you have two choices: check the MySQL users table or
try to use the login.
The latter is simply a matter of creating a second connection. This is best placed in a try...except structure:
try:
mydb2 = MySQLdb.connect(host = 'localhost',
user = 'exemplar',
passwd = 'MoreSecurity')
cursor2 = mydb2.cursor()
except:
raise
We can check the MySQL users table manually or within a program. To affect a check manually, log into MySQL and select the mysql database for use.
Within mysql, read out from the user table.
Depending on how many users are registered in the
database, this table will probably run off the screen. However, the last
entry should be the account just created. Alternatively, use a WHERE clause to quantify what you want.
SELECT * FROM users WHERE User = '<userid>';
So for the user exemplar, we would enter the following statement:
SELECT * FROM user WHERE User='exemplar';
Within Python, we can issue the last statement as follows:
mycheck = MySQLdb.connect(host = 'localhost',
user = 'root',
passwd = 'rootsecret',
db = 'mysql')
checker = mycheck.cursor()
statement = """SELECT * FROM user WHERE User='exemplar'"""
results = checker.execute(statement)
if results == 1:
print "Success!"
else:
print "Failure."
Using the user ID in the statement saves us from having to match each record against that value.