[Tutor] String representation of NULL (non type) values

Danny Yoo dyoo at hashcollision.org
Tue Nov 5 20:02:53 CET 2013


>
>
> from a SQLite database I get a value by SELECT s from... which normaly is
> a string, but can be the NULL value, wich means it is not defined. To put
> the value into a form (made by QT) I need a string representation.
>
> str(s) gives either the string itself (which is good) or "None" (which is
> not so good) in the case of NULL. Instead of "None" I would prefer an empty
> string "". How to get that?
>
> Possibly there is a build in function smart(s1, s2, s3,...) which returns
> the first s which is a useable string, or even "" if there isn't any string
> in the arguments?
>
>

Be extra careful if you're constructing SQL statements from user input.
 You have probably heard of the term "SQL Injection" or "Bobby Tables",
both of which are pretty much the same thing: your user may, intentionally
or not, input values that can be interpreted as SQL commands rather than as
literal data.

If you know up front what what possible values you're allowing for your
column selection, I'd recommend explicitly enumerating them in a function,
and then guarantee that your code will deal with just those columns.  E.g.

################################################
SAFE_COLUMNS = ['name', 'age', 'phone', 'favorite_pokemon']
#
# ... later in the code
#
if s in SAFE_COLUMNS:
    # ... we're good to go.
else:
    raise ValueError('Unknown column', s)
################################################

That is, prevent insertion of arbitrary, user-defined values in your SQL
query string unless you really have no other choice.

Also see:



http://stackoverflow.com/questions/6514274/how-do-you-escape-strings-for-sqlite-table-column-names-in-python


Best of wishes!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131105/b5b03136/attachment-0001.html>


More information about the Tutor mailing list