Use of %s format specifier or format() to perform queries means using python code to insert values into SQL queries using placeholders and formatting methods.

The %s format specifier is used with the % operator to perform string formatting in python. It allows you to format a value inside a string by replacing the %s with the value passed as an argument. 

For example, to insert a name into a string, you can write:

name = "Bob"

print("Hello, %s" % name)

The %s format specifier can also be used to insert values into SQL queries.

For example, to insert a username and a password into an insert query, you can write:

sql_query = "INSERT INTO TEACHOOLOGIN (username, password) VALUES (%s, %s)"

values = ("craig", "1234")

my_database.execute(sql_query, values)

Note that the %s is used as a placeholder for the values , and the values are passed as a tuple or a list as the second argument of the execute() method . This is a good practice to avoid SQL injection attacks and errors due to data types.

The format() method is another way to perform string formatting in python . It allows you to format a value inside a string by using curly braces {} as placeholders and passing the values as arguments or keywords.

For example, to insert a name into a string, you can write:

name = "Bob"

print("Hello, {}".format(name))

The format() method can also be used to insert values into SQL queries.  

For example, to insert a username and a password into an insert query, you can write:

sql_query = "INSERT INTO TEACHOOLOGIN (username, password) VALUES ({}, {})"

values = ("craig", "1234")

my_database.execute(sql_query.format(*values))

Note that the curly braces {} are used as placeholders for the values, and the values are passed as a tuple or a list and unpacked with the * operator as an argument of the format() method. This is also a good practice to avoid SQL injection attacks and errors due to data types.

 

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo