MySQLdb is a Python library to use MySQL database. MySQLdb is the first database wrapper i ever used. Its quite simple and good. Anyone who knows MySQL commands can use MySQLdb with ease.
First step is to import MySQLdb to your code
Importing
Connecting to MySQL. The parameters we need to connect for DB are db user name, password for that user, host address and the db name. With these data was make a connection to the db from our code.
Connection
host_ip = "localhost"
user_name = "admin"
password = "secret"
db_name = "dictionary"
db_connection = MySQLdb.connect(host = host_ip, user = user_name, passwd = password, db = db_name)
Now that we have the connection, we can perform db operations. For using the db operation methods we need to create a cursor of the db connection. The cursor class provides the methods that we acn use to do db operations.
Cursor
db_cursor = db_connection.cursor()
Lets try a SELECT operation with the cursor. Lets say that the db dictionary has a table named word_meanings. And lets try selecting one meaning for a word. The table has three feilds namely id, word, meaning.
SELECT one row
db_cursor.execute("SELECT * FROM word_meanings WHERE word = 'data'")
result = db_cursor.fetchone()
The result in variable meaning is a tuple. The tuple contains all the data in that particular row selected
Result
result = (1273, 'data', 'Facts and statistics collected together for reference or analysis')
meaning = result[2]
What if you want to select more than one row. If the word has more than one menings. In that case we can use fetchmany(n) where the n number of rows will be selected. Or fetchall() will select all rows that satisfies your query.
SELECT multiple rows
db_cursor.execute("SELECT * FROM word_meanings WHERE word = 'data'")
result = db_cursor.fetchall()
In this case the variable result will be a tuple of tuples.
Result
result = (
(1273, 'data', 'Facts and statistics collected together for reference or analysis')
(1274, 'data', 'These data represent the results of our analyses')
(1275, 'data', 'information in numerical form that can be digitally transmitted or processed ')
)
For any MySQL query like SELECT, SHOW, DESC that returns a set of data, we need to do fetchone(), fetchall() or fetchmany(n). For those query dont return any data such as INSERT, UPDATE, CREATE, we just need to do execute() alone.
Now lets try an INSERT query. We have just made a new contribution to English dictionary. So gonna insert the word and its meaning to table word_meanings.
INSERT
db_cursor.execute("INSERT INTO word_meanings(word, meaning) VALUES ('indictionariate', 'A word that is not in the dictionary')")
But as we are programmers, we dont want to pass a string query to execute().Instead we would prefer to pass only the required data to the query and not making the whole query all the time.
Passing Data to Query
new_word = "indictionariate"
word_meaning = "A word that is not in the dictionary"
db_cursor.execute("INSERT INTO word_meanings(word, meaning) VALUES (%s, %s)", (new_word, word_meaning))
Which is equal to
Updating Query
query = "INSERT INTO word_meanings(word, meaning) VALUES (%s, %s)" % (new_word, word_meaning)
db_cursor.execute(query)
What if you want to make multiple entries with same query. I know you must be thinking about using a loop over the above code to do this. Well its not a bad idea. But MySQLdb has its own method to do the same.
Multiple Querying
db_cursor.execute("INSERT INTO word_meanings(word, meaning) VALUES (%s, %s)",
[(word1, meaning1),
(word2, meaning2),
(word3, meaning3)]
)
So this is how you used MySQLdb. A vey important thing is to close a db connection once usage is done. You dont wanna leave a connetion open. Bad for your MySQL server. So always the final step of your db operation is close the db commection.
Closing DB Connection
Even though MySQLdb is good and simple, i wont advise it to be used for a long running program, which is very dynamic. It is good for a one shot code. For long running processes use some ORMs.