File: usage.rst

package info (click to toggle)
mariadb-connector-python 1.1.14-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 952 kB
  • sloc: python: 6,288; ansic: 4,973; sh: 23; makefile: 14
file content (263 lines) | stat: -rw-r--r-- 8,876 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
***********
Basic usage
***********

.. sectionauthor:: Georg Richter <georg@mariadb.com>

Connecting
##########

The basic usage of MariaDB Connector/Python is similar to other database drivers which
implement |DBAPI|. 

Below is a simple example of a typical use of MariaDB Connector/Python

.. testsetup::

   import mariadb

   # connection parameters
   conn_params= {
      "user" : "example_user",
      "password" : "GHbe_Su3B8",
      "host" : "localhost",
      "database" : "test"
   }

   # Establish a connection
   with mariadb.connect(**conn_params) as conn:
      with conn.cursor() as cursor:
         cursor.execute("CREATE OR REPLACE TABLE `countries` ("
                   "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
                   "`name` varchar(50) NOT NULL,"
                   "`country_code` char(3) NOT NULL,"
                   "`capital` varchar(50) DEFAULT NULL,"
                   "PRIMARY KEY (`id`),"
                   "KEY `name` (`name`),"
                   "KEY `capital` (`capital`)"
                   ") ENGINE=InnoDB DEFAULT CHARSET=latin1")

.. testcode::

    import mariadb

    # connection parameters
    conn_params= {
        "user" : "example_user",
        "password" : "GHbe_Su3B8",
        "host" : "localhost",
        "database" : "test"
    }

    # Establish a connection
    with mariadb.connect(**conn_params) as conn:
        with conn.cursor() as cursor:
            # Populate countries table  with some data
            cursor.execute("INSERT INTO countries(name, country_code, capital) VALUES (?,?,?)",
                ("Germany", "GER", "Berlin"))

            # retrieve data
            cursor.execute("SELECT name, country_code, capital FROM countries")

            # print content
            row= cursor.fetchone()
            print(*row, sep=' ')

*Output*:

.. testoutput::

    Germany GER Berlin


Before MariaDB Connector/Python can be used, the MariaDB Connector/Python module must be 
imported.
Once the mariadb module is loaded, a connection to a database server will be established
using the method :func:`~mariadb.connect`.

In order to be able to communicate with the database server in the form of SQL statements, 
a cursor object must be created first. 

The method name cursor may be a little misleading: unlike a cursor in MariaDB that can only
read and return data, a cursor in Python can be used for all types of SQL statements.

After creating the table mytest, everything is ready to insert some data: Column values
that are to be inserted in the database are identified by place holders, the data is then passed in
the form of a tuple as a second parameter.

After creating and populating the table mytest the cursor will be used to retrieve the data.

At the end we free resources and close cursor and connection.

Passing parameters to SQL statements
####################################
As shown in previous example, passing parameters to SQL statements happens by using placeholders in the statement. By default
MariaDB Connector/Python uses a question mark as a placeholder, for compatibility reason also %s placeholders are supported.
Passing parameters is supported in methods :func:`~execute` and :func:`~executemany` of the cursor class.

Since |MCP| uses binary protocol, escaping strings or binary data like in other database drivers is not required.

.. testcode::

    import mariadb

    # connection parameters
    conn_params= {
        "user" : "example_user",
        "password" : "GHbe_Su3B8",
        "host" : "localhost",
        "database" : "test"
    }

    # Establish a connection
    with mariadb.connect(**conn_params) as conn:
        with conn.cursor() as cursor:
            sql= "INSERT INTO countries (name, country_code, capital) VALUES (?,?,?)"
            data= ("Germany", "GER", "Berlin")
            cursor.execute(sql, data)

            conn.commit()

            # delete last entry
            sql= "DELETE FROM countries WHERE country_code=?"
            data= ("GER",)
            cursor.execute(sql, data)

            conn.commit()


Often there is a requirement to update, delete or insert multiple records. This could be done be using :func:`~execute` in
a loop, but much more effective is using the :func:`executemany` method, especially when using a MariaDB database server 10.2 and above, which supports a special "bulk" protocol. The executemany() works similar to execute(), but accepts data as a list of tuples:

