Log in / create account
DocForge
An Open Wiki For Software Developers

Python database connectivity

From DocForge

[edit] Connecting from Python to MySQL

Import the MySQLdb library:

import MySQLdb

Connect to the database:

db = MySQLdb.connect(host, user, passwd, db)

Get a database cursor:

c=db.cursor()

Execute a SQL statement:

c.execute("SELECT id, name, date FROM schedule WHERE id = %s", (id,))

Get one record:

row = c.fetchone()
if row != None:
      (id, name, date) = row

Get all records:

rows = c.fetchall()
for row in rows:
      (id, name, date) = row
      ...