replacing variable in SQL statement using django - django

I have a problem when using raw sql query which has a variable table name like
cursor.execute("SELECT description FROM %s WHERE id = 1", [table_name])
%s replaces the string in double quote which isn't executing properly.When I execute the above statement I get
"NameError: name 'nike_tshirts' is not defined"

Your should just put the table name between quotes 'table_name' / "table_name" or define the variable before: table_name = 'nike_tshirts'.
So:
cursor.execute("SELECT description FROM %s WHERE id = 1", 'nike_tshirts')
or
table_name = 'nike_tshirts'
cursor.execute("SELECT description FROM %s WHERE id = 1", table_name)
should work just fine.
Python raises a NameError because it thinks you are referring to a variable, when you are trying to refer to a string.

Related

DJANGO How to execute this sql in django.db with execute - SET PREPARE EXECUTE [duplicate]

import mysql.connector
connection = mysql.connector.connect(user="REMOVED",
password="REMOVED",
host="REMOVED",
database="REMOVED")
cur = connection.cursor()
# Latitude - remove letter A
cur.execute("UPDATE tau._inm_exportados_test_csv SET latitud = REPLACE (latitud, 'a=','');")
print("Latitude change remove letter A - executed!")
# Longitude - remove letter A
cur.execute("UPDATE tau._inm_exportados_test_csv SET longitud = REPLACE (longitud, 'a=','');")
print("Longitude change remove letter A - executed!")
# Latitude - MODIFY COLUMN
cur.execute("ALTER TABLE tau._inm_exportados_test_csv MODIFY COLUMN latitud DECIMAL(10,6);")
print("Latitude - MODIFY COLUMN - executed!")
# Longitude - MODIFY COLUMN
cur.execute("ALTER TABLE tau._inm_exportados_test_csv MODIFY COLUMN longitud DECIMAL(10,6);")
print("Longitude - MODIFY COLUMN - executed!")
# Post Code data type change
cur.execute("ALTER TABLE tau._inm_exportados_test_csv MODIFY COLUMN codigo_postal varchar(255);)")
print("Post Code data type change to varchar(255) - executed!")
connection.commit()
cur.close()
connection.close()
I'm trying to make this simple list of statements work without success. What makes it more confusing is that the first four statements work whereas the final one doesn't work even when I comment out the rest! The final statement gets the following reponse:
mysql.connector.errors.InterfaceError: Use multi=True when executing multiple statements
The datatype for codigo_postal is int(11) unlike latitud and longitud which are varchar.
I have tried creating new connections, new cursors, new connections AND cursors. I have tried adding multi="True" and combining statements into one operation. I have tried adding multi="True" to each cur.execute() as both the second and third parameter. I have run the statement in Workbench to ensure the statement is valid and it works.
No success with it here though...
You can use commit after you executed DML (Data Manipulation Language) commands. Also using multi=True can be more convenient to complete this job, but you need to run the generator which created by execute. doc.
Ordinary method:
cur = connection.cursor()
def alter(state,msg):
try:
cur.execute(state)
connection.commit()
except Exception as e:
connection.rollback()
raise e
print(msg)
alter("ALTER TABLE address MODIFY COLUMN id int(15);","done")
alter("ALTER TABLE address MODIFY COLUMN email varchar(35);","done")
alter("ALTER TABLE address MODIFY COLUMN person_id int(35);","done")
With multi=True:
cur = connection.cursor()
def alter(state,msg):
result = cur.execute(state,multi=True)
result.send(None)
print(msg,result)
try:
alter("ALTER TABLE address MODIFY COLUMN id int(45)","done")
alter("ALTER TABLE address MODIFY COLUMN email varchar(25)","done")
alter("ALTER TABLE address MODIFY COLUMN person_id int(25);","done")
connection.commit()
except Exception as e:
connection.rollback()
raise e
I had the same problem.
I wanted my code to be clean and I wanted to have all my commands in a list and just run them in a sequence.
I found this link and this link and finally was able to write this code:
import mysql.connector as sql
from mysql.connector import Error
commands = [
'''
USE sakila;
SELECT * FROM actor;
''',
'''
USE sakila;
SELECT * FROM actor WHERE actor_id < 10;
'''
]
connection_config_dict = {
'user': 'username',
'password': 'password',
'host': '127.0.0.1',
}
try:
connection = sql.connect(**connection_config_dict)
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info, '\n')
cursor = connection.cursor()
for command in commands:
for result in cursor.execute(command, multi=True):
if result.with_rows:
print("Rows produced by statement '{}':".format(
result.statement))
print(result.fetchall())
else:
print("Number of rows affected by statement '{}': {}".format(
result.statement, result.rowcount), '\n')
record = cursor.fetchall()
except Error as e:
print("Error while connecting to MySQL", e, '\n')
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed", '\n')

