I used the below statement to extract the ddl for particular function using python in DB2.
Function name = 'DEPTEMPLOYEES'
DDL = "select text from syscat.routines where routineschema = {}
and routinename = {} and routinetype = 'F'".format(user_schema,objs.upper())
cursor.execute(DDL)
But when I tried to execute this statement am getting an error.
ibm_db_dbi::ProgrammingError: SQLNumResultCols failed: [IBM][CLI
Driver][DB2/NT64] SQL0206N "DEPTEMPLOYEES" is not valid in the
context where it is used. SQLSTATE=42703\r SQLCODE=-206
Can someone please help me to solve this error
Have you tried something like this, adding single quotes around the strings?
DDL = "select text from syscat.routines where routineschema = '{}'
and routinename = '{}' and routinetype = 'F'".format(user_schema,objs.upper())
cursor.execute(DDL)
Based on the error it seems that your parameters was printed and the quotes were missing. This turned the parameter into a keyword, hence the error message.
Related
fairly new to SQL in general. I'm currently trying to bolster my general understanding of how to pass commands via cursor.execute(). I'm currently trying to grab a column from a table and rename it to something different.
import mysql.connector
user = 'root'
pw = 'test!*'
host = 'localhost'
db = 'test1'
conn = mysql.connector.connect(user=user, password=pw, host=host, database=db)
cursor = conn.cursor(prepared=True)
new_name = 'Company Name'
query = f'SELECT company_name AS {new_name} from company_directory'
cursor.execute(query)
fetch = cursor.fetchall()
I've also tried it like this:
query = 'SELECT company_name AS %s from company_directory'
cursor.execute(query, ('Company Name'),)
fetch = cursor.fetchall()
but that returns the following error:
stmt = self._cmysql.stmt_prepare(statement)
_mysql_connector.MySQLInterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? from company_directory' at line 1
I'm using python and mySQL. I keep reading about database injection and not using string concatenation but every time I try to use %s I get an error similar to the one below where. I've tried switching to ? syntax but i get the same error.
If someone could ELI5 what the difference is and what exactly database injection is and if what I'm doing in the first attempt qualifies as string concatenation that I should be trying to avoid.
Thank you so much!
If a column name or alias contains spaces, you need to put it in backticks.
query = f'SELECT company_name AS `{new_name}` from company_directory'
You can't use a placeholder for identifiers like table and column names or aliases, only where expressions are allowed.
You can't make a query parameter in place of a column alias. The rules for column aliases are the same as column identifiers, and they must be fixed in the query before you pass the query string.
So you could do this:
query = f"SELECT company_name AS `{'Company Name'}` from company_directory'
cursor.execute(query)
I am following this tutorial :https://docs.snowflake.com/en/sql-reference/functions/validate.html
to try and 'return errors by query ID and saves the results to a table for future reference'
however for a seamless transfer I don't want to be putting the job id always as it would require me to go to snowflake console- go to history- get the jobid -copy and paste it to python code.
Instead I wanted to go with just the tablename which is a variable and 'last_query_id()' and give me the list errors. Is there any way i can achieve this?
import snowflake.connector
tableName='F58155'
ctx = snowflake.connector.connect(
user='*',
password='*',
account='*')
cs = ctx.cursor()
ctx.cursor().execute("USE DATABASE STORE_PROFILE_LANDING")
ctx.cursor().execute("USE SCHEMA PUBLIC")
try:
ctx.cursor().execute("PUT file:///temp/data/{tableName}/* #%
{tableName}".format(tableName=tableName))
except Exception:
pass
ctx.cursor().execute("truncate table {tableName}".format(tableName=tableName))
ctx.cursor().execute("COPY INTO {tableName} ON_ERROR = 'CONTINUE' ".format(tableName=tableName,
FIELD_OPTIONALLY_ENCLOSED_BY = '""', sometimes=',', ERROR_ON_COLUMN_COUNT_MISMATCH = 'TRUE'))
I have tried the below validate function....it is giving me error on this line
the error is "SQL compilation error:
syntax error line 1 at position 74 unexpected 'tableName'.
syntax error line 1 at position 83 unexpected '}'."
ctx.cursor().execute("create or replace table save_copy_errors as select * from
table(validate({tableName},'select last_query_id()'))");
ctx.close()
The line
ctx.cursor().execute("create or replace table save_copy_errors as select * from
table(validate({tableName},'select last_query_id()'))");
should be replaced with these two
job_id = ctx.cursor().execute("select last_query_id()").fetchone()[0]
ctx.cursor().execute(f"create or replace table save_copy_errors as select * from
table(validate({tableName},job_id=>'{job_id}'))");
I am using Sqlalchemy 1.3 to connect to a PostgreSQL 9.6 database (through Psycopg).
I have a very, very raw Sql string formatted using Psycopg2 syntax which I can not modify because of some legacy issues:
statement_str = SELECT * FROM users WHERE user_id=%(user_id)s
Notice the %(user_id)s
I can happily execute that using a sqlalchemy connection just by doing:
connection = sqlalch_engine.connect()
rows = conn.execute(statement_str, user_id=self.user_id)
And it works fine. I get my user and all is nice and good.
Now, for debugging purposes I'd like to get the actual query with the %(user_id)s argument expanded to the actual value. For instance: If user_id = "foo", then get SELECT * FROM users WHERE user_id = 'foo'
I've seen tons of examples using sqlalchemy.text(...) to produce a statement and then get a compiled version. I have that thanks to other answers like this one or this one been able to produce a decent str when I have an SqlAlchemy query.
However, in this particular case, since I'm using a more cursor-specific syntax %(user_id) I can't do that. If I try:
text(statement_str).bindparams(user_id="foo")
I get:
This text() construct doesn't define a bound parameter named 'user_id'
So I guess what I'm looking for would be something like
conn.compile(statement_str, user_id=self.user_id)
But I haven't been able to get that.
Not sure if this what you want but here goes.
Assuming statement_str is actually a string:
import sqlalchemy as sa
statement_str = "SELECT * FROM users WHERE user_id=%(user_id)s"
params = {'user_id': 'foo'}
query_text = sa.text(statement_str % params)
# str(query_text) should print "select * from users where user_id=foo"
Ok I think I got it.
The combination of SqlAlchemy's raw_connection + Psycopg's mogrify seems to be the answer.
conn = sqlalch_engine.raw_connection()
try:
cursor = conn.cursor()
s_str = cursor.mogrify(statement_str, {'user_id': self.user_id})
s_str = s_str.decode("utf-8") # mogrify returns bytes
# Some cleanup for niceness:
s_str = s_str.replace('\n', ' ')
s_str = re.sub(r'\s{2,}', ' ', s_str)
finally:
conn.close()
I hope someone else finds this helpful
I keep getting a error with a SQL query that is written in python.
Here is the code in question:
else:
else_query = "SELECT count(*) FROM PARKING_SPOTS WHERE OCCUPANCY = %s"
cursor.execute(else_query, (occupancy,)
" AND WHERE LOCATION = %s", (location,))
Here's the error message:
File "exp1", line 116
" AND WHERE LOCATION = %s", (location,))
^
SyntaxError: invalid syntax
Can anyone spot the error ? I've changed things around several times, including containing part of the SQL query in a variable, yet I receive the same error.
your query is incorrect because you can't have 2 WHERE clauses
you can only pass one querystring
so make that:
else_query = """SELECT count(*) FROM PARKING_SPOTS WHERE OCCUPANCY = %s
AND LOCATION = %s
"""
cursor.execute(else_query, (occupancy, location))
parameters for the query need to be passed as a tuple
I think I have the right idea to solve this function, but I'm not sure why I get this error when I test it. Can anyone please help me fix this?
Error: conn = sqlite3.connect(db)
sqlite3.OperationalError: unable to open database file
Desired Output:
>>> get_locations(db, 'ANTA01H3F')
[('ANTA01H3F', 'LEC01', 'AA112'), ('ANTA01H3F', 'LEC01', 'SY110'), ('ANTA01H3F', 'LEC02', 'AC223')]
def get_locations(db, course):
'''Return the course, section and locations of the exam for the given course.'''
return run_query('''SELECT Courses.Course, Courses.Sections, Room.Locations
FROM Courses JOIN Locations ON Courses.ID = Locations.ID WHERE Course = ?''', [course])
This is too much abstract. ;)
See run_query() from where it is getting the value of db (sqlite database file name) to run queries. It is not getting correct file name that you are expecting.
You are calling the function wrong, it accepts db and sql statement string:
return run_query(db, "SELECT Courses.Course, Courses.Sections, Locations.Room " \
" FROM Courses JOIN Locations ON Courses.ID = Locations.ID WHERE Course = '{}'".format(course))