%d format: a number is required not list - python-2.7

I want to print a column values from a table using this query -
cursor = self.conn.execute ("select column1 from table_name where column2 =='%d'"%(number))
Value = cursor.fetchall()
Print value

The mentioned query format is not secure, you can try binding in this way:
self.conn.execute('SELECT column1 FROM table_name WHERE column2 = ?', (number,))
According the docs (Sqlite3 Docs):
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)

You have declared your database item as ATOMIC NUMBER so either change that to ATOMIC_NUMBER or change the code to put inverted commas around the two words "ATOMIC NUMBER".
AND for the 5th time now read the StackOverflow Tour guide so that you can behave in a way that doesn't annoy the people that are trying to answer your questions.
https://stackoverflow.com/tour

Related

put a word with white space as a variable in a sql query using .format()

I would like to know how to put a word with white space as a variable in a sql query (I use postgresql)
data = "something with white space"
choice = "DESC"
limit = 10
def rDB(sql_request):
with connection.cursor() as cursor:
cursor.execute(sql_request)
row = cursor.fetchall()
return row
queryWithFormat(data, choice, limit):
return('''
SELECT col1, SUM(col2) as nb
FROM Table
WHERE col1 = {d}
GROUP BY col1
ORDER BY nb {c}
LIMIT {l}
'''.format(d=data, c=choice, l=limit)
rDB(queryWithFormat(data, choice, limit))
django.db.utils.ProgrammingError: ERROR: syntax error on or near 'with'
LINE 8: WHERE col1 = something with white ...
-------------------------------^
Possible solution but I don't know if it's a good practice
unpack sql request
i use format() for "DESC"/"ASC"
and %s for word with white space
fdsfe
def requeteDB(sql_request):
with connection.cursor() as cursor:
cursor.execute(*sql_request)
row = cursor.fetchall()
return row
queryWithFormat(data, choice, limit):
return('''
SELECT col1, SUM(col2) as nb
FROM Table
WHERE col1 = %s
GROUP BY col1
ORDER BY nb {0}
LIMIT %s
'''.format(choice), [data,limit])
The best way is to not use Python's native string formatting at all! Instead, you should create a parameterised query.
It would be possible to make your code work, I think, by quoting the variable col1 = '{d}', but I am telling you this for information only and you should not do it. It is a security risk. For best practice, see this section of the docs.
Django aside (not my area of expertise...), it looks like you're using SQLAlchemy to execute the query. This library has its own syntax and methods for parameter binding, which you could implement as follows:
from sqlalchemy.sql import text
def query_with_format(data, choice, limit):
query = text("""
SELECT col1, SUM(col2) as nb
FROM Table
WHERE col1 = :d
GROUP BY col1
ORDER BY nb :c
LIMIT :l
""")
query.bindparams(d=data, c=choice, l=limit)
return query
rDB(query_with_format(data, choice, limit))
I do not think you will have any trouble with variables containing whitespace with this approach, and it is far, far safer.

How do you query table names and row counts for all tables in a schema using HP NonStop SQL/MX?

How do you query table names and row counts for all tables in a schema using HP NonStop SQL/MX?
Thanks!
This might help you, althought this is more standard SQL and im not sure how much variation comes into sqlmx
SELECT
TableName = t.NAME,
TableSchema = s.Name,
RowCounts = p.rows
FROM
sys.tables t
INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
t.is_ms_shipped = 0
GROUP BY
t.NAME, s.Name, p.Rows
ORDER BY
s.Name, t.Name
Obviously this is an example, replace example data and table info with yours
Here is how to list the tables in a sql/mx schema, note that the system catalog name given here is an example, replace NONSTOP_SQLMX_SYSNAME with NONSTOP_SQLMX_xxxx where xxxx is the Expand node name of your system.
Also the definition schema name includes the schema version number, this example uses 3600. This example lists all the base table names in schema JDFCAT.T.
See chapter 10 of the SQL/MX reference manual for information on the metadata tables.
The table row counts are not stored in the system metadata, so you can't get them from there. For a table do SELECT ROW COUNT FROM TABLE;
SELECT
O.OBJECT_NAME
FROM
NONSTOP_SQLMX_SYSNAME.SYSTEM_SCHEMA.CATSYS C
INNER JOIN NONSTOP_SQLMX_SYSNAME.SYSTEM_SCHEMA.SCHEMATA S
ON (S.CAT_UID = C.CAT_UID)
INNER JOIN JDFCAT.DEFINITION_SCHEMA_VERSION_3600.OBJECTS O
on S.SCHEMA_UID = o.SCHEMA_UID
WHERE C.CAT_NAME = 'JDFCAT' AND
S.SCHEMA_NAME = 'T' AND
O.OBJECT_TYPE = 'BT'
READ UNCOMMITTED ACCESS;

SqlAlchemy core union_all not adding parentheses

I have the following sample code:
queries = []
q1 = select([columns]).where(table.c.id == #).limit(#)
queries.append(q1)
q2 = select([columns]).where(table.c.id == #).limit(#)
queries.append(q2)
final_query = union_all(*queries)
The generated SQL should be this:
(select columns from table where id = # limit #)
UNION ALL
(select columns from table where id = # limit #)
But, I'm getting
select columns from table where id = # limit #
UNION ALL
select columns from table where id = # limit #
I tried using subquery, as follows for my queries:
q1 = subquery(select([columns]).where(table.c.id == #).limit(#))
The generated query then looks like this:
SELECT UNION ALL SELECT UNION ALL
I also tried doing
q1 = select([columns]).where(table.c.id == #).limit(#)).subquery()
But, I get the error:
'Select' object has no attribute 'subquery'
Any help to get the desired output with my subqueries wrapped in parentheses?
Note: this is not a duplicate of this question, because I'm not using Session.
EDIT
Okay, this works, but I don't believe it is very efficient, and it's adding an extra select * from (my sub query), but it works.
q1 = select('*').select_from((select(columns).where(table.c.id == #).limit(#)).alias('q1'))
So, if anyone has any ideas to optimize, or let me know if this is as good as it gets. I would appreciate it.
The author of SQLAlchemy seems to be aware of this and mentions a workaround for it on the SQLAlchemy 1.1 changelog page. The general idea is to do .alias().select() on each select.
stmt1 = select([table1.c.x]).order_by(table1.c.y).limit(1).alias().select()
stmt2 = select([table2.c.x]).order_by(table2.c.y).limit(2).alias().select()
stmt = union(stmt1, stmt2)

Escaping queries in Django

I have the following method:
def select_query(self):
sql = "SELECT * FROM {t} WHERE 1".format(t=self._meta.db_table)
for column_name in self.distinguishing_column_names():
sql = sql + " AND {c} = {v}".format(c=column_name, v=getattr(self, column_name))
return sql
This will give me a query like this:
SELECT * FROM customer WHERE 1 AND name = JOHN SMITH AND customer_number = 11423 AND social_security_number = 1234567890 AND phone = 2323523353
Obviously, that's not going to work. Is there a way to get Django to quote this for me?
Note: I'm not asking for a prepared statement. That's something different.
Do you need to return a query this way? The proper way would be to call cursor with the query and the params as argument:
Does Python support MySQL prepared statements?
The correct way to format a query seems to be:
query = query % db.literal(args)
Where db is a mysql.Connection (or presumably any connection)
Apparently the answer is "no."

Nested statements in sqlite

I'm using the sqlite3 library in c++ to query the database from *.sqlite file. can you write a query statement in sqlite3 like:
char* sql = "select name from table id = (select full_name from second_table where column = 4);"
The second statement should return an id to complete the query statement with first statement.
Yes you can, just make sure that the nested query doesn't return more than one row. Add a LIMIT 1 to the end of the nested query to fix this. Also make sure that it always returns a row, or else the main query will not work.
If you want to match several rows in the nested query, then you can use either IN, like so:
char* sql = "select name from table WHERE id IN (select full_name from second_table where column = 4);"
or you can use JOIN:
char* sql = "select name from table JOIN second_table ON table.id = second_table.full_name WHERE second_table.column = 4"
Note that the IN method can be very slow, and that JOIN can be very fast, if you index on the right columns
On a sidenote, you can use SQLiteadmin (http://sqliteadmin.orbmu2k.de/) to view the database and make queries directly in it (useful for testing etc).