ipython-sql
ipython-sql copied to clipboard
How to use magic sql function when connecting using psycopg2?
Here is my code to connect to database:
import pandas as pd
import psycopg2
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
import matplotlib as mpl
import pandasql as ps
# Hide warnings
import warnings
warnings.filterwarnings('ignore')
db = '**'
host = '**'
port = '**'
user = 'user_name'
password = 'password'
try:
#Create a connection to the database
conn = psycopg2.connect(database=db,
host=host,
port=port,
user=user,
password=password,
sslmode='require')
print("Successfully connected to the database...")
except Exception as e:
print("Connection failed... \n" + str(e)) #Return message if unable to connect
exit(1)
q="""SELECT DISTINCT * FROM schema.table_name """
data=pd.read_sql(q, conn)
Question1: How to use magic function here?
@pratikchhapolika There are multiple ways of doing so. You don't really need to set the connection via psycopg2, you can follow this guide for connecting, or pass an existing engine like you have in the sample above via this guide (I'd use this only if you have a use case for it)