execute()

Specifies a SQL statement to execute.

See also: MariaDB Connector/Python 1.0

DETAILS

Specify a SQL statement to execute. The optional parameters provide a sequence or mapping that are bound to "variable" markers in the SQL statement. These variables are usually specified as question marks (paramstyle="qmark"), however a paramstyle of "format" or "pyformat" are also supported (as long as one style is used per call).

EXAMPLES

Given the following "sample" table in database "test":

CREATE TABLE sample (
  num INTEGER,
  str VARCHAR(64),
  ts DATE
);

The following will INSERT 3 rows and then SELECT all the rows in the table:

import mariadb

conn = mariadb.connect(
    host = 'localhost',
    user = 'root',
    password = 'secret',
    database = 'test',
    )

cursor = conn.cursor()

# The values for "qmark" style are always specified as a tuple:
cursor.execute("INSERT INTO sample VALUES (?, ?, ?)",
    (1, "A 'string' with single quotes.", '2020-01-01'))

# The values for "format" style are also specified as a tuple:
cursor.execute("INSERT INTO sample VALUES (%d, %s, %s)",
    (2, 'A "string" with double quotes.', '2020-01-02'))

# The values for "pyformat" style are specified as a dict:
cursor.execute("INSERT INTO sample VALUES (%(num)s, %(str)s, %(ts)s)",
    {
        'num': 3,
        'str': "Another simple string value...",
        'ts': '2020-01-03',
    })

cursor.execute("SELECT * FROM sample")

# This will output all the column names for the above SELECT:
print([x[0] for x in cursor.description])

# ... and then output all the rows (as tuples):
for row in cursor:
    print(row)

conn.close()

The output when starting with an empty table would look like this:

['num', 'str', 'ts']
(1, "A 'string' with single quotes.", datetime.date(2020, 1, 1))
(2, 'A "string" with double quotes.', datetime.date(2020, 1, 2))
(3, 'Another simple string value...', datetime.date(2020, 1, 3))