python sqlite3: executescript fails - python

This is a minimum code:
import sqlite3 as sq3
import os
import sys
def main(argv):
q = 'select * from table_name;'
db = 'test.db'
con = sq3.connect(db)
cur = con.cursor()
cur.executescript(q) // cur.execute(q) will work
print cur.fetchone()
if __name__ == '__main__':
sys.exit(main(sys.argv))
My problem is executescript always fails while execute works fine. Is it because executescript is Nonstandard or some libraries I missed?

executescript isn't supposed to return anything, what would it return? The last statement? The first statement? or maybe that one in the middle.
Since it allows you to execute multiple SQL statements there is no way to tell which one you want to have returned.

executescript() is for executing multiple SQL commands, i.e., a script. What is the return value of multiple SQL commands? Hard to say, which is why executescript() returns None. You're not doing anything wrong nor do you have anything missing in your installation.

Related

Running multiple statements with MySQLdb

I'd like to run multiple statements with one command. Is it possible:
This is the SQL command:
UPDATE toggle SET state='0' WHERE feature_name=‘feature_1;
UPDATE toggle SET state=‘1’ WHERE feature_name=‘feature_2’;
UPDATE toggle SET state=‘1’ WHERE feature_name=‘feature_3’;
For one command I run something like that:
import MySQLdb
myDB = MySQLdb.connect(host=host, port=db_port, user=user, passwd=db_password, db=db)
cHandler = myDB.cursor()
cHandler.execute(query)
But this obviously works only for a single statement
Thanks!
Use parameterized query and executemany.

pymssql, can't execute EXEC command sql

i'm trying to execute this type of sql command with python but that doesn't work
import pymssql
_conn = pymssql.connect(** SQL parameter)
_cur = _conn.cursor()
_cur.execute("EXEC(SELECT * something)")
i got this error.
Thanks.
The EXECUTE command takes a string, not plain SQL commands:
EXEC('SELECT * something')
But I'm not sure why you're doing this, you could just pass the SELECT statement directly.

Oracle Python callproc() Script stops

I have a hughe problem.
I created a procedure and stored it in my OracleDB.
Now I want to execute the procedure, but its not working. There is no Error-Message Occuring, it just stops and dont continue after the first callproc call. Anybody any ideas?
!Autoincrement is enabled for the whole script!
import cx_Oracle dsn= cx_Oracle.makedsn("**********,1521,"orcl")
db= cx_Oracle.connect('******','*******',dsn)
db.autocommit = True cur = db.cursor()
cur.callproc("UPDATE_MISSING_VALUES", ['GENDER','***_PRE',1])
The Procedure is found and if I change the parameters, an SQL Error occurs. But if I let it like that, nothing happens.
If I run that query in SQL-Developer, it works just fine
It works now, I have actually now idea why, but the most important thing is that it works.
Is it possible, that the reason is that I made a
COMMIT;
Statement in my DB?? After that it worked suddenly.

Can Someone Explain the Difference in two Python Commands?

I want to do a subprocess.call to create a file (and eventually populate it). Here's my code:
#!/usr/bin/python
import sys
import subprocess
import psycopg2
import base64
import urlparse
sys.path.append('/var/www/cgi-bin')
def index(req):
out = ""
mkFile = str("touch /etc/httpd/conf/ipForward/90.conf")
subprocess.call([mkFile],shell=True)
return out
mkFile = str("touch /etc/httpd/conf/ipForward/111.conf")
subprocess.call([mkFile],shell=True)
Right now only the bottom command works, but these two subprocesses should do the same exact thing (I've named the file differently for testing purposes). I know there is a better way to do this but, for my own edification (and sanity) can someone explain the difference?
~~~~~~~~~~~~~~~~~~~~~~~EDIT COMPLETE CODE~~~~~~~~~~~~~~~~~~~~~
def index(req):
out = ""
conn = psycopg2.connect("dbname='pwp' host='localhost' user='~~~' password='~~~~~'")
c = conn.cursor()
inClCN = str(req.subprocess_env['SSL_CLIENT_S_DN_CN'])
c.execute("select * from Users where cn = '{0}';".format(inClCN))
rows = c.fetchall()
for row in rows:
port = row[0]
mkFile = str("touch /etc/httpd/conf/ipForward/{0}.conf".format(port))
subprocess.call([mkFile],shell=True)
insert = r"""Listen {0}\n\n<VirtualHost _default_:{1}>\n\nDocumentRoot '/var/www/html/'\nDirectoryIndex indexAlex.py\n\nRewriteEngine On\n\nErrorLog /etc/httpd/logs/error_log\nTransferLog /etc/httpd/logs/access_log\nLogLevel warn\n\n\nNSSVerifyClient require\n\nNSSEngine on\nNSSFIPS on\nNSSProtocol(MORE CONF STRING)</VirtualHost>""".format(port,port)
confFile = str('echo "{0}" >> /etc/httpd/conf/ipForward/{1}.conf'.format(insert,port))
subprocess.call([confFile],shell=True)
return out
The only reason I need the req is to get the environmental variable from apache. I don't really know how that works but I've been using that in other code without subprocesses.
Your first call to subprocess.call is within a def statement. A def statement doesn't actually call anything under it right away, instead it defines a function, which is a block of code you can reuse anywhere else.
The first "call" to subprocess.call doesn't do anything because you are just defining it as part of a reusable piece of code, but never actually using this reusable piece of code.
If you want to "use" the first call, you need to call the function you just defined using def:
Add the following to the end of your script:
index(None)
and the "first" call should happen, but after the first.
You can read more about how the def statement works and about functions here.

Why can't I use printf with sqlite when executed in Python

Per this page, printf belongs to the core functions of sqlite, so, with the sqlite3 shell, I can execute this statement successfully:
sqlite> create table foo as select printf("%5.2f", 42.424242) bar;
Yet, If I try to do what I believe is the same thing with a Python script, it errors with sqlite3.OperationalError: no such function: printf. Here's the script that I used:
# -*- coding: utf-8 -*-
import os
import sys
import sqlite3
db_filename = 'printf.db'
if os.path.isfile(db_filename):
os.remove(db_filename)
db = sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()
cur.execute(r'create table foo as select printf("%5.2f", 42.424242) bar')
Does someone know why that is?
Edit: As per g4ur4v's suggestion, I changed cur.execute('create... in the script to cur.execute(r'create.... The error did not change.
printf was added as a core function in version 3.8.3 of sqlite3. Likely the Python you are using uses an older version. This information can be found in these release notes:
2014-02-03 (3.8.3)
Added support for common table expressions and the WITH clause.
Added the printf() SQL function.
One way to check what version of the Sqlite3 library your Python is using is to issue this command:
print(sqlite3.sqlite_version)

Categories