.. testcode:: python

    import mariadb

    # connection parameters
    conn_params= {
        "user" : "example_user",
        "password" : "GHbe_Su3B8",
        "host" : "localhost",
        "database" : "test"
    }

    # Establish a connection
    with mariadb.connect(**conn_params) as connection:
        with connection.cursor() as cursor:
            sql= "INSERT INTO countries (name, country_code, capital) VALUES (?,?,?)"

            data= [("Ireland", "IE", "Dublin"),
                   ("Italy", "IT", "Rome"),
                   ("Malaysia", "MY", "Kuala Lumpur"),
                   ("France", "FR", "Paris"),
                   ("Iceland", "IS", "Reykjavik"),
                   ("Nepal", "NP", "Kathmandu")]

            # insert data
            cursor.executemany(sql, data)

            # Since autocommit is off by default, we need to commit last transaction
            connection.commit()

            # Instead of 3 letter country-code, we inserted 2 letter country code, so
            # let's fix this mistake by updating data
            sql= "UPDATE countries SET country_code=? WHERE name=?"
            data= [("Ireland", "IRL"),
                   ("Italy", "ITA"),
                   ("Malaysia", "MYS"),
                   ("France", "FRA"),
                   ("Iceland", "ISL"),
                   ("Nepal", "NPL")]
            cursor.executemany(sql, data)

            # Now let's delete all non European countries
            sql= "DELETE FROM countries WHERE name=?"
            data= [("Malaysia",), ("Nepal",)]
            cursor.executemany(sql, data)

            # by default autocommit is off, so we need to commit
            # our transactions
            connection.commit()


When using executemany(), there are a few restrictions:
- All tuples must have the same types as in first tuple. E.g. the parameter [(1),(1.0)] or [(1),(None)] are invalid.
- Special values like None or column default value needs to be indicated by an indicator.

Using indicators
****************

In certain situations, for example when inserting default values or NULL, special indicators must be used.

.. testcode::

    import mariadb
    from mariadb.constants import *

    import mariadb

    # connection parameters
    conn_params= {
        "user" : "example_user",
        "password" : "GHbe_Su3B8",
        "host" : "localhost",
        "database" : "test"
    }

    # Establish a connection
    with mariadb.connect(**conn_params) as connection:
        with connection.cursor() as cursor:
            cursor.execute("DROP TABLE IF EXISTS cakes")
            cursor.execute("CREATE TABLE cakes(id int, cake varchar(100), price decimal(10,2) default 1.99)")

            sql= "INSERT INTO cakes (id, cake, price) VALUES (?,?,?)"
            data= [(1, "Cherry Cake", 2.10), (2, "Apple Cake", INDICATOR.DEFAULT)]
            cursor.executemany(sql, data)

Beside the default indicator which inserts the default value of 1.99, the following indicators are supported:
   * INDICATOR.IGNORE: Ignores the value (only update commands)
   * INDICATOR.NULL: Value is NULL
   * INDICATOR.IGNORE_ROW: Don't update or insert row

.. note::
  * Mixing different parameter styles is not supported and will raise an exception
  * The Python string operator % must not be used. The :func:`~execute` method accepts a tuple or list as second parameter.
  * Placeholders between quotation marks are interpreted as a string.
  * Parameters for :func:`~execute` needs to be passed as a tuple. If only one parameter will be passed, tuple needs to contain a comma at the end.
  * Parameters for :func:`~executemany` need to be passed as a list of tuples.

Supported Data types
--------------------

Several standard python types are converted into SQL types and returned as Python objects when a statement is executed.

.. list-table:: Supported Data Types
    :align: left
    :header-rows: 1

    * - Python type
      - SQL type
    * - None
      - NULL
    * - Bool
      - TINYINT
    * - Float, Double
      - DOUBLE
    * - Decimal
      - DECIMAL
    * - Long
      - TINYINT, SMALLINT, INT, BIGINT
    * - String
      - VARCHAR, VARSTRING, TEXT
    * - ByteArray, Bytes
      - TINYBLOB, MEDIUMBLOB, BLOB, LONGBLOB
    * - DateTime
      - DATETIME
    * - Date
      - DATE
    * - Time
      - TIME
    * - Timestamp
      - TIMESTAMP

{% @marketo/form formId=\"4316\" %}