How to querying in Snowflake using Python (SSO Authentication)? - python

I tried to connect snowflake(SSO Authentication) and get data from table.
But, When i run the code, i can login with my credentials in the pop-up browser window and it connect Snowflake, no response after that(the program neither terminate nor provide result).
Not sure, where am doing mistake, Pls help.
'''
import snowflake.connector
# Connecting to Snowflake using SAML 2.0-compliant IdP federated authentication
conn = snowflake.connector.connect(
user='G*****K',
account='abcdf',
authenticator='externalbrowser',
warehouse='abcdf',
database='abcdf',
schema='abcdf'
)
cur = conn.cursor()
sql = "select * from abcdf.ACCT limit 10"
x=cur.execute(sql)
cur.close()
print(x)
'''

I believe you are closing the cursor before the print;
try:
cur.execute("SELECT col1, col2 FROM test_table ORDER BY col1")
for (col1, col2) in cur:
print('{0}, {1}'.format(col1, col2))
finally:
cur.close()
Details: https://docs.snowflake.com/en/user-guide/python-connector-example.html#using-cursor-to-fetch-values

Results of the query are stored in cursor. The contents of cursor may then be stored in a local variable.
Also, best practice to close connection in the end.
https://www.psycopg.org/docs/cursor.html
import snowflake.connector
# Connecting to Snowflake using SAML 2.0-compliant IdP federated authentication
conn = snowflake.connector.connect(
user='G*****K',
account='abcdf',
authenticator='externalbrowser',
warehouse='abcdf',
database='abcdf',
schema='abcdf'
)
cur = conn.cursor()
sql = "select * from abcdf.ACCT limit 10"
cur.execute(sql)
print(cur.fetchall())
cur.close()
conn.close()

Related

psycopg2 with Postgres fetchall works but not execute

I am trying to execute some Postgres queries with psycopg2.
import psycopg2
conn = psycopg2.connect(
host="test.postgres.database.azure.com",
database="postgres",
user="test",
password="test")
cur = conn.cursor()
sql = "select site_panel from test.ws_sites"
cur.execute(sql)
rows = cur.fetchall()
The query above works well and returns the data but the following query does not delete the table as intended.
cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
Anything wrong I'm doing here?
A query that modifies table data or schema structure needs to be committed:
cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
conn.commit()
Alternatively, place
conn.autocommit = True
after creating the connection.

PostgreSQL Error while executing sql command in Python

i've been trying to get some data from my db by using below code, but the code is not working. is there any mistake that i made in the code, if so how can i fix it.
NOTE: i took the below code from just a script not a django or flesk web app.
def db():
conn = psycopg2.connect(
"dbname=mydb user=postgres password=****** host=*.*.*.*")
cur = conn.cursor()
cur.execute("""SELECT * FROM MddPublisher""")
query_results = cur.fetchall()
print(query_results)
db()
ERROR: psycopg2.errors.UndefinedTable: relation "mddpublisher" does not exist LINE 1: SELECT * FROM MddPublisher
additionally,i want to show below code to prove that connection is ok. the problem is that i can't receive data from my db whenever i try to execute select command through python.
def print_tables():
conn = psycopg2.connect(
"dbname=mydb user=postgres password=***** host=*.*.*.*.*")
cur = conn.cursor()
cur.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cur.fetchall():
print(table)
print_tables()
OUTPUT:
('MddPublisher',)
This is probably an issue with case sensitivity. Postgresql names are usually normalized to lower case. However, when used inside double quotes, they keep their case. So, to access a table named MddPublisher you must write it like "MddPublisher".
All the gory details are in Section 4.1.1, Identifiers and Key Words in the Postgresql 14 docs.

How can I connect to Impala using a keytab?

