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.
Related
I have a very simple piece of code:
#app.route('/read')
def db_read():
dbcursor.execute('SELECT * FROM books;')
result = dbcursor.fetchall()
return render_template('read.html', result=result)
When I start the server, everything works fine, however, if I make the changes to the database while the app is running, the changes are not reflected on /read page, the app has to be restarted to reflect them.
I expect the code to query database each time I refresh the page and the current behavior seems very counter-intuitive to me. Can someone please help?
Have you tried setting TEMPLATES_AUTO_RELOAD to true in your config? It should toggle ON when you run in debug mode but it seems like template reloading has always been a little buggy.
You should also be using the flask run --debug command as well. app.run has issues that the run command copes with.
Your cursor is intialized withing the app instance hence queries executed are saved to the instance as read only, so changes reflected to the database are persistent within the instance.
There are several workarounds to overcome this isssue.
I would recommend you to create separate module for database instance and import where ever required.
database.py
mydb = mysql.connector.connect(
host=cfg['host'],
user=cfg['user'],
passwd=cfg['password'],
database=cfg['database']
)
db = mydb.cursor()
app.py
from database import db
#app.route('/read')
def db_read():
db.execute('SELECT * FROM books;')
result = db.fetchall()
return render_template('read.html', result=result)
I am using MySQLdb package in Python to update my database. I have a simple update command as follows :
update_query = "update user_details set `address`='%s' where `id`='%s'"
cursor.execute(update_query, (address, id1))
print(cursor._last_executed)
Here is the command executed :
update user_details set `address`='35, Chikmagalur' where `id`='242069'
The program runs fine without error. However, the database is not getting updated. The same command works when I run as an SQL query on PHPMyAdmin.
Any idea what could be the issue ?
this is a duplicate of ...
sql transactions needs to be committed, either explicitly or implicitly.
either issue a commit command explicitly
cursor._get_db().commit()
setting the connection to autocommit when opening the connection is also an option.
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.
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)
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.