string in pypyodbc query not recognised - python

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)

Related

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

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.

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"

Convert Java to Python using cx_Oracle SQL/XML query

I have an existing solution in Java to extract data from an Oracle database. I do it like so:
String tmp = "begin ? := pkgioexportora.request(?); end;";
String xml = "<ttc.export.public.data.search><query><popid>1</popid> <moduleid>3</moduleid><only_changes>0</only_changes></query></ttc.export.public.data.search>";
CallableStatement callableStmt = oracle.prepareCall(tmp);
// Register the type of the out param - an Oracle specific type
callableStmt.registerOutParameter(1, OracleTypes.NUMBER);
callableStmt.setString(2, xml);
This construct returns a job id which I'm later required to use in the WHERE clause of a SELECT query.
I've tried using just a cursor and input the complete statement, without the CallableStatement stuff, but no luck.
cursor = con.cursor()
cursor.execute("begin 2 := pkgioexportora.request(xml_stuff_here); end;";)
callproc seems to give me similar error.
I've tried searching for solutions, or similar things done, but yet to come up with any examples. Is it possible to do such a thing with cx_Oracle or am I stuck with my Java code for doing this?
You can use cursor.callfunc() in cx_Oracle. As in the following:
result = cursor.callfunc("pkgioexportora.request", cx_Oracle.NUMBER, [xml_stuff])
You could also do it this way, but its more complex:
var = cursor.var(cx_Oracle.NUMBER)
cursor.execute("begin :1 := pkgioexportora.request(:2); end;", [var, xml_stuff])
result = var.getvalue()

String-encoding SQL statement

I have a very strange issue. I have a SQL statement that works locally, but the same statement does not work on a remote ubuntu machine (same mysql version). I think it has to do with how the SQL string is being encoded by the driver. Here is the statement I have:
group_ids = ('43ede7a1e1f048872c025867602dc54d', '43ede7a1e1f048872c025867602dc54d', '7a8ec12901c43606aee041f1e6d5b2d4', '0f57f4ad
cursor = connection.cursor()
cursor.execute( '''
SELECT
DISTINCT c.group_id
FROM
main_cue c
LEFT OUTER JOIN
main_passongroup p
ON
(c.group_id=p.group_id AND p.user_id=%s)
WHERE
c.group_id in %s
ORDER BY
p.timestamp ASC, c.id DESC''', (user.pk, group_ids))
results = cursor.fetchall()
print '>>> 1', results
On my local machine, it seems to be properly SQL-encoding the statement, but on the remote server, it is only working if I hard code the exact sql statement.
Is there a better way to encode the SQL statement?
This seemed to be an issue with an outdated version of MySQLdb, which was not properly encoding the string.
I was able to solve this by uninstalling MySQLdb and then reinstalling the newer version, (MySQL-python==1.2.5).

Python MySQLdb, simple chatroom/guestbook app

I've browsed some of the other questions about MySQL and Python on SO. There are a few things eluding me, because I'm pretty new to Python.
First, I'm trying to get a simple guestbook app to work. It takes posted variables and puts them into a MySQL database. Take a look:
con = MySQLdb.connect (host = "localhost",
user = "Chat",
passwd = "myPass",
db = "Chatserver")
cursor = con.cursor()
cursor.execute ("INSERT INTO guestbook (name,message) VALUES(%s,%s)",(name,greeting))
Ok, so some of the tutorials and answers on SO have many Quotation marks surrounding the SQL query, and I don't know why that is. I've tried it with 1 quote, I've tried it with 3 quotes, and it just never works. There are no exception callbacks and the code seems to run, but no records are ever entered into the database.
So my two questions are, how many quotation marks do I need when encapsulating the Queries, and why doesn't my script add anything to the database but not report any errors?
Ok, this answer Can't execute an INSERT statement in a Python script via MySQLdb helped me figure it out.
You have to add this at the end of your query.
cursor.execute(...)
con.commit() //this is what makes it actually do the execution?

Categories