· 9 years ago · Oct 19, 2016, 07:04 PM
1import psycopg2
2from psycopg2.extras import RealDictCursor
3
4
5dsn = """host='localhost' port='5432'
6 dbname='mydb' user='pg' password='pg'"""
7con = psycopg2.connect(dsn, cursor_factory=RealDictCursor)
8
9create_table = '''
10 drop table if exists users;
11 create table users (
12 id serial primary key not null,
13 username varchar(255) not null
14 );
15'''
16
17insert_data = '''
18 insert into users (id, username)
19 values (%(id)s,%(username)s);
20'''
21
22
23with con.cursor() as cursor:
24 cursor.execute(create_table)
25 cursor.execute(insert_data, {'id': 1, 'username': 'fred'})
26 fred = cursor.execute("select * from users where username == 'fred';")