catherinedevlin / ipython-sql

%%sql magic for IPython, hopefully evolving into full SQL client
MIT License
1.79k stars 370 forks source link

How to use magic sql function when connecting using psycopg2? #175

Open pratikchhapolika opened 4 years ago

pratikchhapolika commented 4 years ago

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?

idomic commented 1 year ago

@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)