Executing SQL commands

Suppose that the connection is established and there is a variable conn that refers to the instance of the class connection. To execute a SQL command, it is necessary to first create a cursor object that will represent the context of the command. Cursors are created by calling the connection.cursor() method of a connection, as follows:

cur = conn.cursor()

Now the variable cur refers to the cursor object. Optionally, the method cursor() can take the following parameters:

  • name: When specified, the cursor will represent a server-side cursor. The difference between client-side and server-side cursors is that the first would usually download the whole result set and store it in memory, and the last would ask the server to give the data in portions when the application is ready to process it.
  • cursor_factory: This is used to create non-standard cursors.
  • scrollable: This only works with server-side cursors. When set to true, the cursor will be able to scroll back when iterating over the result set.
  • withhold: This only works with server-side cursors. When set to true, the cursor will be able to fetch data even after the transaction commit (but not after rollback).

After a cursor is created, the method cursor.execute() should be used to execute an SQL command. For example to select rows or to delete records, the following code can be used:

cur.execute("SELECT * FROM car_portal_app.car_model")
cur.execute("DELETE FROM car_portal_app.car_model WHERE car_model_id = 2")

To use query parameters, one should specify them in the query and pass their values as a second argument to the method cursor.execute(). For example, to insert a record into a table, the following code would be used:

new_make = "Ford"
new_model = "Mustang"
sql_command = "INSERT INTO car_portal_app.car_model (make, model) "
"VALUES (%s, %s)"
cur.execute(sql_command, [new_make, new_model])

Here, positional notation was used, meaning that the order of the parameter values must be the same as the order of the parameters placeholder's in the query string. Note the backslash at the end of the third line in the preceding example. It is used to separate long lines of code and tells the Python interpreter that the expression continues on the following line. 

psycopg2 also supports named notation for specifying parameter values. The same example could look like this:

new_make = "Ford"
new_model = "Mustang"
sql_command = "INSERT INTO car_portal_app.car_model (make, model) "
"VALUES (%(make)s, %(model)s)"
cur.execute(sql_command, {"model": new_model, "make": new_make})

Using parameters when executing SQL commands may seem more complicated than including the values of them directly in the command text, like this:

new_make = "Ford"
new_model = "Mustang"
sql_command = "INSERT INTO car_poral_app.car_model (make, model) "
"VALUES ('" + new_make + "', '" + new_model + "')"
cur.execute(sql_command)

However, this is wrong! Never put data directly in to the SQL command. This can lead to a serious security issue. Imagine if the value of the variable new_model was a single quote character '. Then the SQL that is sent to the server will look like this: INSERT INTO car_portal_app.car_model (make, model) VALUES ('Ford', '''), which is obviously wrong. This command will simply not work, causing the database to raise an exception. In a web application, this could crash the server or make it possible to retrieve data that is secret. If parameters were used, then psycopg2 would take care that this character ' is properly inserted into the table as if it was a valid car model name.

This misbehavior is called SQL injection.

The same cursor object can be used multiple times to execute several queries. However, cursors are not thread safe. This means the same cursor should not be used by multiple threads. Several cursors should be created in this case. The connection object is thread safe though.

There is a sample script that inserts a record into the table car_model in the psycopg2_insert_data.py file in the attached media.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset