codegurukool.com · Free coding tutorials & online compiler

Home › Python Tutorial › Python databases: MySQL and MongoDB

Python databases: MySQL and MongoDB

Store data permanently.

Python talks to databases through drivers: mysql-connector-python for MySQL and pymongo for MongoDB. The built-in sqlite3 module works the same way and needs no server, so it is a good way to practise. Always pass values as parameters (?), never by joining strings.

Example code

import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE users (name TEXT, age INT)")
cur.execute("INSERT INTO users VALUES (?, ?)", ("Ada", 36))
for row in cur.execute("SELECT name, age FROM users"):
    print(row)

Run this code in the online editor

← Python data structures and algorithmsLive project: Expense tracker →