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.
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}'))");
Upon running this script:
#! /usr/bin/env python
import MySQLdb as mdb
import sys
class Test:
def check(self, search):
try:
con = mdb.connect('localhost', 'root', 'password', 'recordsdb');
cur = con.cursor()
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
ver = cur.fetchone()
print "Output : %s " % ver
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
test = Test()
test.check("test")
I get an error of:
./lookup
Traceback (most recent call last):
File "./lookup", line 27, in <module>
test.check("test")
File "./lookup", line 11, in creep
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
I have zero idea why. I'm trying to do parameterized querys, but it's been nothing but a pain. I'm somewhat new to Python, so it's probably an obvious problem.
Instead of this:
cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )
Try this:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )
See the MySQLdb documentation. The reasoning is that execute's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).
You can try this code:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
You can see the documentation
'%' keyword is so dangerous because it major cause of 'SQL INJECTION ATTACK'.
So you just using this code.
cursor.execute("select * from table where example=%s", (example,))
or
t = (example,)
cursor.execute("select * from table where example=%s", t)
if you want to try insert into table, try this.
name = 'ksg'
age = 19
sex = 'male'
t = (name, age, sex)
cursor.execute("insert into table values(%s,%d,%s)", t)
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
I do not why, but this works for me . rather than use '%s'.
The accepted answer by #kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.
There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported
cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')
but the 1.2.5 versions require
cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])
as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.
The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.
If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:
$ pip install MySQL-python==1.2.3
I don't understand the first two answers. I think they must be version-dependent. I cannot reproduce them on MySQLdb 1.2.3, which comes with Ubuntu 14.04LTS. Let's try them. First, we verify that MySQL doesn't accept double-apostrophes:
mysql> select * from methods limit 1;
+----------+--------------------+------------+
| MethodID | MethodDescription | MethodLink |
+----------+--------------------+------------+
| 32 | Autonomous Sensing | NULL |
+----------+--------------------+------------+
1 row in set (0.01 sec)
mysql> select * from methods where MethodID = ''32'';
ERROR 1064 (42000): 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 '9999'' ' at line 1
Nope. Let's try the example that Mandatory posted using the query constructor inside /usr/lib/python2.7/dist-packages/MySQLdb/cursors.py where I opened "con" as a connection to my database.
>>> search = "test"
>>> "SELECT * FROM records WHERE email LIKE '%s'" % con.literal(search)
"SELECT * FROM records WHERE email LIKE ''test''"
>>>
Nope, the double apostrophes cause it to fail. Let's try Mike Graham's first comment, where he suggests leaving off the apostrophes quoting the %s:
>>> "SELECT * FROM records WHERE email LIKE %s" % con.literal(search)
"SELECT * FROM records WHERE email LIKE 'test'"
>>>
Yep, that will work, but Mike's second comment and the documentation says that the argument to execute (processed by con.literal) must be a tuple (search,) or a list [search]. You can try them, but you'll find no difference from the output above.
The best answer is ksg97031's.
According PEP8,I prefer to execute SQL in this way:
cur = con.cursor()
# There is no need to add single-quota to the surrounding of `%s`,
# because the MySQLdb precompile the sql according to the scheme type
# of each argument in the arguments list.
sql = "SELECT * FROM records WHERE email LIKE %s;"
args = [search, ]
cur.execute(sql, args)
In this way, you will recognize that the second argument args of execute method must be a list of arguments.
May this helps you.
I encountered this error while executing
SELECT * FROM table;
I traced the error to cursor.py line 195.
if args is not None:
if isinstance(args, dict):
nargs = {}
for key, item in args.items():
if isinstance(key, unicode):
key = key.encode(db.encoding)
nargs[key] = db.literal(item)
args = nargs
else:
args = tuple(map(db.literal, args))
try:
query = query % args
except TypeError as m:
raise ProgrammingError(str(m))
Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.
I use MySQLdb library. When I make a query like this
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = ?", src)
where src is a string variable, I get an error:
TypeError: not all arguments converted during string formatting
I also get an error, if I make it like this:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = %s" % src)
However, I do not have an error in this case:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = '%s'" % src)
But what I do not like about this statement is explicit quotes around %s. I would like to make the driver decide the type of variable and do it implicitly. Otherwise, in case of automatic queries it would be a real problem to do all this routine of parsing variable types and "preparing" a prepared statement.
EDIT
It seems, as if I found a solution. The right syntax was:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = %s" , (src,))
where the variables (src) is provided as a tuple.
'src' in your code means values that you want to pass instead of question mark. If that is true try the below code. Else ignore
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = " + src);
Then try this
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC like '%" + src + "%'");
It seems, as if I found a solution. The right syntax was:
cursor.execute("SELECT COUNT(*) FROM srcdst WHERE TABLESRC = %s" , (src,))
where the variables (src) is provided as a tuple.
I've been trying to work out where I've been going for most of the day, and still can't work it out, been staring at it too long and I'm sqill very early in my learning of Python & MySQL.
The query I've built is:
query = "UPDATE `db`.`%s" % table + "` SET %s" % table + "`.`%s" % field + "` = `%s" % daychangeperc + "` WHERE (`db`.`%s" % table + "`.`id` = %s" % rowid +") LIMIT 1;"
The error I'm getting is:
_mysql_exceptions.ProgrammingError: (1064, "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 '.DayChange= '-0.00736251627767' WHERE (outofthe_finance.test1.id` = 1) ' at line 1")
Anyone able to point out where I'm going wrong? I'm sure it's probably obvious for many.
Thanks in advance.
That's pretty messy, perhaps try doing it like this instead:
query = """UPDATE db.%s SET %s.%s = %s WHERE db.%s.id = %s LIMIT 1""" % (table,table,field,daychangeperc,table,rowid)
First, here is your query re-written so that all of the arguments for your format string come at the end:
query = "UPDATE `db`.`%s` SET %s`.`%s` = `%s` WHERE (`db`.`%s`.`id` = %s) LIMIT 1;" \
%(table,table,field,daychangeperc,table,rowid)
When you look at it this way, you can see that after the SET keyword you have some unbalanced back-ticks. I think this is the issue, and is hard to see because of how you wrote your string.