SQL connection string into function - python

I am trying to put a connection string into a function for database connection:
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server=trve-tl'
'Database=team;'
'Trusted_Connection=yes;')
with open("bike.sql", "r") as file:
query = file.read()
I have attempted to create a function as follows:
def get_connection(server:str, Database:str)->str:
global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server='+server+';'
'Database='+Database+';'
'Trusted_Connection=yes;')
return conn
I get the following error:
global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
^
SyntaxError: invalid syntax

You need to remove the 'global' keyword from your conn variable declaration, then store the output of the function in a new variable.
def get_connection(server:str, Database:str)->str:
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server='+server+';'
'Database='+Database+';'
'Trusted_Connection=yes;')
return conn
then call it something like this
cn = get_connection("localhost","MyDB")
cn.close()

Related

error :- ProgrammingError: Attempt to use a closed connection

hi all im trying to run a stored procedure using python however im getting an error below is my code
import pyodbc
import sqlalchemy
from urllib.parse import quote_plus
import sqlalchemy as sa
driver='SQL Server Native Client 11.0'
params = quote_plus(r'DRIVER={SQL Server Native Client 11.0};'
r'SERVER=i cant disclose my server ;'
r'DATABASE=ForTestPurpose;'
r'Uid='+sql_userid+';'
r'Pwd='+sql_pwd+';')
engine = sqlalchemy.create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
query= sa.text("EXEC InsertTestVisionOpenCases '"+yesterday1+"' ")
engine.execute(query)#you can try entering with parameters as how you give in your sql
engine.execution_options(autocommit=True)
cursor.close()
conn.close()
and im getting this error
ProgrammingError: Attempt to use a closed cursor.
please let me know how can i remove that error
I was able to solve the issue please check the below code it helped me to move ahead.
conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};'
r'SERVER=W-MUM-myserver_name;'
r'DATABASE=Analytics;'
r'Uid='+sql_userid+';'
r'Pwd='+sql_pwd+';')
cursor = conn.cursor()
params=date(yesterday.year,yesterday.month,yesterday.day)
storedProc = "Exec ForTestPurpose.dbo.InsertThreeVisionOpenCases #parameter1 = ?"
cursor.execute( storedProc, params )
conn.commit()
cursor.close()
conn.close()

How to solve SQL Server connection using flask error(windows auth not supported)

I get this error when trying to connect to SQL Server hosted on Azure:
pypyodbc.Error: ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver][SQL Server]Windows logins are not supported in this version of SQL Server.')
This is my code:
from flask import Flask, jsonify, render_template
import pypyodbc
app = Flask(__name__)
connection = pypyodbc.connect('DRIVER={SQL Server};'
'Server=tcp:abc,1433;Initial
'Catalog=LMSDatabase;'
'Persist Security Info=False;'
'User ID=xyz;Password=xyz;'
'MultipleActiveResultSets=False;'
'Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;')
cursor = connection.cursor()
cursor.execute("Select * from DATE_SHEET")
for r in cursor.fetchall():
print(r)
Udi and password are hidden
You need to add
Trusted_Connection=False;Encrypt=True
To your connection string
You can specify the connection string as one long string that uses semi-colons (;) as the argument separator.
Working example:
import pyodbc
cnxn = pyodbc.connect(r'Driver={SQLServer};Server=.\SQLEXPRESS;Database=myDB;Trusted_Connection=yes;')
cursor = cnxn.cursor()
cursor.execute("Select * from DATE_SHEET")
for r in cursor.fetchall():
print(r)
cnxn.close()

Unable to write to SQL Server even when using parameters

The SQL Server has these properties.
I want to write df to a SQL Server table but I get an error "table does not exist".
What am I doing wrong?
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-FCBC9GE/NEW_INSTANCE;'
'Database=master;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM df')

Python connect to sql server using AES decrypted password

I have an application (not mine) which has config file with an encrypted password and I guess it uses AES.
I would like to write a small python code to test connection using this encrypted password to make sure I can use it.
But I do not know how to use the encrypted password to the code
conn = pyodbc.connect('Driver={SQL Server};'
'Server=192.168.10.1;'
'Database=AUIS;'
'uid=sa;'
'pwd=BR+vNRCyv0pxHF97Aad2JA==;')
cursor = conn.cursor()
cursor.execute('SELECT * FROM AUIS.Table')
for row in cursor:
print(row)````
Try to add ColumnEncryption
conn = pyodbc.connect('Driver={SQL Server};'
'Server=192.168.10.1;'
'Database=AUIS;'
'uid=sa;'
'pwd=BR+vNRCyv0pxHF97Aad2JA==;'
'ColumnEncryption=Enabled;')

how can I connect to a postgresql database from external psycopg2.connect?

I would like to connect to a postgresql database using python from a different server.
I triyed this :
conn_string = "host=192.168.1.1 dbname='"+db7+"' user='user' password='"+pw7+"'"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
but I get the error:
conn = psycopg2.connect(conn_string)
File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL: database "database" does not exist
Remove unnecessary quotes in the syntax.
Follow this structure.
conn = psycopg2.connect(host = "localhost",database="ur_database_name", user="db_user", password="your_password")
Example.
conn = psycopg2.connect(host = "localhost",database="studentesdb", user="postgres", password="admin")

Categories

Resources