Space in a string instance can't be read using psycopg2 - python

I am using psycopg2 library and iI made a query to select instances from a table in a database. I have run the code in a user interface program and it works however, I get an error when I run it in python. Here is the code:
find_id = 'SELECT "serial_number" FROM "LogFiles" WHERE "LogFiles"."user_name" = my product;'
cur.execute(find_id)
cur.fetchall()
ERROR happen in ^:
find_id='SELECT "serial_number" FROM "LogFiles" WHERE
"LogFiles"."user_name" = my ^product ;'
It seems that I need to deal with the space inside of a string as reading of the instance is stopped after my.
I have tried to use "my product" and '''my product''' and ''my product'' but they don't work as well.

Related

string in pypyodbc query not recognised

I recently decided to migrate some of my scripts from jupyter notebook to plain old python scripts (.py) for several reasons. in jupyter, everything works properly, however the same code doesn't do anything in SQL. I know the procedure is correct because if I run it directly on the server, it does the trick.
my code is:
query = 'EXEC [dbo].[kpi_init] '+kpi+';'
cursor.execute(query)
I tried adding quotes, like this, no success:
query = 'EXEC [dbo].[kpi_init] \''+kpi+'\';'
I tried using parameterised queries, like this, no success:
query = 'EXEC [dbo].[kpi_init] ?;'
cursor.execute(query, [kpi])
worth mentiong that kpi is a simple variable containing something like A00 or X23 and it's there, as I can print it out and use it to trigger external functions. it's only my SQL code that doesn't work. am I missing something?
thanks
Try this one:
query = f"EXEC [dbo].[kpi_init] '{kpi}'"
cursor.execute(query)

python pypyodbc won't select data

I think I'm going mad here... again :). I'm trying to do the most simple thing on the planet and it doesn't work for some reason unknown to me. I have a python script that connects to a mssql database using pypyodbc and does stuff. when I insert data into the database, it works. when I try to extract it, it fails miserably. what am I doing wrong?
import pypyodbc as mssql
msConnErr = None
try:
msconn = mssql.connect('DRIVER={SQL Server};SERVER=server_name;DATABASE=database;TRUSTED_CONNECTION=True')
print('Source server connected')
srcCursor = msconn.cursor()
except:
print('Source server error')
msConnErr = True
srcCursor.execute("SELECT * FROM schema.table")
srcResult = srcCursor.fetchall()
print(srcResult)
the connection works as I'm being given a successful message. I can also see my script using sql server management studio being connected to the correct database, so I know I'm working in the right environment. the error I'm getting is:
UndefinedTable: relation "schema.table" does not exist
LINE 1: SELECT * FROM schema.table
the table exists, I must specify the schema as I have the same table name in different schemas (data lifecycle). I can extract data from it using sql server management studio, yet python fails miserably. it doesn't fail to insert 35 million rows in it using the same driver. no other query works, even SELECT ##VERSION fails, SELECT TOP (10) * FROM schema.table fails etc. ...
any ideas?
basically, I had a piece of code that would rewrite the srcCursor variable with another connection, obviously that relation wouldn't be present on another server. apologies!

Dealing with long SQL scripts and SQL Alchemy

The problem is that I have a long SQL Script (that contains variables and comments and many lines of code) that I need to re-produce the results of which in Jupyter Notebooks.
I have already tried "tidying" the SQL into a string, but it is many lines and would take too long. For system architecture reasons I cannot create a procedure or view that encapsulates the script.
# The basic structure of my problem sans actual detail as not required
engine = create_engine("server/database=connect")
SQL = "select * from foo" #Insert very long script here
SQL_DF = pd.read_sql(SQL, engine)
I am hoping there is an informal way or trick to either convert a whole cell (containing my script text) to a string variable. Or if someone has another method of turning long SQL scripts into strings that can be used easily with SQL Alchemy.
you can try to use triple quote:
"""select * from foo
some more code
and more
etc"""
or you may use \ in the end of each line:
"select * from foo\
some more code\
and more\
etc"

INSERTING and UPDATE SET issues when handling strings

I've been having this issue for some time now and here is the short story:
I want to edit a date in my Sqlite database with a Python script so I do this using:
import sqlite3
db = sqlite3.connect('test.db')
cursor = db.cursor()
cursor.execute("UPDATE info SET date = '2003-03-14 12:34:20' WHERE id = 10")
but when I execute this I get an exception:
sqlite3.OperationalError: no such module: fts4
with some troubleshooting I've managed to narrow it down to having some issues with the quote marks. Since even if I just reduce it to a single year it still produces an exception.
The same exception appear if I try to insert a string using quote marks.
How can I fix this? Most solutions I find is solved though enabling fts3/fts4 with the SQLITE_ENABLE_FTS3 flag when building, but I have no idea of how to do that.
Besides, the exact same code runs smoothly both in Python 3.6.5 and 2.7.12. what happened in Python3?, or more specifically 3.5.2.
I should add, that it works in linux but not in windows.

python variable invalid syntax issue

I'm having an issue getting what I think is a simple script working and I think it's just me not knowing how to get a variable working.
i'm working on a salesforce script that grabs a list of objects, then looks through the list of objects to get all fields on the table.
this query in python works perfectly for giving me my list of objects that I've pulled into the DB
query = ("SELECT obj_name FROM syncsfobjects")
cursor.execute(query)
i then loop through these records
for x in cursor:
now this is where my issue lies I want to use the obj_name that comes in from my query within the next statement
for xy in sf.%obj_name%.describe()["field"]:
what i'm having massive issues with is getting the obj name into this simple-salesforce query.
if I create a string it works fine
objectname = str(x)
sfquery = 'sf. %s .describe()["fields"]' % objectname
but then when I use the sfquery for my next loop all the loop does it run through each letter within the string instead of run the sf connection command.
any I just missing something simple?
cheers
dan
for xy in sf.%obj_name%.describe()["field"]:
Python doesn't let you do "percent substitution" outside of strings, but you can still access attributes if all you have are their names:
for xy in getattr(sf, objectname).describe()["field"]:

Categories