ipython-sql icon indicating copy to clipboard operation
ipython-sql copied to clipboard

How to use magic sql function when connecting using psycopg2?

Open pratikchhapolika opened this issue 5 years ago • 1 comments

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 avatar Jul 13 '20 13:07 pratikchhapolika

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

idomic avatar Dec 29 '22 22:12 idomic