DatabaseError: ORA-00911: invalid character - python

I have following code to execute sql quesry in Oracle db:
try:
conn = cx_Oracle.connect(DB_LOGIN+"/"+DB_PWD+"#"+SID)
cursor = connection.cursor()
cursor.execute(sql)
connection.commit()
cursor.close()
conn.close()
except cx_Oracle.DatabaseError, ex:
error, = ex.args
print 'Error.code =', error.code
print 'Error.message =' , error.message
print 'Error.offset =', error.offset
conn.rollback()
I got error: DatabaseError: <cx_Orac...40066758>.
Why I don't see full error message in console? Looks like exception part is not executed.
I use python 2.5 and oracle 10.2.0 on linux.
Update: After some investigation I found out that the error is DatabaseError: ORA-00911: invalid character.
My sql string is like: sql = "SELECT ID FROM TABLE WHERE DESC = '" + str(desc[0]) + "';". This is generated string: "SELECT ID FROM TABLE WHERE DESC = '3312';"
When I execute the same request in SQL Developer it works. So what I do wrong?

Delete the semicolon:
sql = "SELECT ID FROM TABLE WHERE DESC = '" + str(desc[0]) + "'"

Related

MySQL Python problem with two Placeholders

I have a problem with my function:
def dataf (p,k):
try:
connection = mysql.connector.connect(host='host',
database='products',
user='user',
password='pwd')
sql_select_Query = "select a from table where b LIKE %s AND c LIKE %s"
cursor = connection.cursor()
cursor.execute(sql_select_Query, ('%' + p+ '%',), ('%' + k + '%',))
records = cursor.fetchall()
return records
except Error as e:
print("Error reading data from MySQL table", e)
finally:
if (connection.is_connected()):
connection.close()
cursor.close()
When I execute this function with only the first placeholder, everything works fine. With the second placeholder I get the TypeError: NoneType
With the second placeholder I want to check if in column c a value is like = 0,5 kg for example. When I write the query without the second placeholder and insert the value directly, everything works fine:
sql_select_Query = "select a from table where b LIKE %s AND c LIKE '0,5 kg'"
What am I doing wrong?
Ok I got it with:
sql_select_Query = "select a from table where b LIKE %s AND c LIKE %s"
cursor = connection.cursor()
cursor.execute(sql_select_Query, ('%' + p+ '%','%' + k + '%',))
I got the result.

Pymysql table name from variable

I am using Python3 and PyMySQL 0.7.9. Version of Mysql is 5.5.57.
Using this query to fetch data from Mysql works:
cur.execute('SELECT date FROM Tablename1 ORDER BY id DESC LIMIT 1')
I would like to get name of table from variable.
Reading Pymysql docs and this Stackoverflow post lead me to belive that this code should work:
dbtable = Tablename1
query = 'SELECT date FROM %s ORDER BY id DESC LIMIT 1'
cur.execute(query, (dbtable, ))
But this results in error:
pymysql.err.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 ''Tablename1' ORDER BY id DESC LIMIT 1' at line 1")
I also tried using quotes but got different error:
query = 'SELECT `date` FROM `%s` ORDER BY `id` DESC LIMIT 1'
cur.execute(query, (dbtable, ))
Results in:
pymysql.err.ProgrammingError: (1146, "Table 'Databasename.'Tablename1'' doesn't exist")
How should the query be changed to allow variable work?
This works for me. Using python 3.8, mariadb 10.2, pymysql
cur = con.cursor()
cur.execute('SELECT field FROM %s ORDER BY id DESC LIMIT 1' %(dbtable))
result = cur.fetchone()
Replace field and dbtable approriately
Like this :
dbtable = input("Table name: ")
query = "SELECT * FROM %s"%(dbtable)
cur.execute(query)
results = cur.fetchall()
for row in results:
print (row[0], row[1], row[2], row[3])

Python MySQLdb: mysql_exceptions.ProgrammingError: (1064)

I am trying to retrieve data from MySQL. Unfortunately, I am getting the error s below:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version fo r the right syntax to use near '1=,-5000,1)) AND
(IF(3=,5000,3)))at line 1")
volumeMin and volumeMax I put as integer. In actual, it can be float. How can I fix the error?
import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host='xxx.mysql.pythonanywhere-services.com',user='xxx',passwd='xxx',db='xxx$default',cursorclass=MySQLdb.cursors.DictCursor)
curs = db.cursor()
name ='G%'
volumeMin = 1
volumeMax = 3
#request args was initially want to retrieve data from external app
#but eventually found that the problem is in MySQL request
"""name = request.args['name']
volumeMin = request.args['volumeMin']
volumeMax = request.args['volumeMax']
"""
query0 = "SELECT * FROM KLSE WHERE Stock LIKE %s AND "
query2 = "(Volume_changes_pc BETWEEN (IF %s='_',-5000,%s)) AND (IF(%s='_',5000,%s)))"
query = query0+query2
input = name,volumeMin,volumeMin,volumeMax,volumeMax
print query
print input
print (query,(input))
curs.execute(query,(input))
a = curs.fetchall()
output of print (query,(input))
('SELECT * FROM KLSE WHERE Stock LIKE %s AND (Volume_changes_pc BETWEEN (IF %s=_,-5000,%s)) AND (IF(%s=_,5000,%s))) AND MACD LIKE %s ', ('G%', 1, 1
, 3, 3, 'H'))
solved
query2 = "(Volume_changes_pc BETWEEN (IF (%s='_',-5000,%s)) AND (IF(%s='_',5000,%s)))"
miss out a bracket

