LefterisL
LefterisL

Reputation: 1153

Python MySQL if variable does not exists still submit

I'm doing some queries ( inserts ) to a database based on some input. However not all the times I get all the data from the user. I still would like though to insert the data that I received. I have a table with close to 10 columns but in the data I also have some arrays.

When I'm trying to insert something I get an exception that the say input['name'] does not exists and the query is not executed.

Is there some way to quickly manage that? If a variable does isn't defined simply throw a warning like in PHP and not break the whole loop.

New to python and only thing I can think of is to check for every single variable but I'd really hope there's something more simpler than this and quicker.

Upvotes: 2

Views: 80

Answers (2)

Termi
Termi

Reputation: 661

Do input.get('name')

From the docs https://docs.python.org/2/library/stdtypes.html#dict.get

Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method never raises a KeyError.

Upvotes: 1

MarkHarley
MarkHarley

Reputation: 116

You should look into exception handling. It sounds like you need to use an try-except-else where you're making use of input['name']

Upvotes: 0

Related Questions