HAKATEMIA
33Backend basics

Database connections

Easy5MIN

Next, let's see how the background system is connected to the database so that the application can save, modify, search, and delete data.

Old, dangerous way

In the past, it was typical for web applications to talk to databases by building raw SQL queries, often combining user input with the query. If we think of a simple todo list application, the code that adds a new task could look like this:

PY
1@app.route('/todos', methods=['POST'])
2def create_todo():
3    title = request.form['title']
4    result = connection.execute(f"INSERT INTO todos (title) VALUES ('{title}')")
5    todo_id = result.lastrowid
6    return '', 204
7

If you remember from the module on HTML templates that this old-fashioned template in HTML construction led to XSS vulnerabilities, you might already guess what kind of vulnerability this becomes. The correct answer is SQL injection. If the user input a quotation mark in the title variable, then the user could change the structure of the SQL query as they please.

You can learn more about SQL injections at Hakatemian SQL injection course, but let's now look at the correct, modern way to use a database from a web application backend.

1 / 4
Hakatemia Pro

Learn to hack — start here

Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.