Sybpydb error 5701 ignored sometimes

I have come across a very strange behavior when developing an application in Python (2.7.11) using a Sybase ASE 15.7 database and the sybpydb library.
When selecting data from the database there is always an error 5701 thrown that isn´t an error but just a informational message taht the client has logged on or changed database.
This should be ignored by the client and it works fine most of the time but sometimes not.
Has anyone come across this problem and know a way to work around it?
I don´t want to stop handling exceptions.
The following code illustrates the problem, the first two queries runs as the should but the last one doesn´t work, I have checked the query and yes it returns a result set.
uname = 'username'
pwd = 'password'
server = 'server'
conn = sybpydb.connect(user=uname, password=pwd, servername=server)
cur = conn.cursor()
try:
sql = 'select * from database..table1'
cur.execute(sql)
print 'Execute for table1'
print cur.connection.errors()
row = cur.fetchone()
print "Query Returned %d row(s)" % cur.rowcount
print row
except sybpydb.Error:
print cur.connection.errors()
finally:
cur.close()
conn.close()
conn = sybpydb.connect(user=uname, password=pwd, servername=server)
cur = conn.cursor()
parameter1 = 'DSE'
try:
sql = 'select * from database..table2 where column1 = ?'
cur.execute(sql, [parameter1])
print 'Execute for table2'
print cur.connection.errors()
row = cur.fetchone()
print "Query Returned %d row(s)" % cur.rowcount
print row
except sybpydb.Error:
print cur.connection.errors()
finally:
cur.close()
conn.close()
parameter1 = 1
parameter2 = 1
conn = sybpydb.connect(user=uname, password=pwd, servername=server)
cur = conn.cursor()
try:
sql = 'select * from database..table3 where column1 = ? and column2 ?'
cur.execute(sql, [parameter1, parameter2])
print 'Execute for table3'
print cur.connection.errors()
row = cur.fetchone()
print "Query Returned %d row(s)" % cur.rowcount
print row
except sybpydb.Error:
print cur.connection.errors()
finally:
cur.close()
conn.close()
These three calls to the database results in this.
Execute for table1
[DatabaseError("Server message: number(5701) severity(10) state(2) line(0)\n\tChanged database context to 'master'.\n\n", 5701)]
Query Returned -1 row(s)
(Resultset for query 1)
Execute for table2
[DatabaseError("Server message: number(5701) severity(10) state(2) line(0)\n\tChanged database context to 'master'.\n\n", 5701)]
Query Returned -1 row(s)
(Resultset for query2)
[DatabaseError("Server message: number(5701) severity(10) state(2) line(0)\n\tChanged database context to 'master'.\n\n", 5701)]
I never get such message when using sybpydb , I don't print cur.connection.errors() , which is not one of the documented methods (I even got an error when I tried to use it )
In all cases ,maybe you are getting this message as part of Sybase ASE informing the client about:
1- Default database when you log in - I don't think this applied to python .
2- when you change the database context .. which you are doing by specifying "database.."
To get rid of this message , simply set a default database for the user you use to connect as the target database , hence , you connection will be located immediately in that database after login and you don't need to specify the database in the query anymore , to change default database for login use :
sp_modifylogin <uname>, defdb, "<database>"
or in ASE 15.7 :
alter login <uname> modify default database <database>
then your queries should look like :
sql = 'select * from table3 where column1 = ? and column2 ?'

mysql is showing error in the syntax

I am having trouble in executing this query in python. I have an IP database which has 3 column startip, endip and country. Now I want to the location of the ip. this is my code
def get_country(ip):
try:
conn = MySQLConnection(host='localhost', database='ipdb', user ='root', password='password')
cursor = conn.cursor()
query = 'SELECT * FROM db6 WHERE %s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
ip_inint= ip2int(ip)
cursor.execute(query,ip_inint)
row = cursor.fetchone()
while row is not None:
print " Start range %s end range %s country %s " %(row[0], row[1], row[2])
row = cursor.fetchone()
except Error as error:
print(error)
ip2int function is
def ip2int(addr):
return struct.unpack("!I", socket.inet_aton(addr))[0]
error i am receiving is
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 '%s BETWEEN INET_ATON(startip) AND INET_ATON(endip)' at line 1
what could be the issue?
You need to pass a tuple to execute():
cursor.execute(query, (ip_inint,))
A list will probably work too:
cursor.execute(query, [ip_inint])
An alternative is to use a dictionary with named variables in the query:
query = 'SELECT * FROM db6 WHERE %(ip_inint)s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
cursor.execute(query, {'ip_inint': ip_inint})
Reference: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

Categories