Basics: How to use PyMysql
March 16, 2018    |    Basics    |    How To    |    Python

PyMysql is a great package for interacting with databases. Here is a little quick start guide for using it:

Connect to a MySQL server:

import pymysql

connection = pymysql.connect(host='<ip-or-domain>',
                             user='<dbuser>',
                             password='<dbpass>',
                             db='<dbname>',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor,
                             autocommit=True)

Insert into a table:

cursor = connection.cursor()
sql = "INSERT INTO content (`title`, `content`) VALUES ('{0}', '{1}')".format("My Title", "My Content")
cursor.execute(sql)
cursor = connection.cursor() 
sql = "INSERT INTO content (`title`, `content`) VALUES ('{0}', '{1}')".format("My Title", "My Content") cursor.execute(sql)

Fetch rows from a database:

cursor = connection.cursor()
cursor.execute("SELECT * FROM content;")
result = cursor.fetchall() # Array of objects