Skip to content
davispuh edited this page Aug 12, 2012 · 1 revision

just small usage example, can save it to file and test if library works successfully

# import MySQLdb module
import MySQLdb

# connect to MySQL using specified settings (everyone of them are optional)
connection = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="information_schema", charset="utf8")

# open cursor
cursor = connection.cursor()

# execute MySQL query
# can use full power of [1] Format String
# also parameters are auto escaped by library using mysql_real_escape_string
# or if not supported by MySQL then mysql_escape_string
cursor.execute("SELECT TABLE_NAME, ENGINE, TABLE_COLLATION\
                FROM TABLES\
                WHERE TABLE_SCHEMA = {schema_name}\
                ORDER BY TABLE_NAME ASC", {"schema_name":"information_schema"})

# display row count 
print("Total Rows: {}".format(cursor.rowcount))

# get description about query, eg. column names, etc.
description = cursor.description

column_string = ""
# join all column names
for column in description:
    column_string+=column[0]+" | "
print("\n | "+column_string+"\n")

# fetch all rows
query_rows = cursor.fetchall()

# process each row
for row in query_rows:
    value_string = ""
    # join row's values
    for value in row:
        value_string+=value+" | "
    print(" | "+value_string)

# close cursor 
cursor.close()

# can also close connection if done with database
connection.close()

Note

cursor.execute(query, args) doesn't accept % formating and that's intended, but it wouldn't be hard to add switch to support both. And args can be Dict, Tuple, List, String. ie. cursor.execute("SELECT {}, {}, {}", (1,2,3)) or just cursor.execute("SELECT {}", "Nice")

[1] Python 3 Format String

Clone this wiki locally