Skip to content

Instantly share code, notes, and snippets.

@rebeccabilbro
Forked from bbengfort/contacts.py
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebeccabilbro/3ee78ad0484867036ccb to your computer and use it in GitHub Desktop.
Save rebeccabilbro/3ee78ad0484867036ccb to your computer and use it in GitHub Desktop.
import os
import sqlite3
def create_tables(conn):
conn.execute("CREATE TABLE contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT)")
conn.commit()
def connect(path="contacts.db", syncdb=False):
"""
Connects to the database and ensures there are tables.
"""
if not os.path.exists(path):
syncdb=True
conn = sqlite3.connect(path)
if syncdb:
create_tables(conn)
return conn
def insert(name, email, conn=None):
if not conn: conn = connect()
sql = "INSERT INTO contacts (name, email) VALUES (?, ?)"
conn.execute(sql, (name, email))
conn.commit()
if __name__ == "__main__":
name = raw_input("Enter name: ")
email = raw_input("Enter email: ")
conn = connect()
insert(name, email, conn)
contacts = conn.execute("SELECT count(id) FROM contacts").fetchone()[0]
print "There are now %i contacts" % contacts
conn.close()
from pymongo import MongoClient
from datetime import datetime
def connect(database="contacts", host="localhost", port=27017):
"""
Connects to the database
"""
client = MongoClient(host, port)
return client[database]
if __name__ == "__main__":
entry = {
"name": raw_input("Enter name: "),
"email": raw_input("Enter email: "),
"created": datetime.now()
}
while True:
key = raw_input("Add key: ")
if not key: break
val = raw_input("Add val: ")
if not val: break
entry[key] = val
db = connect()
collection = db.contacts
collection.insert(entry)
print "There are now %i documents in contacts" % collection.count()
"""
Database already created:
CREATE TABLE contacts (
id SERIAL NOT NULL,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
CONSTRAINT contacts_pkey PRIMARY KEY (id));
"""
import os
import psycopg2
def connect(db, user, password, host="localhost", port=5432):
"""
Connects to the database and ensures there are tables.
"""
conn = psycopg2.connect(**{
"database": db,
"user": user,
"password": password,
"host": host,
"port": port
})
return conn
def insert(name, email, conn=None):
if not conn: conn = connect()
cursor = conn.cursor()
sql = "INSERT INTO contacts (name, email) VALUES (%s, %s)"
cursor.execute(sql, (name, email))
conn.commit()
if __name__ == "__main__":
name = raw_input("Enter name: ")
email = raw_input("Enter email: ")
conn = connect("contacts", "example", "password")
insert(name, email, conn)
cursor = conn.cursor()
cursor.execute("SELECT count(id) FROM contacts")
contacts = cursor.fetchone()[0]
print "There are now %i contacts" % contacts
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment