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)
Related
I'm having lots of trouble with a pythron script that I'm trying to run through crom.
The python script does a few things. It starts by importing modules for SQL, grabs information from an SQL database, turns the information into a text-to-speech string, and then reads it out loud. I currently have the server and the script on a raspberry pi, and when I run the script through the command prompt, it works fine.
However, I can't seem to get the script to run through cron. I've never used cron before, so I don't know much about how to debug it. Whenever I use grep CRON /var/log/syslog, it tells me that its executed when it's supposed to, so it's difficult to tell if its an error with the script running, or if the audio isn't playing. I'm happy to try out any potential solutions, and I'm a beginner to crom, so I wouldn't be surprised if it was something minor that I haven't come across yet. Any help is appreciated!
Edit 1: Here is a minimal reproducible example:
My python script effectively is:
# python sql commands
import pymysql
import os
from gtts import gTTS
#Please keep in mind that this information is just a placeholder, and not what is actually in the script - the script works as intended
db = pymysql.connect(host = "localhost",user = "root",password = "", database = "mydb")
cursor = db.cursor()
sql = "SELECT * FROM table"
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results
name = row[0]
atext = name
speech = gTTS(text = atext, lang = "en")
speech.save("speech.mp3")
os.system("omxplayer -o local speech.mp3")
db.close()
In the crontab, I have it set to run each minute:
* * * * * python3 /path/to/file/"Assignment Grabber.py"
The goal is for the python script to read the text out loud. It does this perfectly when I manually run the python script through the terminal. However, putting it into the crontab and waiting results with nothing.
I use Python 2.5 and informixdb. I want to connect with the database, but what are the parameters for the informixdb.connect() method?
I have
Hostname
Port
Databasename
User
Password
But what is the right order? Or how is the dsn String build?
The official documentation does not really help me.
The documentation says i can use
informixdb.connect(dsn)
but they do not explain how a DataSourceString should looks like. What arguments and in which order are needed.
Here is an link to the documentation.
And i know Python 2.5 is very old, but the database does not support Python 3.x i have tried it.
From the documentation at https://sourceforge.net/projects/informixdb/:
To do anything useful with InformixDB one must connect to a database. This is accomplished by calling informixdb.connect:
>>> import informixdb
>>> conn = informixdb.connect('db#daniel', user='me', password='something')
>>> conn
<_informixdb.Connection object at 0xb7d08e90>
informixdb.connect takes three arguments: A dsn which identifies the database and server to connect to, as recognized by ESQL's CONNECT statement (e.g. 'database#server', 'database', '#server') plus an optional user and a corresponding password.
If the dsn doesn't include a servername the value of the environment variable INFORMIXSERVER is used. When connecting without specifying the name of the database no database will be selected. This is useful for setting up a new database from within InformixDB.
Why not use the new "IfxPy" OpenInformix module?
https://github.com/OpenInformix/IfxPy
It has support for both 2.x and 3.x versions of Python.
I am trying to get code completion for the psycopg2 library in PyCharm 2018.1 but it is not showing cursor class methods like .execute() or .fetchone().
Here is my code:
import logging
import psycopg2 as pg
#Code completion works fine here.
logger = logging.getLogger()
logger.info("Hello World!")
#Code completion works fine here.
con = pg.connect("dbname='postgres' port='5432'")
#Code completion not working!
cur = con.cursor()
That's because:
Psycopg 2 is mostly implemented in C as a libpq wrapper
So you have autocomletion for pg.connect() because it exists in __init__.py and mostly the rest of features are listed as .c and .h files https://github.com/psycopg/psycopg2/tree/master/psycopg that are being handled by setup.py.
In my case the solution is to reset the settings.
From the main menu, select File > Manage IDE Settings > Restore Default Settings.
Alternatively, press Shift twice and type Restore default settings
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.
I want to execute SQL queries from the Python script environment in MySQL Workbench. I looked at the MySQL Workbench documentation for the grt module and found the executeScript method but I can't seem to use it to make queries.
Executing this Python code:
import grt
querystring = "select * from Purchases WHERE PurchaseAmount > 600 and PurchaseAmount < 2500"
executeScript(querystring)
produces the following error message:
Uncaught exception while executing [filepath]runquery.py:
File "[filepath]runquery.py", line 10, in <module>
executeScript(querystring)
NameError: name 'executeScript' is not defined
I don't understand what virtual grt::ListRef executeScript ( const std::string & sql ) means so I can't format my query properly, however, the error message seems to indicate that the executeScript method doesn't exist anyway. Most documentation I look at has examples of correctly-formatted function calls but I can't seem to find any for executeScript.
All I want to do is literally run my string as an SQL query within the MySQL Workbench Python scripting environment.
Thank you!
I am new to Python and SQL so please be patient. :)
To run executeScript function you need to interact with an sqleditor object.
For testing, do the next on MS Windows with the example databases:
Start MySQLWorkbench
connect to local database
select sakila from SCHEMAS
start scripting shell with Tools->scripting shell or (Ctrl+F3)
Add new python script (test.py)
Save script with the content below
run script in scripting shell
Script content:
import grt
result = grt.root.wb.sqlEditors[0].executeScript("select * from actor limit 10;")
for col in result[0].columns:
print col.name
To find out how to reference objects in the script, it is very easy to use the Globals Tree panel's class browser and using right mouse click on the object and choose "Copy Path for Python"
You can run something like the following command if you need to run your script from command line in Windows:
"C:\Program Files\MySQL\MySQL Workbench 6.1 CE\MySQLWorkbench.exe" -query "Local instance MySQL56" -run-python "execfile('c:\Users\Root\AppData\Roaming\MySQL\Workbench\scripts\script.py')" -log-to-stderr -v
The (first) problem seems to be that you use a function called executeScript(), which you haven't defined or taken from anywhere. If it is in the grt module (which I am not familiar with) you have to do it as follows:
from grt import executeScript
querystring = "select * from Purchases WHERE PurchaseAmount > 600 and PurchaseAmount < 2500"
executeScript(querystring)