User Tools

Site Tools


Writing /var/lib/dokuwiki/data/meta/teaching/ie0117/proyectos/2013/i/waconsys/python-mysql.meta failed
teaching:ie0117:proyectos:2013:i:waconsys:python-mysql

Relating Python with MySQL

MySQLdb is an thread-compatible interface to the popular MySQL database server that provides the Python database API, for install it:

sudo apt-get install python-mysqldb

Then it is just like using another package. So we can use a Python environment or a text file .py:

import MySQLdb

Connection objects are returned by the connect() function:

db = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database_name')

You must create a Cursor object. It will let you execute all the query you need:

cursor = db.cursor()

Executing queries is very simple in MySQL Python. All you need to do is take your cursor object and call the 'execute' function. The execute function requires one parameter, the query. If the query contains any substitutions then a second parameter, a tuple, containing the values to substitute must be given. An example:

cursor.execute("CREATE TABLE song ( id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, title TEXT NOT NULL )")
teaching/ie0117/proyectos/2013/i/waconsys/python-mysql.txt · Last modified: 2022/09/20 00:08 (external edit)