odbc connection in python - python

i am writing this code but nothing is happening
import pyodbc
def main():
conn = pyodbc.connect("DRIVER={SQL Server}; server=DESKTOP;database=master;Trusted_Connection=yes;autocommit=TRUE")
cursor = conn.cursor()
query ="create table Python_
ticket(ID int IDENTITY (1,1),NAME text,GENDER text, Comment text)"
cursor = conn.execute(query)
if __name__ == "__main__": main()

Try adding a print(cursor) statement at the end of the main() function, and see what cursor is.

Related

OpenTelemetry is not tracing SQL Statements while using cursor_factory as NamedTupleCursor

Kindly look at the code below. I'm using opentelemetry for tracing. Psycopg2Instrumentor for PostgreSQL tracing. Here only the "show server_version" SQL statement is getting traced. But the SQL statement in execute method is not traced. I think it's because of using NamedTupleCursor cursor_factory. If I remove NamedTupleCursor, it's tracing the main SQL statements. Could you please help me to trace the main SQL statement without removing NamedTupleCursor?
def self.get_connection():
#conn = create_connection()
with conn.cursor() as curs:
curs.execute("show server_version") ---> this sql statement is getting tracked
return conn
def execute()
with self.get_connection() as conn:
with conn.cursor(cursor_factory=NamedTupleCursor) as curs:
curs.execute("Sql statements"). ---> this sql statement is **not** getting tracked```
Below is the code snippet for working with Psycopg2Instrumentor for PostgreSQL tracing. The instrumentation code to be updated on passing cursor_factory in cursor parameter, rather than setting it in connection. For now, the below works for me and tracing got captured.
import psycopg2
from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor
Psycopg2Instrumentor().instrument()
#add your cursor factory in connection method
cnx = psycopg2.connect(
host=host, database=DBname, user=user, password=password, cursor_factory=RealDictCursor)
#remove the cursor factory from cursor method
cursor = cnx.cursor()
cursor.execute("SELECT statement")
cursor.close()
cnx.close()
Thanks to the thread (Psycopg2Instrumentor doesn't work for cursors with non-default cursor_factory) and #RaguramGopi

create oracle connection using function in python

I'm trying to create a function for oracle connection which will take the parameters as mentioned in below code, but seems some issue...
could anyone please help in understanding how it can be corrected and what i'm missing here?
import cx_Oracle
def sqlconnect(user,passwd,SID, query):
connStr = cx_Oracle.connect('user/passwd#SID')
cursor = connStr.cursor()
cursor.execute(query)
return cursor.fetchall()
if __name__ == '__main__':
sqlconnect('user','password','XEE','select * from dual')
Thanks in advance!
The string user/passwd#SID is not a valid connect string. Unless XEE is a tnsnames.ora entry you need to reference the host and service name in your connect string. You probably want something like this, instead:
def sqlconnect(user, passwd, dsn, query):
conn = cx_Oracle.connect(user=user, password=passwd, dsn=dsn)
cursor = conn.cursor()
cursor.execute(query)
return cursor.fetchall()
if __name__ == '__main__':
host = "my_host_name"
service_name = "XEE"
conn_string = f"{host}/{service_name}"
sqlconnect("user", "password", conn_string, "select * from dual")
You can refer below link which helps you to understand how Python connects to Oracle db and you are missing TNS entry or full service JDBC URL and below are some samples:
https://www.oracle.com/database/technologies/appdev/python/quickstartpythononprem.html
https://oracle.github.io/python-cx_Oracle/samples/tutorial/Python-and-Oracle-Database-Scripting-for-the-Future.html
I think there's also another way by using f-strings:
import cx_Oracle
def sqlconnect(user,passwd,dsn, query):
connStr = cx_Oracle.connect(f'{user}/{passwd}#{dsn}')
cursor = connStr.cursor()
cursor.execute(f'{query}')
return cursor.fetchall()
if __name__ == '__main__':
sqlconnect('user','password','localhost/SID','select * from dual')

I can't access this variable outside the function that will be used for database connection

I am trying to access cursor outside the function dbconnect(). But I am getting this error "AttributeError: 'function' object has no attribute 'cursor'"
It would be really great if somebody could fix it. I am trying to make a program for school project. Code is given below.
import mysql.connector as mysql
def dbconnect():
db = mysql.connect(host='',
database='',
user='',
password='')
cursor = db.cursor()
return cursor
query = "select name,atomic_weight from elements where atomic_number = 8"
dbconnect.cursor.execute(query)
result = dbconnect.cursor.fetchall()
print(result)
cursor = dbconnect()
cursor.execute(query)
result = cursor.fetchall()

Updating MySQL DB Using Python For Loop Does not Work

I am trying to update the data from 'Active' to 'Retired by loop through a list of devices from the specific text file.
Somehow, however, it does not filter the list of devices from the text file and update the corresponding data, making no changes to the database at all.
Could it have something to do with my for statement, or mysql statement that I came up with? Regardless of how many times I fix MYSQL, it still results the same.
What could be the problem?
Please take a look at the code below and see if there is any mistake I have made with regards to MYSQL-wise or Python-wise.
Thank you in advance for your great help. Much appreciated.
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=############;'
'Database=########;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT id, device_id, model_number, serial_number_1,\
status_1, user_name_1 FROM [Footprint].[fpscdb001_cmdb_004].[desktop]')
results = []
with open('H:\list.txt') as inputfile:
results = inputfile.read().splitlines()
SQL = """UPDATE [Footprint].[fpscdb001_cmdb_004].[desktop]
SET status_1 = "Retired"
WHERE device_id == %s"""
try:
for i in results:
cursor.execute(SQL, results[i])
cursor.commit()
# print(rowcount)
except:
conn.rollback()
finally:
conn.close()
It looks like the problem is both your SQL and your Python.
There is a problem with your SQL at this part: WHERE device_id == %s. In SQL, there is no ==. Instead, you use a single = to both set and check values. You should use WHERE device_id = ?.
In addition, you're using %s as a placeholder in your query. I'm not familiar with pyodbc, but a quick check of the docs looks like you should be using the ? as a placeholder.
So try this:
SQL = """UPDATE [Footprint].[fpscdb001_cmdb_004].[desktop]
SET status_1 = "Retired"
WHERE device_id = ?"""
Building on the answer that #RToyo wrote, you may be able to do this a little more quickly
we can build a list of "?" placeholders in the SQL, and then pass each item safely to the ODBC holder, using the * notation to explode the array of device id's into the ODBC execute() function. This allows you to both execute only one query, and do it securely, too
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=############;'
'Database=########;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('SELECT id, device_id, model_number, serial_number_1,\
status_1, user_name_1 FROM [Footprint].[fpscdb001_cmdb_004].[desktop]')
results = []
with open('H:\list.txt') as inputfile:
results = inputfile.read().splitlines()
SQL = """UPDATE [Footprint].[fpscdb001_cmdb_004].[desktop]
SET status_1 = "Retired"
WHERE device_id in ({})""".format(("?, " * len(results))[0:-2])
try:
if len(results) > 0:
cursor.execute(SQL, *results)
except:
conn.rollback()
finally:
conn.close()
Hope this helps someone.

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

Categories