SQL String error? No Such Column

I'm using sqlite3 in my c++ program and am trying to run an SQL string in the
sqlite3_get_table function.
Here's my sql string.
SELECT name FROM sqlite_master WHERE type='table' AND name=test_table;
I keep getting the error "no such column "test_table"" .
All I am trying to do is confirm the existence of a table in my database. That's all.
Any clues as to what's wrong with my string.
In SQLite double quotes ('"') is the identifier-escape character, so assuming this is your SQL (raw SQL, nothing to do with C++):
SELECT
name
FROM
sqlite_master
WHERE
type = 'table'
AND
name = "test_table;"
Is equivalent to:
...
name = test_table
...which obviously isn't what you want.
You should use single-quoted strings in SQL, and the statement-terminating semicolon should go at the very end:
SELECT
name
FROM
sqlite_master
WHERE
type = 'table'
AND
name = 'test_table';

SSAS Rowset Action: Replace blank value from DMVs with a text string using MDX

Working in SSAS (inside Visual Studio Shell), I have a rowset action created that returns basic measure information from $SYSTEM.MDSCHEMA_MEASURES. Not all measures in the SSAS database have descriptions.
How can I replace BLANK description values with a simple text string "No description available."
"select [MEASURE_CAPTION], [MEASUREGROUP_NAME], [MEASURE_DISPLAY_FOLDER],[DESCRIPTION], [EXPRESSION]
from $SYSTEM.MDSCHEMA_MEASURES where [MEASURE_UNIQUE_NAME] = '" + Measures].CurrentMember.UniqueName + "'AND [CUBE_NAME] = '" + [Measures].CurrentMember.Properties("CUBE_NAME") + "'"
Returns:
Current Measure Description
Distinct Person Count
DESIRED Return:
Current Measure Description
Distinct Person Count No Description Available
Rowset Action Configuration
Is that just straight sql replacement of null or is your script returning a string "BLANK" ?
Try replacing [DESCRIPTION] with:
ISNULL([DESCRIPTION],'No Description Available')
or
CASE WHEN [DESCRIPTION] = 'BLANK' THEN 'No Description Available' ELSE [DESCRIPTION] END

How do i get the sqlite3 column

My code:
import sqlite3
conn = sqlite3.connect("keywords.db")
def search_location(name2):
name3 = ' '.join(name2)
c = conn.cursor()
c.execute('SELECT location FROM INPUT WHERE id = ?', (name3,))
for (location,) in c:
print name3.capitalize(),':' '\n',location
break
else:
pass # not found
Sqlite table:
sqlite>
CREATE TABLE input(
ID INT PRIMARY KEY AUTOINCRREMENT, NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY ....
);
I keep getting the error: No column LOCATION found. Items in name3 are to match the items in column NAME. If I change the code to read :
'SELECT NAME FROM INPUT WHERE id = ?', (name3,)
The error is the same. Please refer to the question I had asked earlier on How to improve sqlite database request and speed

How to parse SQL Queries and sub queries using sqlparser into python

Want to parse sql join query, select sub query into python. I am using sqlparse library. But i could not parse sub query. How i can parse whole query.
e.g:
query = "select id,fname,lname,address from res_users as r left join res_partner as p on p.id=r.partner_id where name = (select name from res_partner where id = 1)"
query_tokens = sqlparse.parse(query)[0].tokens
I could not parse for this select name from res_partner where id = 1 sub query.
Not so elegant, but works:
import sqlparse
from sqlparse.sql import Where, Comparison, Parenthesis
query = """
select
id,fname,lname,address
from
res_users as r
left join
res_partner as p
on
p.id=r.partner_id
where
name = (select name from res_partner where id = 1)"""
query_tokens = sqlparse.parse(query)[0]
where = next(token for token in query_tokens.tokens if isinstance(token, Where))
condition = next(token for token in where.tokens if isinstance(token, Comparison))
subquery = next(token for token in condition.tokens if isinstance(token, Parenthesis))
print subquery
prints:
(select name from res_partner where id = 1)
This library can parse and generate SQL https://code.google.com/p/python-sql/