Log in / create account | Login with OpenID
DocForge
Programmer's Wiki

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
      ...
Do you have information or insights to contribute to this article? Please feel free to edit this page. Ask questions or contribute to the discussion on this article's talk page.