-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpostgresql.txt
More file actions
90 lines (57 loc) · 2 KB
/
postgresql.txt
File metadata and controls
90 lines (57 loc) · 2 KB
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
80
81
82
83
84
85
86
87
88
89
90
## Notes on PostgreSQL
brew install postgresql
To start postgres once:
postgres -D /usr/local/var/postgres
Or install lunchy:
gem install lunchy (allows easy start/stop of Postgres)
Install launch agent in the right place:
cp /usr/local/Cellar/postgresql/9.4.4/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
To start and stop postgres:
lunchy start postgres
lunchy stop postgres
---
create a new database
createdb tempdb
Then connect with
psql -d tempdb
---
RPostgreSQL package
library(DBI)
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="tempdb", host="localhost")
summary(con)
dbWriteTable(con, "mtcars", mtcars)
dbListTables(con)
rs <- dbSendQuery(con, "select * from mtcars")
fetch(rs) # grab everything (default n=-1)
rs <- dbSendQuery(con, "select * from mtcars")
fetch(rs, n=5) # grab 5 rows
fetch(rs) # grab the rest
rs <- dbSendQuery(con, "select * from mtcars where cyl =4")
x <- fetch(rs)
dbDisconnect(con)
con <- dbConnect(drv, dbname="bpsimple", host="localhost") # db from Apress book
rs <- dbSendQuery(con, paste('SELECT customer.fname, customer.lname,',
'count(orderinfo.orderinfo_id) AS "no. orders"',
'FROM orderinfo, customer',
'WHERE orderinfo.customer_id = customer.customer_id',
'GROUP BY customer.customer_id'))
fetch(rs)
dbDisconnect(con)
---
python: psycopg2
to install psycopg2:
conda install -c https://conda.binstar.org/anaconda psycopg2
sudo ln -s /Users/kbroman/.anaconda/anaconda/lib/libssl.1.0.0.dylib /usr/lib
sudo ln -s /Users/kbroman/.anaconda/anaconda/lib/libcrypto.1.0.0.dylib /usr/lib
Basic use:
import psycopg2
con = psycopg2.connect("dbname='bpsimple' host='localhost'")
cur = con.cursor()
cur.execute("SELECT * from customer")
rows = cur.fetchall()
---
Dates
cast('2004-06-23' as date)
select * from orderinfo where date_placed > cast('2004-06-23' as date);