Procedure execute inside SQL Developer, but not inside a script - python

I had a procedure that was not working.
If I tried to run: "BEGIN proc_name; END;" in SQL Developer or via script I had the same error.
I've fixed the procedure and now when I run that same command in SQL Developer, it's fine, but the script returns an error.
When I try:
...
sql = """EXEC proc_name"""
con = connection.cursor()
con.execute( sql )
...
I get DatabaseError: ORA-00900: invalid SQL statement, but probably is because of that: Problem with execute procedure in PL/SQL Developer and I'm not really worried about it.
What is really making me curious is when I try:
...
sql = """BEGIN proc_name;END;"""
con = connection.cursor()
con.execute( sql )
...
I get the same error that I had before fix the procedure.
Do you have any idea what is going on?
PS: This is a python script using cx_Oracle and I'm using Oracle 10g.

Try using the callproc() or callfunc() method on the cursor, instead of execute(). They are not exactly Py DB API compatible, but should do the job for cx_Oracle...

Related

executing USE-statement yields "You have an error in your SQL syntax"

I have a weird escaping problem. USE-statement does not work as I would expect. Here are three statements I tried, but only the last one works:
engine=create_engine("mysql+pymysql://l:pw#myserver")
engine.execute("use :db", db='mydb') # fails
engine.execute("use 'mydb'") # fails
engine.execute("use `mydb`") # works fine
Failing stements raise exception "You have an error in your SQL syntax...". I checked with strace the queries that are sent over the wire, it's "use 'mydb'". But this query executed from MySQL cli works just fine. Why it doesn't work from within SQLAlchemy?
PS I tried using "SET sql_mode=ANSI_QUOTES" and updated SQLAlchemy and PyMySQL to the latest versions. Also tried mysqlclient driver, no luck.

SqlAlchemy python script hangs while executing SQL Server Stored procedure

I am working on a Python script that makes use of SqlAlchemy library to execute Stored Procedure on SQL Server. I am passing XML contents to the stored procedure.
xml_text = "<root><element>some xml contents</element></root>"
query = PROCS['myStoreProc']
session = get_session()
result = session.execute(text(query, bindparams=[bindparam('xmlContent', value=xml_text)])).fetchall()
session.commit()
return result
I am able to get the query and session fine. But for some reason the command session.execute hangs. It neither returns any result nor any exception.

Python mysql doesn't see data change in database

i need some help with python an mysql.
I have the following code, which is executing in infinite loop:
db = MySQLdb.connect("127.0.0.1","user","password","dbname" )
while True:
cursor = db.cursor()
cursor.execute("SELECT * FROM requests WHERE status <> 'Finished'")
all_pending_requests = cursor.fetchall()
cursor.close()
And that works fine the first time i run it. But when i go to a tool like mysql workbench or i type it myself in in terminal, i update some rows and set their status to something that is not "Finished". So by doing that the next time the loop executes i should get those rows as a result but i get nothing. Do you guys now why this is happening maybe?
Thanks for help.
I am not certain but would assume that you are using InnoDB storage engine in MySQL and MySQLdb version >=1.2.0. You need to commit before the changes are being reflected. As of version 1.2.0, MySQLdb disables auto-commit by default. Confirmation of the same is here. Try adding db.commit() as the last line in the loop.

Error: "Cannot perform a backup or restore operation within a transaction." when trying to backup MSSQL database using pyodbc and freetds

I'm currently running into some problems when I'm trying to backup a MSSQL database from a Linux host using pyodbc and freetds. The versions are as follows:
Python 2.7.6, pyodbc 3.0.7, freetds 0.91-2, Centos 6.5
The code I'm running are as follows (with names and passwords etc removed):
import pyodbc
conn = pyodbc.connect('DRIVER=FreeTDS;SERVER=<servername>;PORT=<port>;DATABASE=<database>;UID=<user>;PWD=<password>;TDS_Version=8.0;Autocommit=True;')
sql = "exec dbo.backupStashDB"
cursor=conn.cursor().execute(sql)
while cursor.nextset():
pass
conn.close()
The error message I get is:
exec dbo.backupnameDB
Traceback (most recent call last):
File "soph_stash_db_bkp.py", line 6, in <module>
conn.execute(sql)
pyodbc.ProgrammingError: ('42000', '[42000] [FreeTDS][SQL Server]Cannot perform a backup or restore operation within a transaction. (3021) (SQLExecDirectW)')
I get the same message whether or not I run the command 'manually' or via a stored procedure as in this code example.
I did some googling and found references to adding 'Autocommit=True' would resolve this problem but that doesn't seem to make any difference at all.
Does anyone have any helpful insights to share on this one?
Thanks in advance, Mike
autocommit should be specified as a keyword argument to the pyodbc.connect function, it is not part of the ODBC connection string. See the section that starts with:
"Some keywords are used by pyodbc and are not passed to the odbc driver..."
Modify your code to the following:
...
conn = pyodbc.connect('DRIVER=FreeTDS;SERVER=<servername>;PORT=<port>;DATABASE=<database>;UID=<user>;PWD=<password>;TDS_Version=8.0;',
autocommit=True)
...

SQLite Insert command in Python script Doesn't work on web

I'm trying to use an SQLite insert operation in a python script, it works when I execute it manually on the command line but when I try to access it on the web it won't insert it in the database. Here is my function:
def insertdb(unique_id,number_of_days):
conn = sqlite3.connect('database.db')
print "Opened database successfully";
conn.execute("INSERT INTO IDENT (ID_NUM,DAYS_LEFT) VALUES (?,?)",(unique_id,number_of_days));
conn.commit()
print "Records created successfully";
conn.close()
When it is executed on the web, it only shows the output "Opened database successfully" but does not seem to insert the value into the database. What am I missing? Is this a server configuration issue? I have checked the database permissions on writing and they are correctly set.
The problem is almost certainly that you're trying to create or open a database named database.db in whatever happens to be the current working directory, and one of the following is true:
The database exists and you don't have permission to write to it. So, everything works until you try to do something that requires write access (like commiting an INSERT).
The database exists, and you have permission to write to it, but you don't have permission to create new files in the directory. So, everything works until sqlite needs to create a temporary file (which it almost always will for execute-ing an INSERT).
Meanwhile, you don't mention what web server/container/etc. you're using, but apparently you have it configured to just swallow all errors silently, which is a really, really bad idea for any debugging. Configure it to report the errors in some way. Otherwise, you will never figure out what's going on with anything that goes wrong.
If you don't have control over the server configuration, you can at least wrap all your code in a try/except and manually log exceptions to some file you have write access to (ideally via the logging module, or just open and write if worst comes to worst).
Or, you can just do that with dumb print statements, as you're already doing:
def insertdb(unique_id,number_of_days):
conn = sqlite3.connect('database.db')
print "Opened database successfully";
try:
conn.execute("INSERT INTO IDENT (ID_NUM,DAYS_LEFT) VALUES (?,?)",(unique_id,number_of_days));
conn.commit()
print "Records created successfully";
except Exception as e:
print e # or, better, traceback.print_exc()
conn.close()

Categories

Resources