I am trying to call this UCP I have written and it takes in some variables as input. When I run the following code, it works.
try:
cursor.execute("PYH_uspUpdateConversation #lngConversationID=1020910, #lngNodeID=2, #strText='WAZZAA', #strResponse='sup', #strSentiment=0.98")
except pyodbc.Error:
print('Error !!!!! %s' % pyodbc.Error)
print ("\nResults :")
recs = cursor.fetchall()
print(recs[0][0])
However, when I execute the same code like this:
try:
cursor.execute(f"PYH_uspUpdateConversation #lngConversationID={id}, #lngNodeID={nodeID}, #strText={text}, #strResponse={resp}, #strSentiment={sentiment}")
except pyodbc.Error:
print('Error !!!!! %s' % pyodbc.Error)
print ("\nResults :")
recs = cursor.fetchall()
print(recs[0][0])
I get an error saying that it is not a valid SQL statement: No results. Previous SQL was not a query.
Related
I have a postgresql function that returns a string as follows:
CREATE OR REPLACE FUNCTION script.fn_indent()
RETURNS character varying
LANGUAGE 'plpgsql'
------
----function body to perform data insertion job---
results:='0 - Success';
return results
exception when others then
get stacked diagnostics
v_state = returned_sqlstate,
v_msg = message_text,
v_detail = pg_exception_detail,
v_hint = pg_exception_hint,
v_context = pg_exception_context;
raise notice 'Transaction was rolled back';
raise notice '% %', SQLERRM, SQLSTATE;
results:=v_state||'-'||v_msg||v_msg||'-'||v_detail ||'-'||v_hint ||'-'||v_context;
return results;
Now I am trying to run the above function from python using psycopg2.
conn = psycopg2.connect({connection string})
curr = conn.cursor
try:
curr.execute("SELECT * FROM script.fn_indent())
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
err = str(error)
conn.rollback()
curr.close()
print(err)
conn.close()
The above code is running fine. But I want to capture the return string from script.fn_indent() and show the same to python console. Something like as below:
---above python script---
print (results) <--results is the returning string that comes from fn_indent()
How to do it? I do not have any clue on this.
I got the clue from this thread
Refer here
Accordingly, I have modified the code base as follows:
conn = psycopg2.connect({connection string})
curr = conn.cursor
curr.execute("SELECT * FROM script.fn_indent()")
conn.commit()
s = curr.fecthone()
print (s)
conn.close()
I'm trying to loop through an array and insert each element into a table. As far as I can see my syntax is correct and I took this code straight from Microsoft Azure's documentation.
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
data = ['1','2','3','4','5']
for x in data:
cursor.execute("INSERT INTO test (serial) VALUES (%s)",(x))
print("Inserted",cursor.rowcount,"row(s) of data.")
conn.commit()
cursor.close()
conn.close()
print("Done.")
When I run this is gets to cursor.execute(...) and then fails. Here is the stack trace.
Traceback (most recent call last):
File "test.py", line 29, in
cursor.execute("INSERT INTO test (serial) VALUES (%s)",("test"))
File "C:\Users\AlexJ\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor_cext.py", line 248, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "C:\Users\AlexJ\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection_cext.py", line 538, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
Try this:
for x in data:
value = "test"
query = "INSERT INTO test (serial) VALUES (%s)"
cursor.execute(query,(value,))
print("Inserted",cursor.rowcount,"row(s) of data.")
Since you are using mysql module, cursor.execute requires a sql query and a tuple as parameters
Nice answer from #lucas, but maybe this help other, cz i think more cleaner
sql = "INSERT INTO your_db (your_table) VALUES (%s)"
val = [("data could be array")]
cursor = cnx.cursor()
cursor.execute(sql, val)
print("Inserted",cursor.rowcount,"row(s) of data.")
cnx.commit()
cnx.close()
Cz this is useful for my purpose, to input multiple data.
I'm facing same issue but instead of array, I'm looping through a set and insert each item into mysql db and got this error mysql.connector.errors.ProgrammingError: Could not process parameters: str(Data_Tokens), it must be of type list, tuple or dict.
The uniqueTokenSet includes string data type, but as error shows that it must be list, tuple or dict. By converting item to list of tuple [(item)] work for me.
uniqueTokenSet = set()
for item in uniqueTokenSet:
tokenSql = "insert into tokens(token) values (%s)"
data = [(item)]
mycursor.execute(tokenSql, data)
print('data inserted')
mydb.commit()
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 ?'
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
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]) + "'"