I am trying to establish a connection to the impala database through a Python script using a keytab instead the normal user/password combination, but am unable to find any tutorials online whatsoever, the code I am currently using is:
conn = connect(host=impala_host, port=impala_port, use_ssl=True, auth_mechanism="PLAIN", user=username, password=pwd, database=impala_db)
cursor = conn.cursor()
However, I want to connect using keytab instead of my password.
It appears that you are trying to use that library: https://github.com/cloudera/impyla
Please have a look at Usage section in README.md there:
from impala.dbapi import connect
conn = connect(host='my.host.com', port=21050)
cursor = conn.cursor()
cursor.execute('SELECT * FROM mytable LIMIT 100')
print cursor.description # prints the result set's schema
results = cursor.fetchall()
...
...

Connect python to Sybase IQ

First of all thank you for your help.
I was trying to retrieve some data from a sybase IQ database using python, but I can not make it.
I've tried with the following code( from https://github.com/sqlanywhere/sqlanydb):
import sqlanydb
conn = sqlanydb.connect(uid='dba', pwd='sql', eng='demo', dbn='demo' )
curs = conn.cursor()
curs.execute("select 'Hello, world!'")
print( "SQL Anywhere says: %s" % curs.fetchone() )
curs.close()
conn.close()
Unfotunately it gives me the following error:
InterfaceError: ('Could not load dbcapi. Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib', 0)
Does anyone know how to fix it?
Thanks in advance
Jessica
On windows, first you need to add the data source name (DSN).
You do this by searching for 'odbc data source administrator' on windows and creating a DSN for 'SQL Anywhere 12'. Fill in the necessary information like username,password,host,port,server name and database name. Finally test the connection as shown.
Once finished you can call the code as follows:
import sqlanydb
conn = sqlanydb.connect(dsn='SYBASE_IQ')
curs = conn.cursor()
curs.execute("select 'Hello, world!'")
print( "SQL Anywhere says: %s" % curs.fetchone())
curs.close()
conn.close()
Get and install the SYBASE ODBC DRIVER.
Configure the DSN on your PC.
On Windows, search for the Microsoft ODBC Administrator. Then create a DSN.
Python code:
using SQLAchemy
import sqlalchemy as sa
from sqlalchemy import create_engine, event
from sqlalchemy.engine.url import URL
import urllib
params = urllib.parse.quote_plus('DSN=dsn_name;PWD=user_pwd')
engine = sa.create_engine("sybase+pyodbc:///?odbc_connect={}".format(params))
with engine.connect() as cursor:
cursor.execute(""" SELECT * FROM database """)
Using PyODBC
import pyodbc
conn = pyodbc.connect('DSN=dsn_name;PWD=user_pwd')
with conn:
cursor = conn.cursor()
cursor.execute(""" SELECT * FROM database """)

python pyscopg2 unable to select data from AWS redshift

I have a postgres database on AWS redshift. Currently I use Python Pyscopg2 to interact with the database. I find that I can run:
curosr.execute("INSERT INTO datatype VALUES (%s, %s)", ("humidity", "some description"))
connect.commit()
but when I do:
for row in cursor.execute("SELECT * FROM datatype"):
print(row)
what ever I do, it always returns me None Type. Anyone can give me advice that what is the correct way to interact with redshift postgres?
Thank you
As required, here's the whole code
##encoding=utf8
from __future__ import print_function
import psycopg2
def connect():
conn = psycopg2.connect(host = "wbh1.cqdmrqjbi4nz.us-east-1.redshift.amazonaws.com",
port = 5439,
dbname = "dbname",
user = "user",
password = "password")
c = conn.cursor()
return conn, c
conn, c = connect()
c.execute("INSERT INTO table netatmo VALUES (%s, %s)", (1, 10.5))
conn.commit() # this works, and I can see the data in other db client software
for row in c.execute("SELECT * FROM netatmo").fetchall(): # this not working
print(row) # AttributeError: 'NoneType' object has no attribute 'fetchall'
you missed "fetchall()",
when updating - you don't need it, but when selecting - you have to fetch the results
http://initd.org/psycopg/docs/cursor.html
your code should look like this:
cursor.execute("SELECT * FROM datatype;")
for row in cursor.fetchall():
print(row)

Categories