forked from sunscrapers/flask-boilerplate
/
playground_core.py
79 lines (59 loc) · 2.58 KB
/
playground_core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Getting Started
# ----------------------------------------------------------------------
from sqlalchemy import create_engine, select
engine = create_engine("postgresql://postgres@127.0.0.1/flask_example", echo=True)
conn = engine.connect()
select_query = select([1])
# Fetch all
result_proxy = conn.execute(select_query)
print 'All', result_proxy.fetchall()
# Fetch one
result_proxy = conn.execute(select_query)
print 'One', result_proxy.fetchone()
# Fetch scalar
result_proxy = conn.execute(select_query)
print 'Scalar', result_proxy.scalar()
# ----------------------------------------------------------------------
# SELECTing directly
# ----------------------------------------------------------------------
result_proxy = conn.execute("SELECT id, first_name, last_name FROM users")
print 'All', result_proxy.fetchall()
result_proxy = conn.execute("SELECT id, first_name, last_name FROM users")
print 'One', result_proxy.fetchone()
# ----------------------------------------------------------------------
# SELECTing directly with WHERE clause
# ----------------------------------------------------------------------
result_proxy = conn.execute("SELECT id, first_name, last_name FROM users WHERE first_name = 'David'")
print 'All', result_proxy.fetchall()
result_proxy = conn.execute("SELECT id, first_name, last_name FROM users WHERE first_name = 'David'")
print 'One', result_proxy.fetchone()
# ----------------------------------------------------------------------
# SELECTing directly with WHERE clause and bindparams
# ----------------------------------------------------------------------
from sqlalchemy import text
result_proxy = conn.execute(
text("SELECT id, first_name, last_name FROM users WHERE first_name = :first_name"),
first_name="David"
)
print 'All', result_proxy.fetchall()
result_proxy = conn.execute(
text("SELECT id, first_name, last_name FROM users WHERE first_name = :first_name"),
first_name="David"
)
print 'One', result_proxy.fetchone()
# ----------------------------------------------------------------------
# SELECTing With A Schema
# ----------------------------------------------------------------------
from sqlalchemy import literal_column, table
select_query = select([
literal_column('first_name'),
literal_column('last_name')
]).select_from(table('users'))
# Fetch all
result_proxy = conn.execute(select_query)
print 'All Literal', result_proxy.fetchall()
# Fetch one
result_proxy = conn.execute(select_query)
print 'One Literal', result_proxy.fetchone()