-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQL_Python.py
92 lines (53 loc) · 1.41 KB
/
PostgreSQL_Python.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
80
81
82
83
84
85
86
87
88
89
90
91
# coding: utf-8
# # Using PostgreSQL in Python (with Psycopg2)
#
# ### Psycopg2
#
# A library that allows Python to connect to an existing PostgreSQL database to utilize SQL functionality.
#
# #### Documentation
# * http://initd.org/psycopg/docs/install.html
#
# In[ ]:
# After installing with pip install psycopg2
import psycopg2 as pg2
# In[ ]:
# Create a connection with PostgreSQL
# 'password' is whatever password you set, we set password in the install video
conn = pg2.connect(database='postgres', user='postgres',password='password')
# In[ ]:
# Establish connection and start cursor to be ready to query
cur = conn.cursor()
# In[ ]:
# Pass in a PostgreSQL query as a string
cur.execute("SELECT * FROM payment")
# In[ ]:
# Return a tuple of the first row as Python objects
cur.fetchone()
# In[ ]:
# Return N number of rows
cur.fetchmany(10)
# In[ ]:
# Return All rows at once
cur.fetchall()
# In[ ]:
# To save and index results, assign it to a variable
data = cur.fetchmany(10)
# **Inserting Information**
# In[2]:
query1 = '''
CREATE TABLE new_table (
userid integer
, tmstmp timestamp
, type varchar(10)
);
'''
# In[ ]:
cur.execute(query1)
# In[ ]:
# commit the changes to the database
cur.commit()
# In[ ]:
# Don't forget to close the connection!
# killing the kernel or shutting down juptyer will also close it
conn.close()