Making the most basic MySQL insert in Python 2.*

November 27th, 2016 by Alex Leave a reply »

This is a very simple example, but it might confuse you sometimes.

There are some differences from other languages like PHP or Node.js, particularly in the need to download a separate MySQL connector available on the official MySQL pages https://dev.mysql.com/downloads/connector/python/2.1.html

import mysql.connector
 
mysql_host='127.0.0.1'
mysql_port='3306'
mysql_user='user'
mysql_pass='pass'
mysql_db='test'
 
cnx = mysql.connector.connect(user=mysql_user, password=mysql_pass,
                              host=mysql_host,
                              port=mysql_port,
                              database=mysql_db)
cursor = cnx.cursor()
query = "INSERT INTO mytable SET `field1` = %s, `field2` = %s"
cursor.execute(query, ("value1", "value2"))
cnx.commit()

The main difference here is that we need to initialize a cursor, and that query arguments are all %s, there’s no support for %d or %f. That’s it.


Leave a Reply