%reload_ext sql
# %load_ext sql
%sql postgresql://postgres:postgres@localhost/postgres
'Connected: postgres@postgres'
%sql select version(); #using %sql magic line
%sql select * from notes;
* postgresql://postgres:***@localhost/postgres 1 rows affected. (psycopg2.errors.SyntaxError) syntax error at or near "#" LINE 1: #using %sql magic line ^ [SQL: #using %%sql magic line] (Background on this error at: http://sqlalche.me/e/f405) * postgresql://postgres:***@localhost/postgres 1 rows affected.
id | body | title |
---|---|---|
1 | This is my note text. | Test note |
import psycopg2 #using psycopg2 library
"""you can define the variables separately and then use only the variables names here like in this blog
https://www.a2hosting.in/kb/developer-corner/postgresql/connecting-to-postgresql-using-python """
conn = psycopg2.connect(host="localhost", user="postgres", password="postgres", dbname="postgres")
cur = conn.cursor()
cur.execute("select * from notes")
cur.fetchall()
[(1, 'This is my note text.', 'Test note')]
conn.close()
cur.execute("select * from notes")
cur.fetchall()
--------------------------------------------------------------------------- InterfaceError Traceback (most recent call last) <ipython-input-5-43bfadbca523> in <module> ----> 1 cur.execute("select * from notes") 2 cur.fetchall() InterfaceError: cursor already closed