PageRenderTime 75ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/resources/lib/mysql-connector-python/docs/mysql-connector-python.txt

https://github.com/wtmmac/mythbox
Plain Text | 2386 lines | 1833 code | 553 blank | 0 comment | 0 complexity | 7ce7cf45ad9cf7d012c7af07d97291a0 MD5 | raw file
Possible License(s): Unlicense, AGPL-1.0, BSD-2-Clause, GPL-2.0, MIT, Apache-2.0
  1. MySQL Connector/Python
  2. Abstract
  3. This manual describes how to install, configure, and develop
  4. database applications using MySQL Connector/Python, a
  5. self-contained Python driver for communicating with MySQL servers.
  6. Document generated on: 2012-12-17 (revision: 33584)
  7. _______________________________________________________
  8. Preface and Legal Notices
  9. This manual describes how to install, configure, and develop
  10. database applications using MySQL Connector/Python, the a
  11. self-contained Python driver for communicating with MySQL servers.
  12. Legal Notices
  13. Copyright (c) 2012, Oracle and/or its affiliates. All rights
  14. reserved.
  15. This software and related documentation are provided under a
  16. license agreement containing restrictions on use and disclosure
  17. and are protected by intellectual property laws. Except as
  18. expressly permitted in your license agreement or allowed by law,
  19. you may not use, copy, reproduce, translate, broadcast, modify,
  20. license, transmit, distribute, exhibit, perform, publish, or
  21. display any part, in any form, or by any means. Reverse
  22. engineering, disassembly, or decompilation of this software,
  23. unless required by law for interoperability, is prohibited.
  24. The information contained herein is subject to change without
  25. notice and is not warranted to be error-free. If you find any
  26. errors, please report them to us in writing.
  27. If this software or related documentation is delivered to the U.S.
  28. Government or anyone licensing it on behalf of the U.S.
  29. Government, the following notice is applicable:
  30. U.S. GOVERNMENT RIGHTS Programs, software, databases, and related
  31. documentation and technical data delivered to U.S. Government
  32. customers are "commercial computer software" or "commercial
  33. technical data" pursuant to the applicable Federal Acquisition
  34. Regulation and agency-specific supplemental regulations. As such,
  35. the use, duplication, disclosure, modification, and adaptation
  36. shall be subject to the restrictions and license terms set forth
  37. in the applicable Government contract, and, to the extent
  38. applicable by the terms of the Government contract, the additional
  39. rights set forth in FAR 52.227-19, Commercial Computer Software
  40. License (December 2007). Oracle USA, Inc., 500 Oracle Parkway,
  41. Redwood City, CA 94065.
  42. This software is developed for general use in a variety of
  43. information management applications. It is not developed or
  44. intended for use in any inherently dangerous applications,
  45. including applications which may create a risk of personal injury.
  46. If you use this software in dangerous applications, then you shall
  47. be responsible to take all appropriate fail-safe, backup,
  48. redundancy, and other measures to ensure the safe use of this
  49. software. Oracle Corporation and its affiliates disclaim any
  50. liability for any damages caused by use of this software in
  51. dangerous applications.
  52. Oracle is a registered trademark of Oracle Corporation and/or its
  53. affiliates. MySQL is a trademark of Oracle Corporation and/or its
  54. affiliates, and shall not be used without Oracle's express written
  55. authorization. Other names may be trademarks of their respective
  56. owners.
  57. This software and documentation may provide access to or
  58. information on content, products, and services from third parties.
  59. Oracle Corporation and its affiliates are not responsible for and
  60. expressly disclaim all warranties of any kind with respect to
  61. third-party content, products, and services. Oracle Corporation
  62. and its affiliates will not be responsible for any loss, costs, or
  63. damages incurred due to your access to or use of third-party
  64. content, products, or services.
  65. This documentation is in prerelease status and is intended for
  66. demonstration and preliminary use only. It may not be specific to
  67. the hardware on which you are using the software. Oracle
  68. Corporation and its affiliates are not responsible for and
  69. expressly disclaim all warranties of any kind with respect to this
  70. documentation and will not be responsible for any loss, costs, or
  71. damages incurred due to the use of this documentation.
  72. The information contained in this document is for informational
  73. sharing purposes only and should be considered in your capacity as
  74. a customer advisory board member or pursuant to your beta trial
  75. agreement only. It is not a commitment to deliver any material,
  76. code, or functionality, and should not be relied upon in making
  77. purchasing decisions. The development, release, and timing of any
  78. features or functionality described in this document remains at
  79. the sole discretion of Oracle.
  80. This document in any form, software or printed matter, contains
  81. proprietary information that is the exclusive property of Oracle.
  82. Your access to and use of this material is subject to the terms
  83. and conditions of your Oracle Software License and Service
  84. Agreement, which has been executed and with which you agree to
  85. comply. This document and information contained herein may not be
  86. disclosed, copied, reproduced, or distributed to anyone outside
  87. Oracle without prior written consent of Oracle or as specifically
  88. provided below. This document is not part of your license
  89. agreement nor can it be incorporated into any contractual
  90. agreement with Oracle or its subsidiaries or affiliates.
  91. This documentation is NOT distributed under a GPL license. Use of
  92. this documentation is subject to the following terms:
  93. You may create a printed copy of this documentation solely for
  94. your own personal use. Conversion to other formats is allowed as
  95. long as the actual content is not altered or edited in any way.
  96. You shall not publish or distribute this documentation in any form
  97. or on any media, except if you distribute the documentation in a
  98. manner similar to how Oracle disseminates it (that is,
  99. electronically for download on a Web site with the software) or on
  100. a CD-ROM or similar medium, provided however that the
  101. documentation is disseminated together with the software on the
  102. same medium. Any other use, such as any dissemination of printed
  103. copies or use of this documentation, in whole or in part, in
  104. another publication, requires the prior written consent from an
  105. authorized representative of Oracle. Oracle and/or its affiliates
  106. reserve any and all rights to this documentation not expressly
  107. granted above.
  108. For more information on the terms of this license, or for details
  109. on how the MySQL documentation is built and produced, please visit
  110. MySQL Contact & Questions (http://dev.mysql.com/contact/).
  111. For additional licensing information, including licenses for
  112. third-party libraries used by MySQL products, see "Preface and
  113. Legal Notices."
  114. For help with using MySQL, please visit either the MySQL Forums
  115. (http://forums.mysql.com) or MySQL Mailing Lists
  116. (http://lists.mysql.com) where you can discuss your issues with
  117. other MySQL users.
  118. For additional documentation on MySQL products, including
  119. translations of the documentation into other languages, and
  120. downloadable versions in variety of formats, including HTML and
  121. PDF formats, see the MySQL Documentation Library
  122. (http://dev.mysql.com/doc).
  123. Chapter 1. MySQL Connector/Python
  124. MySQL Connector/Python allows Python programs to access MySQL
  125. databases, using an API that is compliant with the Python DB API
  126. version 2.0 (http://www.python.org/dev/peps/pep-0249/). It is
  127. written in pure Python and does not have any dependencies except
  128. for the Python Standard Library (http://docs.python.org/library/).
  129. MySQL Connector/Python includes support for:
  130. * Almost all features provided by MySQL Server up to and
  131. including MySQL Server version 5.5.
  132. * Converting parameter values back and forth between Python and
  133. MySQL data types, for example Python datetime and MySQL
  134. DATETIME. You can turn automatic conversion on for
  135. convenience, or off for optimal performance.
  136. * All MySQL extensions to standard SQL syntax.
  137. * Protocol compression, which enables compressing the data
  138. stream between the client and server.
  139. * Connections using TCP/IP sockets and on Unix using Unix
  140. sockets.
  141. * Secure TCP/IP connections using SSL.
  142. * Self-contained driver. Connector/Python does not require the
  143. MySQL client library or any Python modules outside the
  144. standard library.
  145. MySQL Connector/Python supports from Python version 2.4 through
  146. 2.7, and Python 3.1 and later. Note that Connector/Python does not
  147. support the old MySQL Server authentication methods, which means
  148. that MySQL versions prior to 4.1 will not work.
  149. Chapter 2. Connector/Python Versions
  150. MySQL Connector/Python v1.0.x series went going through a series
  151. of beta releases, leading to the first generally available (GA)
  152. version 1.0.7. Any development releases prior to general
  153. availability are not supported now that the GA version is
  154. released.
  155. The following table summarizes the available Connector/Python
  156. versions:
  157. Table 2.1. Connector/Python Version Reference
  158. Connector/Python Version MySQL Server Versions Python Versions
  159. Support Status for Connector
  160. 1.0 5.6, 5.5 (5.1, 5.0, 4.1) 2.7, 2.6 (2.5, 2.4); 3.1 and later
  161. Recommended version
  162. Note
  163. MySQL server and Python versions within brackets are known to work
  164. with Connector/Python, but are not officially supported. Bugs
  165. might not get fixed for those versions.
  166. Chapter 3. Connector/Python Installation
  167. Connector/Python runs on any platform where Python is installed.
  168. Python comes pre-installed on almost any Linux distribution or
  169. UNIX-like system such as Apple Mac OS X and FreeBSD. On Microsoft
  170. Windows systems, you can install Python using the installer found
  171. on the Python Download website (http://python.org/download/).
  172. Connector/Python is a pure Python implementation of the MySQL
  173. Client/Server protocol, meaning it does not require any other
  174. MySQL client libraries or other components. It also has no
  175. third-party dependencies. If you need SSL support, verify that
  176. your Python installation has been compiled using the OpenSSL
  177. (http://www.openssl.org/) libraries.
  178. The installation of Connector/Python is similar on every platform
  179. and follows the standard Python Distribution Utilities
  180. (http://docs.python.org/install/index.html#install-index) or
  181. Distutils (http://docs.python.org/distutils/). Some platforms have
  182. specific packaging, for example RPM, and, when made available, the
  183. installation of these will be covered in this manual.
  184. Python terminology regarding distributions:
  185. * Source Distribution is a distribution that contains only
  186. source files and is generally platform independent.
  187. * Built Distribution can be regarded as a binary package. It
  188. contains both sources and platform-independent bytecode.
  189. 3.1. Installing Connector/Python Source Distribution on Linux, UNIX,
  190. or OS X
  191. On UNIX-like systems such as Linux distributions, Solaris, Apple
  192. Mac OS X, and FreeBSD, you can download Connector/Python as a tar
  193. archive from http://dev.mysql.com/downloads/connector/python/.
  194. To install Connector/Python from the .tar.gz file, download the
  195. latest version and follow these steps:
  196. shell> gunzip mysql-connector-python-1.0.6b1.tar.gz
  197. shell> tar xf mysql-connector-python-1.0.6b1.tar
  198. shell> cd mysql-connector-python-1.0.6b1
  199. shell> sudo python setup.py install
  200. On UNIX-like systems, Connector/Python gets installed in the
  201. default location /prefix/lib/pythonX.Y/site-packages/, where
  202. prefix is the location where Python was installed and X.Y is the
  203. version of Python. See How installation works
  204. (http://docs.python.org/install/index.html#how-installation-works)
  205. in the Python manual.
  206. If you are not sure where Connector/Python was installed, do the
  207. following to retrieve the location:
  208. shell> python
  209. >>> from distutils.sysconfig import get_python_lib
  210. >>> print get_python_lib() # Python v2.x
  211. /Library/Python/2.7/site-packages
  212. >>> print(get_python_lib()) # Python v3.x
  213. /Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-
  214. packages
  215. Note
  216. The above example shows the default installation location on Mac
  217. OS X 10.7.
  218. 3.2. Installing Connector/Python Source Distribution on Microsoft
  219. Windows
  220. On Microsoft Windows systems, you can download Connector/Python as
  221. a zip archive from
  222. http://dev.mysql.com/downloads/connector/python/.
  223. Make sure that the Python executable is available in the Windows
  224. %PATH% setting. For more information about installation and
  225. configuration of Python on Windows, see the section Using Python
  226. on Windows (http://docs.python.org/using/windows.html) in the
  227. Python documentation.
  228. To install Connector/Python from the .zip file, download the
  229. latest version and follow these steps:
  230. 1. Unpack the downloaded zip archive into a directory of your
  231. choice. For example, into the folder C:\mysql-connector\. Use
  232. the appropriate unzip command for your system, for example,
  233. unzip, pkunzip, and so on.
  234. 2. Start a console window (or a DOS window) and change to the
  235. folder where you unpacked the Connector/Python zip archive.
  236. shell> cd C:\mysql-connector\
  237. 3. Once inside the Connector/Python folder, do the following:
  238. shell> python setup.py install
  239. On Windows, Connector/Python gets installed in the default
  240. location C:\PythonX.Y\Lib\site-packages\ where X.Y is the Python
  241. version you used to install the connector.
  242. If you are not sure where Connector/Python ended up, do the
  243. following to retrieve the location where packages get installed:
  244. shell> python
  245. >>> from distutils.sysconfig import get_python_lib
  246. >>> print get_python_lib() # Python v2.x
  247. >>> print(get_python_lib()) # Python v3.x
  248. 3.3. Verifying Your Connector/Python Installation
  249. To test that your Connector/Python installation is working and is
  250. able to connect to a MySQL database server, you can run a very
  251. simple program where you substitute the login credentials and host
  252. information of the MySQL server. See Section 4.1, "Connecting to
  253. MySQL Using Connector/Python" for an example.
  254. Chapter 4. Connector/Python Coding Examples
  255. These coding examples illustrate how to develop Python
  256. applications and scripts which connect to a MySQL Server using
  257. MySQL Connector/Python.
  258. 4.1. Connecting to MySQL Using Connector/Python
  259. The connect() constructor is used for creating a connection to the
  260. MySQL server and returns a MySQLConnection object.
  261. The following example shows how to connect to the MySQL server:
  262. import mysql.connector
  263. cnx = mysql.connector.connect(user='scott', password='tiger',
  264. host='127.0.0.1',
  265. database='employees')
  266. cnx.close()
  267. See Chapter 6, "Connector/Python Connection Arguments" for all
  268. possible connection arguments.
  269. It is also possible to create connection objects using the
  270. connection.MySQLConnection() class. Both methods, using the
  271. connect() constructor, or the class directly, are valid and
  272. functionally equal, but using connector() is preferred and will be
  273. used in most examples in this manual.
  274. To handle connection errors, use the try statement and catch all
  275. errors using the errors.Error exception:
  276. import mysql.connector
  277. from mysql.connector import errorcode
  278. try:
  279. cnx = mysql.connector.connect(user='scott',
  280. database='testt')
  281. except mysql.connector.Error as err:
  282. if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
  283. print("Something is wrong your username or password")
  284. elif err.errno == errorcode.ER_BAD_DB_ERROR:
  285. print("Database does not exists")
  286. else:
  287. print(err)
  288. else:
  289. cnx.close()
  290. If you have lots of connection arguments, it's best to keep them
  291. in a dictionary and use the **-operator. Here is an example:
  292. import mysql.connector
  293. config = {
  294. 'user': 'scott',
  295. 'password': 'tiger',
  296. 'host': '127.0.0.1',
  297. 'database': 'employees',
  298. 'raise_on_warnings': True,
  299. }
  300. cnx = mysql.connector.connect(**config)
  301. cnx.close()
  302. 4.2. Creating Tables Using Connector/Python
  303. All DDL
  304. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_ddl)
  305. (Data Definition Language) statements are executed using a handle
  306. structure known as a cursor. The following examples show how to
  307. create the tables of the employees database. You will need them
  308. for the other examples.
  309. In a MySQL server, tables are very long-lived objects, and are
  310. often accessed by multiple applications written in different
  311. languages. You might typically work with tables that are already
  312. set up, rather than creating them within your own application.
  313. Avoid setting up and dropping tables over and over again, as that
  314. is an expensive operation. The exception is temporary tables
  315. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_tempora
  316. ry_table), which can be created and dropped quickly within an
  317. application.
  318. from __future__ import print_function
  319. import mysql.connector
  320. from mysql.connector import errorcode
  321. DB_NAME = 'employees'
  322. TABLES = {}
  323. TABLES['employees'] = (
  324. "CREATE TABLE `employees` ("
  325. " `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
  326. " `birth_date` date NOT NULL,"
  327. " `first_name` varchar(14) NOT NULL,"
  328. " `last_name` varchar(16) NOT NULL,"
  329. " `gender` enum('M','F') NOT NULL,"
  330. " `hire_date` date NOT NULL,"
  331. " PRIMARY KEY (`emp_no`)"
  332. ") ENGINE=InnoDB")
  333. TABLES['departments'] = (
  334. "CREATE TABLE `departments` ("
  335. " `dept_no` char(4) NOT NULL,"
  336. " `dept_name` varchar(40) NOT NULL,"
  337. " PRIMARY KEY (`dept_no`), UNIQUE KEY `dept_name` (`dept_name`)"
  338. ") ENGINE=InnoDB")
  339. TABLES['salaries'] = (
  340. "CREATE TABLE `salaries` ("
  341. " `emp_no` int(11) NOT NULL,"
  342. " `salary` int(11) NOT NULL,"
  343. " `from_date` date NOT NULL,"
  344. " `to_date` date NOT NULL,"
  345. " PRIMARY KEY (`emp_no`,`from_date`), KEY `emp_no` (`emp_no`),"
  346. " CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`emp_no`) "
  347. " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
  348. ") ENGINE=InnoDB")
  349. TABLES['dept_emp'] = (
  350. "CREATE TABLE `dept_emp` ("
  351. " `emp_no` int(11) NOT NULL,"
  352. " `dept_no` char(4) NOT NULL,"
  353. " `from_date` date NOT NULL,"
  354. " `to_date` date NOT NULL,"
  355. " PRIMARY KEY (`emp_no`,`dept_no`), KEY `emp_no` (`emp_no`),"
  356. " KEY `dept_no` (`dept_no`),"
  357. " CONSTRAINT `dept_emp_ibfk_1` FOREIGN KEY (`emp_no`) "
  358. " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
  359. " CONSTRAINT `dept_emp_ibfk_2` FOREIGN KEY (`dept_no`) "
  360. " REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
  361. ") ENGINE=InnoDB")
  362. TABLES['dept_manager'] = (
  363. " CREATE TABLE `dept_manager` ("
  364. " `dept_no` char(4) NOT NULL,"
  365. " `emp_no` int(11) NOT NULL,"
  366. " `from_date` date NOT NULL,"
  367. " `to_date` date NOT NULL,"
  368. " PRIMARY KEY (`emp_no`,`dept_no`),"
  369. " KEY `emp_no` (`emp_no`),"
  370. " KEY `dept_no` (`dept_no`),"
  371. " CONSTRAINT `dept_manager_ibfk_1` FOREIGN KEY (`emp_no`) "
  372. " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
  373. " CONSTRAINT `dept_manager_ibfk_2` FOREIGN KEY (`dept_no`) "
  374. " REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
  375. ") ENGINE=InnoDB")
  376. TABLES['titles'] = (
  377. "CREATE TABLE `titles` ("
  378. " `emp_no` int(11) NOT NULL,"
  379. " `title` varchar(50) NOT NULL,"
  380. " `from_date` date NOT NULL,"
  381. " `to_date` date DEFAULT NULL,"
  382. " PRIMARY KEY (`emp_no`,`title`,`from_date`), KEY `emp_no` (`emp
  383. _no`),"
  384. " CONSTRAINT `titles_ibfk_1` FOREIGN KEY (`emp_no`)"
  385. " REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
  386. ") ENGINE=InnoDB")
  387. The above code shows how we are storing the CREATE statements in a
  388. Python dictionary called TABLES. We also define the database in a
  389. global variable called DB_NAME, which allows you to easily use a
  390. different schema.
  391. cnx = mysql.connector.connect(user='scott')
  392. cursor = cnx.cursor()
  393. A single MySQL server can contain multiple databases
  394. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_databas
  395. e). Typically, you specify the database to switch to when
  396. connecting to the MySQL server. This example does not connect to
  397. the database upon connection, so that it can make sure the
  398. database exists, and create it if not.
  399. def create_database(cursor):
  400. try:
  401. cursor.execute(
  402. "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(
  403. DB_NAME))
  404. except mysql.connector.Error as err:
  405. print("Failed creating database: {}".format(err))
  406. exit(1)
  407. try:
  408. cnx.database = DB_NAME
  409. except mysql.connector.Error as err:
  410. if err.errno == errorcode.ER_BAD_DB_ERROR:
  411. create_database(cursor)
  412. cnx.database = DB_NAME
  413. else:
  414. print(err)
  415. exit(1)
  416. We first try to change to a particular database using the database
  417. property of the connection object cnx. If there is an error, we
  418. examine the error number to check if the database does not exist.
  419. If so, we call the create_database function to create it for us.
  420. On any other error, the application exits and displays the error
  421. message.
  422. for name, ddl in TABLES.iteritems():
  423. try:
  424. print("Creating table {}: ".format(name), end='')
  425. cursor.execute(ddl)
  426. except mysql.connector.Error as err:
  427. if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
  428. print("already exists.")
  429. else:
  430. print(err.errmsg)
  431. else:
  432. print("OK")
  433. cursor.close()
  434. cnx.close()
  435. After we succesfully created or changed to the target database, we
  436. create the tables by iterating over the items of the TABLES
  437. dictionary.
  438. We handle the error when the table already exists by simply
  439. notifying the user that it was already there. Other errors are
  440. printed, but we simply continue creating tables. (We show how to
  441. handle the "table already exists" condition for illustration
  442. purposes. In a real application, we would typically avoid the
  443. error condition entirely by using the IF NOT EXISTS clause of the
  444. CREATE TABLE
  445. (http://dev.mysql.com/doc/refman/5.5/en/create-table.html)
  446. statement.)
  447. The output would be something like this:
  448. Creating table employees: already exists.
  449. Creating table salaries: already exists.
  450. Creating table titles: OK
  451. Creating table departments: already exists.
  452. Creating table dept_manager: already exists.
  453. Creating table dept_emp: already exists.
  454. To populate the employees tables, use the dump files of the
  455. Employee Sample Database
  456. (http://dev.mysql.com/doc/employee/en/index.html). Note that you
  457. only need the data dump files that you will find in an archive
  458. named like employees_db-dump-files-1.0.5.tar.bz2. After
  459. downloading the dump files, do the following from the command
  460. line, adding connection options to the mysql commands if
  461. necessary:
  462. shell> tar xzf employees_db-dump-files-1.0.5.tar.bz2
  463. shell> cd employees_db
  464. shell> mysql employees < load_employees.dump
  465. shell> mysql employees < load_titles.dump
  466. shell> mysql employees < load_departments.dump
  467. shell> mysql employees < load_salaries.dump
  468. shell> mysql employees < load_dept_emp.dump
  469. shell> mysql employees < load_dept_manager.dump
  470. 4.3. Inserting Data Using Connector/Python
  471. Inserting or updating data is also done using the handler
  472. structure known as a cursor. When you use a transactional storage
  473. engine such as InnoDB (which is the default in MySQL 5.5 and
  474. later), you must commit
  475. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_commit)
  476. the data after a sequence of INSERT
  477. (http://dev.mysql.com/doc/refman/5.5/en/insert.html), DELETE
  478. (http://dev.mysql.com/doc/refman/5.5/en/delete.html), and UPDATE
  479. (http://dev.mysql.com/doc/refman/5.5/en/update.html) statements.
  480. In this example we show how to insert new data. The second INSERT
  481. (http://dev.mysql.com/doc/refman/5.5/en/insert.html) depends on
  482. the value of the newly created primary key
  483. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_primary
  484. _key) of the first. We are also demonstrating how to use extended
  485. formats. The task is to add a new employee starting to work
  486. tomorrow with a salary set to 50000.
  487. Note
  488. The following example uses tables created in the example Section
  489. 4.2, "Creating Tables Using Connector/Python." The AUTO_INCREMENT
  490. column option for the primary key of the employees table is
  491. important to ensure reliable, easily searchable data.
  492. from __future__ import print_function
  493. from datetime import date, datetime, timedelta
  494. import mysql.connector
  495. cnx = mysql.connector.connect(user='scott', database='employees')
  496. cursor = cnx.cursor()
  497. tomorrow = datetime.now().date() + timedelta(days=1)
  498. add_employee = ("INSERT INTO employees "
  499. "(first_name, last_name, hire_date, gender, birth_date
  500. ) "
  501. "VALUES (%s, %s, %s, %s, %s)")
  502. add_salary = ("INSERT INTO salaries "
  503. "(emp_no, salary, from_date, to_date) "
  504. "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_da
  505. te)s)")
  506. data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6,
  507. 14))
  508. # Insert new employee
  509. cursor.execute(add_employee, data_employee)
  510. emp_no = cursor.lastrowid
  511. # Insert salary information
  512. data_salary = {
  513. 'emp_no': emp_no,
  514. 'salary': 50000,
  515. 'from_date': tomorrow,
  516. 'to_date': date(9999, 1, 1),
  517. }
  518. cursor.execute(add_salary, data_salary)
  519. # Make sure data is committed to the database
  520. cnx.commit()
  521. cursor.close()
  522. cnx.close()
  523. We first open a connection to the MySQL server and store the
  524. connection object in the variable cnx. We then create a new
  525. cursor, by default a MySQLCursor object, using the connection's
  526. cursor() method.
  527. We could calculate tomorrow by calling a database function, but
  528. for clarity we do it in Python using the datetime module.
  529. Both INSERT statements are stored in the variables called
  530. add_employee and add_salary. Note that the second INSERT statement
  531. uses extended Python format codes.
  532. The information of the new employee is stored in the tuple
  533. data_employee. The query to insert the new employee is executed
  534. and we retrieve the newly inserted value for the column emp_no
  535. using the lastrowid property of the cursor object.
  536. Next, we insert the new salary for the new employee. We are using
  537. the emp_no variable in the directory holding the data. This
  538. directory is passed to the execute() method of the cursor object.
  539. Since by default Connector/Python turns autocommit
  540. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_autocom
  541. mit) off, and MySQL 5.5 and later uses transactional InnoDB tables
  542. by default, it is necessary to commit your changes using the
  543. connection's commit() method. You could also roll back
  544. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_rollbac
  545. k) using the rollback() method.
  546. 4.4. Querying Data Using Connector/Python
  547. The following example shows how to query
  548. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_query)
  549. data using a cursor created using the connection's cursor()
  550. method. The data returned is formatted and printed on the console.
  551. The task is to select all employees hired in the year 1999 and
  552. print their names with their hire date to the console.
  553. import datetime
  554. import mysql.connector
  555. cnx = mysql.connector.connect(user='scott', database='employees')
  556. cursor = cnx.cursor()
  557. query = ("SELECT first_name, last_name, hire_date FROM employees "
  558. "WHERE hire_date BETWEEN %s AND %s")
  559. hire_start = datetime.date(1999, 1, 1)
  560. hire_end = datetime.date(1999, 12, 31)
  561. cursor.execute(query, (hire_start, hire_end))
  562. for (first_name, last_name, hire_date) in cursor:
  563. print("{}, {} was hired on {:%d %b %Y}".format(
  564. last_name, first_name, hire_date))
  565. cursor.close()
  566. cnx.close()
  567. We first open a connection to the MySQL server and store the
  568. connection object in the variable cnx. We then create a new
  569. cursor, by default a MySQLCursor object, using the connection's
  570. cursor() method.
  571. In the preceding example, we store the SELECT statement in the
  572. variable query. Note that we are using unquoted %s-markers where
  573. dates should have been. Connector/Python converts hire_start and
  574. hire_end from Python types to a data type that MySQL understands
  575. and adds the required quotes. In this case, it replaces the first
  576. %s with '1999-01-01', and the second with '1999-12-31'.
  577. We then execute the operation stored in the query variable using
  578. the execute() method. The data used to replace the %s-markers in
  579. the query is passed as a tuple: (hire_start, hire_end).
  580. After executing the query, the MySQL server is ready to send the
  581. data. The result set could be zero rows, one row, or 100 million
  582. rows. Depending on the expected volume, you can use different
  583. techniques to process this result set. In this example, we use the
  584. cursor object as an iterator. The first column in the row will be
  585. stored in the variable first_name, the second in last_name, and
  586. the third in hire_date.
  587. We print the result, formatting the output using Python's built-in
  588. format() function. Note that hire_date was converted automatically
  589. by Connector/Python to a Python datetime.date object. This means
  590. that we can easily format the date in a more human-readable form.
  591. The output should be something like this:
  592. ..
  593. Wilharm, LiMin was hired on 16 Dec 1999
  594. Wielonsky, Lalit was hired on 16 Dec 1999
  595. Kamble, Dannz was hired on 18 Dec 1999
  596. DuBourdieux, Zhongwei was hired on 19 Dec 1999
  597. Fujisawa, Rosita was hired on 20 Dec 1999
  598. ..
  599. Chapter 5. Connector/Python Tutorials
  600. These tutorials illustrate how to develop Python applications and
  601. scripts that connect to a MySQL database server using MySQL
  602. Connector/Python.
  603. 5.1. Tutorial: Raise employee's salary using a buffering cursor
  604. The following example script will give a long-overdue raise
  605. effective tomorrow to all employees who joined in the year 2000
  606. and are still with the company.
  607. We are using buffered cursors to iterate through the selected
  608. employees. This way we do not have to fetch the rows in a new
  609. variables, but can instead use the cursor as an iterator.
  610. Note that the script is an example; there are other ways of doing
  611. this simple task.
  612. from __future__ import print_function
  613. from decimal import Decimal
  614. from datetime import datetime, date, timedelta
  615. import mysql.connector
  616. # Connect with the MySQL Server
  617. cnx = mysql.connector.connect(user='scott', database='employees')
  618. # Get two buffered cursors
  619. curA = cnx.cursor(buffered=True)
  620. curB = cnx.cursor(buffered=True)
  621. # Query to get employees who joined in a period defined by two dates
  622. query = (
  623. "SELECT s.emp_no, salary, from_date, to_date FROM employees AS e "
  624. "LEFT JOIN salaries AS s USING (emp_no) "
  625. "WHERE to_date = DATE('9999-01-01')"
  626. "AND e.hire_date BETWEEN DATE(%s) AND DATE(%s)")
  627. # UPDATE and INSERT statements for the old and new salary
  628. update_old_salary = (
  629. "UPDATE salaries SET to_date = %s "
  630. "WHERE emp_no = %s AND from_date = %s")
  631. insert_new_salary = (
  632. "INSERT INTO salaries (emp_no, from_date, to_date, salary) "
  633. "VALUES (%s, %s, %s, %s)")
  634. # Select the employes getting a raise
  635. curA.execute(query, (date(2000, 1, 1), date(2001, 1, 1)))
  636. # Iterate through the result of curA
  637. for (emp_no, salary, from_date, to_date) in curA:
  638. # Update the old and insert the new salary
  639. new_salary = int(round(salary * Decimal('1.15')))
  640. curB.execute(update_old_salary, (tomorrow, emp_no, from_date))
  641. curB.execute(insert_new_salary,
  642. (emp_no, tomorrow, date(9999, 1, 1,), new_salary))
  643. # Commit the changes
  644. cnx.commit()
  645. cnx.close()
  646. Chapter 6. Connector/Python Connection Arguments
  647. The following lists the arguments which can be used to initiate a
  648. connection with the MySQL server using either:
  649. * Function mysql.connector.connect()
  650. * Class mysql.connector.MySQLConnection()
  651. Table 6.1. Connection Arguments for Connector/Python
  652. Argument Name Default Description
  653. user (username*) The username used to authenticate with the
  654. MySQL Server.
  655. password (passwd*) The password to authenticate the user with
  656. the MySQL Server.
  657. database (db*) Database name to use when connecting with the
  658. MySQL Server.
  659. host 127.0.0.1 Hostname or IP address of the MySQL Server.
  660. port 3306 TCP/IP port of the MySQL Server. Must be an integer.
  661. unix_socket The location of the Unix socket file.
  662. use_unicode True Whether to use Unicode or not.
  663. charset utf8 Which MySQL character set to use.
  664. collation utf8_general_ci Which MySQL collation to use.
  665. autocommit False Whether to autocommit
  666. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_autocom
  667. mit) transactions.
  668. time_zone Set the time_zone session variable at connection.
  669. sql_mode Set the sql_mode session variable at connection.
  670. get_warnings False Whether to fetch warnings.
  671. raise_on_warnings False Whether to raise an exception on warnings.
  672. connection_timeout (connect_timeout*) Timeout for the TCP and
  673. Unix socket connections.
  674. client_flags MySQL client flags.
  675. buffered False Whether cursor object fetches the result
  676. immediately after executing query.
  677. raw False Whether MySQL results are returned as-is, rather than
  678. converted to Python types.
  679. ssl_ca File containing the SSL certificate authority.
  680. ssl_cert File containing the SSL certificate file.
  681. ssl_key File containing the SSL key.
  682. dsn Not supported (raises NotSupportedError when used).
  683. * Synonymous argument name, available only for compatibility with
  684. other Python MySQL drivers. Oracle recommends not to use these
  685. alternative names.
  686. Authentication with MySQL will use username and password. Note
  687. that MySQL Connector/Python does not support the old, insecure
  688. password protocols of MySQL versions prior to 4.1.
  689. When the database parameter is given, the current database is set
  690. to the given value. To later change the database, execute the
  691. MySQL USE command or set the database property of the
  692. MySQLConnection instance.
  693. By default, Connector/Python tries to connect to a MySQL server
  694. running on localhost using TCP/IP. The host argument defaults to
  695. IP address 127.0.0.1 and port to 3306. Unix sockets are supported
  696. by setting unix_socket. Named pipes on the Windows platform are
  697. not supported.
  698. Strings coming from MySQL are by default returned as Python
  699. Unicode literals. To change this behavior, set use_unicode to
  700. False. You can change the character setting for the client
  701. connection through the charset argument. To change the character
  702. set after connecting to MySQL, set the charset property of the
  703. MySQLConnection instance. This technique is preferred over using
  704. the MySQL SET NAMES statement directly. Similar to the charset
  705. property, you can set the collation for the current MySQL session.
  706. Transactions are not automatically committed; call the commit()
  707. method of the MySQLConnection instance within your application
  708. after doing a set of related insert, update, and delete
  709. operations. For data consistency and high throughput for write
  710. operations, it is best to leave the autocommit configuration
  711. option turned off when using InnoDB or other transactional tables.
  712. The time zone can be set per connection using the time_zone
  713. argument. This is useful if the MySQL server is set, for example,
  714. to UTC and TIMESTAMP values should be returned by MySQL converted
  715. to the PST time zone.
  716. MySQL supports so called SQL Modes. which will change the behavior
  717. of the server globally or per connection. For example, to have
  718. warnings raised as errors, set sql_mode to TRADITIONAL. For more
  719. information, see Server SQL Modes
  720. (http://dev.mysql.com/doc/refman/5.5/en/server-sql-mode.html).
  721. Warnings generated by queries are fetched automatically when
  722. get_warnings is set to True. You can also immediately raise an
  723. exception by setting raise_on_warnings to True. Consider using the
  724. MySQL sql_mode
  725. (http://dev.mysql.com/doc/refman/5.5/en/server-sql-mode.html)
  726. setting for turning warnings into errors.
  727. To set a timeout value for connections, use connection_timeout.
  728. MySQL uses client flags
  729. (http://dev.mysql.com/doc/refman/5.5/en/mysql-real-connect.html)
  730. to enable or disable features. Using the client_flags argument,
  731. you have control of what is set. To find out what flags are
  732. available, use the following:
  733. from mysql.connector.constants import ClientFlag
  734. print '\n'.join(ClientFlag.get_full_info())
  735. If client_flags is not specified (that is, it is zero), defaults
  736. are used for MySQL v4.1 and later. If you specify an integer
  737. greater than 0, make sure all flags are set. A better way to set
  738. and unset flags is to use a list. For example, to set FOUND_ROWS,
  739. but disable the default LONG_FLAG:
  740. flags = [ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG]
  741. mysql.connector.connect(client_flags=flags)
  742. By default, MySQL Connector/Python does not buffer or pre-fetch
  743. results. This means that after a query is executed, your program
  744. is responsible of fetching the data. This avoids using excessive
  745. memory when queries return large result sets. If you know that the
  746. result set is small enough to handle all at once, fetching the
  747. results immediately by setting buffered to True. It is also
  748. possible to set this per cursor (see cursor manual).
  749. MySQL types will be converted automatically to Python types. For
  750. example, a DATETIME column becomes a datetime.datetime
  751. (http://docs.python.org/library/datetime.html#datetime.datetime)
  752. object. When conversion should be done differently, for example to
  753. get better performance, set raw to True.
  754. Using SSL connections is possible when your Python installation
  755. supports SSL (http://docs.python.org/library/ssl.html), that is,
  756. when it is compiled against the OpenSSL libraries. When you
  757. provide the arguments ssl_ca, ssl_key and ssl_cert, the connection
  758. switches to SSL. You can use this in combination with the
  759. compressed argument set to True.
  760. passwd, db and connect_timeout are valid for compatibility with
  761. other MySQL interfaces and are respectively the same as password,
  762. database and connection_timeout. The latter take precedence. Data
  763. source name syntax or dsn is not used; if specified, it raises a
  764. NotSupportedError exception.
  765. Chapter 7. Connector/Python API Reference
  766. This section contains the public API reference of
  767. Connector/Python. Although valid for both Python 2 and Python 3,
  768. examples should be considered working for Python 2.7, and Python
  769. 3.1 and greater.
  770. The following overview shows the mysql.connector package with its
  771. modules. Currently, only the most useful modules, classes and
  772. functions for end users are documented.
  773. mysql.connector
  774. errorcode
  775. errors
  776. connection
  777. constants
  778. conversion
  779. cursor
  780. dbapi
  781. locales
  782. eng
  783. client_error
  784. protocol
  785. utils
  786. 7.1. Errors and Exceptions
  787. The mysql.connector.errors module defines exception classes for
  788. errors and warnings raised by MySQL Connector/Python. Most classes
  789. defined in this module are available when you import
  790. mysql.connector.
  791. The exception classes defined in this module follow mostly the
  792. Python Database Specification v2.0 (PEP-249). For some MySQL
  793. client or server errors it is not always clear which exception to
  794. raise. It is good to discuss whether an error should be
  795. reclassified by opening a bug report.
  796. MySQL Server errors are mapped with Python exception based on
  797. their SQLState (see Server Error Codes and Messages
  798. (http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
  799. )). The following list shows the SQLState classes and the
  800. exception Connector/Python will raise. It is, however, possible to
  801. redefine which exception is raised for each server error. Note
  802. that the default exception is DatabaseError.
  803. * 02: DataError
  804. * 07: DatabaseError
  805. * 08: OperationalError
  806. * 0A: NotSupportedError
  807. * 21: DataError
  808. * 22: DataError
  809. * 23: IntegrityError
  810. * 24: ProgrammingError
  811. * 25: ProgrammingError
  812. * 26: ProgrammingError
  813. * 27: ProgrammingError
  814. * 28: ProgrammingError
  815. * 2A: ProgrammingError
  816. * 2B: DatabaseError
  817. * 2C: ProgrammingError
  818. * 2D: DatabaseError
  819. * 2E: DatabaseError
  820. * 33: DatabaseError
  821. * 34: ProgrammingError
  822. * 35: ProgrammingError
  823. * 37: ProgrammingError
  824. * 3C: ProgrammingError
  825. * 3D: ProgrammingError
  826. * 3F: ProgrammingError
  827. * 40: InternalError
  828. * 42: ProgrammingError
  829. * 44: InternalError
  830. * HZ: OperationalError
  831. * XA: IntegrityError
  832. * 0K: OperationalError
  833. * HY: DatabaseError
  834. 7.1.1. Module errorcode
  835. This module contains both MySQL server and client error codes
  836. defined as module attributes with the error number as value. Using
  837. error codes instead of error numbers could make reading the source
  838. code a bit easier.
  839. >>> from mysql.connector import errorcode
  840. >>> errorcode.ER_BAD_TABLE_ERROR
  841. 1051
  842. See Server Error Codes and Messages
  843. (http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
  844. ) and Client Error Codes and Messages
  845. (http://dev.mysql.com/doc/refman/5.5/en/error-messages-client.html
  846. ).
  847. 7.1.2. Exception errors.Error
  848. This exception is the base class for all other exceptions in the
  849. errors module. It can be used to catch all errors in a single
  850. except statement.
  851. The following example shows how we could catch syntax errors:
  852. import mysql.connector
  853. try:
  854. cnx = mysql.connector.connect(user='scott', database='employees')
  855. cursor = cnx.cursor()
  856. cursor.execute("SELECT * FORM employees") # Syntax error in query
  857. cnx.close()
  858. except mysql.connector.Error as err:
  859. print("Something went wrong: {}".format(err))
  860. Initializing the exception supports a few optional arguments,
  861. namely msg, errno, values and sqlstate. All of them are optional
  862. and default to None. errors.Error isinternally used by
  863. Connector/Python to raise MySQL client and server errors and
  864. should not be used by your application to raise exceptions.
  865. The following examples show the result when using no or a
  866. combination of the arguments:
  867. >>> from mysql.connector.errors import Error
  868. >>> str(Error())
  869. 'Unknown error'
  870. >>> str(Error("Oops! There was an error."))
  871. 'Oops! There was an error.'
  872. >>> str(Error(errno=2006))
  873. '2006: MySQL server has gone away'
  874. >>> str(Error(errno=2002, values=('/tmp/mysql.sock', 2)))
  875. "2002: Can't connect to local MySQL server through socket '/tmp/mysql
  876. .sock' (2)"
  877. >>> str(Error(errno=1146, sqlstate='42S02', msg="Table 'test.spam' do
  878. esn't exist"))
  879. "1146 (42S02): Table 'test.spam' doesn't exist"
  880. The example which uses error number 1146 is used when
  881. Connector/Python receives an error packet from the MySQL Server.
  882. The information is parsed and passed to the Error exception as
  883. shown.
  884. Each exception subclassing from Error can be initialized using the
  885. above mentioned arguments. Additionally, each instance has the
  886. attributes errno, msg and sqlstate which can be used in your code.
  887. The following example shows how to handle errors when dropping a
  888. table which does not exists (when you do not want to use the IF
  889. EXISTS clause):
  890. import mysql.connector
  891. from mysql.connector import errorcode
  892. cnx = mysql.connector.connect(user='scott', database='test')
  893. try:
  894. cur.execute("DROP TABLE spam")
  895. except mysql.connector.Error as err:
  896. if err.errno == errorcode.ER_BAD_TABLE_ERROR:
  897. print("Creating table spam")
  898. else:
  899. raise
  900. errors.Error is a subclass of the Python StandardError.
  901. 7.1.3. Exception errors.Warning
  902. This exception is used for reporting important warnings, however,
  903. Connector/Python does not use it. It is included to be compliant
  904. with the Python Database Specification v2.0 (PEP-249).
  905. Consider using either more strict Server SQL Modes
  906. (http://dev.mysql.com/doc/refman/5.5/en/server-sql-mode.html) or
  907. the raise_on_warnings connection argument to make Connector/Python
  908. raise errors when your queries produce warnings.
  909. errors.Warning is a subclass of the Python StandardError.
  910. 7.1.4. Exception errors.InterfaceError
  911. This exception is raised for errors originating from
  912. Connector/Python itself, not related to the MySQL server.
  913. errors.InterfaceError is a subclass of errors.Error.
  914. 7.1.5. Exception errors.DatabaseError
  915. This exception is the default for any MySQL error which does not
  916. fit the other exceptions.
  917. errors.DatabaseError is a subclass of errors.Error.
  918. 7.1.6. Exception errors.InternalError
  919. This exception is raised when the MySQL server encounters an
  920. internal error, for example, when a deadlock occurred.
  921. errors.InternalError is a subclass of errors.DatabaseError.
  922. 7.1.7. Exception errors.OperationalError
  923. This exception is raised for errors which are related to MySQL's
  924. operations. For example, to many connections, a hostname could not
  925. be resolved, bad handshake, server is shutting down, communication
  926. errors, and so on.
  927. errors.OperationalError is a subclass of errors.DatabaseError.
  928. 7.1.8. Exception errors.ProgrammingError
  929. This exception is raised on programming errors, for example when
  930. you have a syntax error in your SQL or a table was not found.
  931. The following example shows how to handle syntax errors:
  932. try:
  933. cursor.execute("CREATE DESK t1 (id int, PRIMARY KEY (id))")
  934. except mysql.connector.ProgrammingError as err:
  935. if err.errno == errorcode.ER_SYNTAX_ERROR:
  936. print("Check your syntax!")
  937. else:
  938. print("Error: {}".format(err))
  939. errors.ProgrammingError is a subclass of errors.DatabaseError.
  940. 7.1.9. Exception errors.IntegrityError
  941. This exception is raised when the relational integrity of the data
  942. is affected. For example, a duplicate key was inserted or a
  943. foreign key constraint would fail.
  944. The following example shows a duplicate key error raised as
  945. IntegrityError:
  946. cursor.execute("CREATE TABLE t1 (id int, PRIMARY KEY (id))")
  947. try:
  948. cursor.execute("INSERT INTO t1 (id) VALUES (1)")
  949. cursor.execute("INSERT INTO t1 (id) VALUES (1)")
  950. except mysql.connector.IntegrityError as err:
  951. print("Error: {}".format(err))
  952. errors.IntegrityError is a subclass of errors.DatabaseError.
  953. 7.1.10. Exception errors.DataError
  954. This exception is raised when there were problems with the data.
  955. Examples are a column set to NULL when it can not, out of range
  956. values for a column, division by zero, column count does not match
  957. value count, and so on.
  958. errors.DataError is a subclass of errors.DatabaseError.
  959. 7.1.11. Exception errors.NotSupportedError
  960. This exception is raised is case some feature was used but not
  961. supported by the version of MySQL which returned the error. It is
  962. also raised when using functions or statements which are not
  963. supported by stored routines.
  964. errors.NotSupportedError is a subclass of errors.DatabaseError.
  965. 7.1.12. Function errors.custom_error_exception(error=None,
  966. exception=None)
  967. This function defines custom exceptions for MySQL server errors
  968. and returns current customizations.
  969. If error is a MySQL Server error number, then you have to pass
  970. also the exception class. The error argument can also be a
  971. dictionary in which case the key is the server error number, and
  972. value the class of the exception to be raised.
  973. To reset the customizations, simply supply an empty dictionary.
  974. import mysql.connector
  975. from mysql.connector import errorcode
  976. # Server error 1028 should raise a DatabaseError
  977. mysql.connector.custom_error_exception(1028, mysql.connector.Database
  978. Error)
  979. # Or using a dictionary:
  980. mysql.connector.custom_error_exception({
  981. 1028: mysql.connector.DatabaseError,
  982. 1029: mysql.connector.OperationalError,
  983. })
  984. # To reset, pass an empty dictionary:
  985. mysql.connector.custom_error_exception({})
  986. 7.2. Class connection.MySQLConnection
  987. The MySQLConnection class is used to open and manage a connection
  988. to a MySQL server. It also used to send commands and SQL queries
  989. and read result.
  990. 7.2.1. Constructor connection.MySQLConnection(**kwargs)
  991. The MySQLConnection constructor initializes the attributes and
  992. when at least one argument is passed, it tries to connect with the
  993. MySQL server.
  994. For a complete list or arguments, see Chapter 6, "Connector/Python
  995. Connection Arguments."
  996. 7.2.2. Method MySQLConnection.close()
  997. See disconnect().
  998. Returns a tuple.
  999. 7.2.3. Method MySQLConnection.config(**kwargs)
  1000. Allows to configure a MySQLConnection instance after it was
  1001. instantiated. See Chapter 6, "Connector/Python Connection
  1002. Arguments" for a complete list of possible arguments.
  1003. You could use the config() method to change, for example, the
  1004. username and call reconnect().
  1005. cnx = MySQLConnection(user='joe', database='test')
  1006. # Connected as 'joe'
  1007. cnx.config(user='jane')
  1008. cnx.reconnect()
  1009. # Now connected as 'jane'
  1010. 7.2.4. Method MySQLConnection.connect(**kwargs)
  1011. This method sets up the connection to the MySQL server. If no
  1012. arguments are given, it uses the already configured or default
  1013. values. See Chapter 6, "Connector/Python Connection Arguments" for
  1014. a complete list of possible arguments.
  1015. 7.2.5. Method MySQLConnection.commit()
  1016. This method sends the COMMIT command to the MySQL server,
  1017. committing the current transaction. Since by default,
  1018. Connector/Python does not auto commit, it is important to call
  1019. this method after every transaction which updates data for tables
  1020. using transactional storage engines.
  1021. See the rollback() method for rolling back transactions.
  1022. >>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)",
  1023. ('Jane'))
  1024. >>> cnx.commit()
  1025. 7.2.6. Method MySQLConnection.cursor(buffered=None, raw=None,
  1026. cursor_class=None)
  1027. This method returns a MySQLCursor() object, or a subclass of it
  1028. depending the passed arguments.
  1029. When buffered is True, the cursor will fetch all rows after the
  1030. operation is executed. This is useful when queries return small
  1031. result sets. Setting raw will skip the conversion from MySQL data
  1032. types to Python types when fetching rows. Raw is usually used when
  1033. you want to have more performance and/or you want to do the
  1034. conversion yourself.
  1035. The cursor_class argument can be used to pass a class to use for
  1036. instantiating a new cursor. It has to be a subclass of
  1037. cursor.CursorBase.
  1038. The returned object depends on the combination of the buffered and
  1039. raw arguments.
  1040. * If not buffered and not raw: cursor.MySQLCursor
  1041. * If buffered and not raw: cursor.MySQLCursorBuffered
  1042. * If buffered and raw: cursor.MySQLCursorBufferedRaw
  1043. * If not buffered and raw: cursor.MySQLCursorRaw
  1044. Returns a CursorBase instance.
  1045. 7.2.7. Method MySQLConnection.cmd_change_user(username='',
  1046. password='', database='', charset=33)
  1047. Changes the user using username and password. It also causes the
  1048. specified database to become the default (current) database. It is
  1049. also possible to change the character set using the charset
  1050. argument.
  1051. Returns a dictionary containing the OK packet information.
  1052. 7.2.8. Method MySQLConnection.cmd_debug()
  1053. Instructs the server to write some debug information to the log.
  1054. For this to work, the connected user must have the SUPER
  1055. privilege.
  1056. Returns a dictionary containing the OK packet information.
  1057. 7.2.9. Method MySQLConnection.cmd_init_db(database)
  1058. This method makes specified database the default (current)
  1059. database. In subsequent queries, this database is the default for
  1060. table references that do not include an explicit database
  1061. specifier.
  1062. Returns a dictionary containing the OK packet information.
  1063. 7.2.10. Method MySQLConnection.cmd_ping()
  1064. Checks whether the connection to the server is working.
  1065. This method is not to be used directly. Use ping() or
  1066. is_connected() instead.
  1067. Returns a dictionary containing the OK packet information.
  1068. 7.2.11. Method MySQLConnection.cmd_process_info()
  1069. This method raises the NotSupportedError exception. Instead, use
  1070. the SHOW PROCESSLIST statement or query the tables found in the
  1071. database INFORMATION_SCHEMA.
  1072. 7.2.12. Method MySQLConnection.cmd_process_kill(mysql_pid)
  1073. Asks the server to kill the thread specified by mysql_pid.
  1074. Although still available, it's better to use the SQL KILL command.
  1075. Returns a dictionary containing the OK packet information.
  1076. The following two lines do the same:
  1077. >>> cnx.cmd_process_kill(123)
  1078. >>> cnx.cmd_query('KILL 123')
  1079. 7.2.13. Method MySQLConnection.cmd_quit()
  1080. This method sends the QUIT command to the MySQL server, closing
  1081. the current connection. Since there is no response from the MySQL,
  1082. the packet that was sent is returned.
  1083. 7.2.14. Method MySQLConnection.cmd_query(statement)
  1084. This method sends the given statement to the MySQL server and
  1085. returns a result. If you need to send multiple statements, you
  1086. have to use the cmd_query_iter() method.
  1087. The returned dictionary contains information depending on what
  1088. kind of query was executed. If the query is a SELECT
  1089. (http://dev.mysql.com/doc/refman/5.5/en/select.html) statement,
  1090. the result contains information about columns. Other statements
  1091. return a dictionary containing OK or EOF packet information.
  1092. Errors received from the MySQL server are raised as exceptions. An
  1093. InterfaceError is raised when multiple results are found.
  1094. Returns a dictionary.
  1095. 7.2.15. Method MySQLConnection.cmd_query_iter(statement)
  1096. Similar to the cmd_query() method, but returns a generator object
  1097. to iterate through results. Use cmd_query_iter() when sending
  1098. multiple statements, and separate the statements with semicolons.
  1099. The following example shows how to iterate through the results
  1100. after sending multiple statements:
  1101. statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
  1102. for result in cnx.cmd_query(statement, iterate=True):
  1103. if 'columns' in result:
  1104. columns = result['columns']
  1105. rows = cnx.get_rows()
  1106. else:
  1107. # do something useful with INSERT result
  1108. Returns a generator object.
  1109. 7.2.16. Method MySQLConnection.cmd_refresh(options)
  1110. This method flushes tables or caches, or resets replication server
  1111. information. The connected user must have the RELOAD privilege.
  1112. The options argument should be a bitwise value using constants
  1113. from the class constants.RefreshOption.
  1114. See Section 7.9, "Class constants.RefreshOption" for a list of
  1115. options.
  1116. Example:
  1117. >>> from mysql.connector import RefreshOption
  1118. >>> refresh = RefreshOption.LOG | RefreshOption.THREADS
  1119. >>> cnx.cmd_refresh(refresh)
  1120. 7.2.17. Method MySQLConnection.cmd_shutdown()
  1121. Asks the database server to shut down. The connected user must
  1122. have the SHUTDOWN privilege.
  1123. Returns a dictionary containing the OK packet information.
  1124. 7.2.18. Method MySQLConnection.cmd_statistics()
  1125. Returns a dictionary containing information about the MySQL server
  1126. including uptime in seconds and the number of running threads,
  1127. questions, reloads, and open tables.
  1128. 7.2.19. Method MySQLConnection.disconnect()
  1129. This method tries to send the QUIT command and close the socket.
  1130. It does not raise any exceptions.
  1131. MySQLConnection.close() is a synonymous method name and more
  1132. commonly used.
  1133. 7.2.20. Method MySQLConnection.get_rows(count=None)
  1134. This method retrieves all or remaining rows of a query result set,
  1135. returning a tuple containing the rows as sequence and the EOF
  1136. packet information. The count argument can be used to get a given
  1137. amount of rows. If count is not specified or is None, all rows are
  1138. retrieved.
  1139. The tuple returned by get_rows() consists of:
  1140. * A list of tuples containing the row data as byte objects, or
  1141. an empty list when no rows are available.
  1142. * EOF packet information as a dictionary containing status_flag
  1143. and warning_count.
  1144. An InterfaceError is raised when all rows have been retrieved.
  1145. The get_rows() method is used by MySQLCursor to fetch rows.
  1146. Returns a tuple.
  1147. 7.2.21. Method MySQLConnection.get_row()
  1148. This method retrieves the next row of a query result set,
  1149. returning a tuple.
  1150. The tuple returned by get_row() consists of:
  1151. * The row as a tuple containing byte objects, or None when no
  1152. more rows are available.
  1153. * EOF packet information as a dictionary containing status_flag
  1154. and warning_count, or None when the row returned is not the
  1155. last row.
  1156. The get_row() method is used by MySQLCursor to fetch rows.
  1157. 7.2.22. Method MySQLConnection.get_server_info()
  1158. This method returns the MySQL server information verbatim, for
  1159. example '5.5.24-log', or None when not connected.
  1160. Returns a string or None.
  1161. 7.2.23. Method MySQLConnection.get_server_version()
  1162. This method returns the MySQL server version as a tuple, or None
  1163. when not connected.
  1164. Returns a tuple or None.
  1165. 7.2.24. Method MySQLConnection.is_connected()
  1166. Reports whether the connection to MySQL Server is available.
  1167. This method checks whether the connection to MySQL is available
  1168. using the ping() method, but unlike ping(), is_connected() returns
  1169. True when the connection is available, False otherwise.
  1170. Returns True or False.
  1171. 7.2.25. Method MySQLConnection.isset_client_flag(flag)
  1172. This method returns True if the client flag was set, False
  1173. otherwise.
  1174. Returns True or False.
  1175. 7.2.26. Method MySQLConnection.ping(attempts=1, delay=0)
  1176. Check whether the connection to the MySQL server is still
  1177. available.
  1178. When reconnect is set to True, one or more attempts are made to
  1179. try to reconnect to the MySQL server using the reconnect() method.
  1180. Use the delay argument (seconds) if you want to wait between each
  1181. retry.
  1182. When the connection is not available, an InterfaceError is raised.
  1183. Use the is_connected() method to check the connection without
  1184. raising an error.
  1185. Raises InterfaceError on errors.
  1186. 7.2.27. Method MySQLConnection.reconnect(attempts=1, delay=0)
  1187. Attempt to reconnect with the MySQL server.
  1188. The argument attempts specifies the number of times a reconnect is
  1189. tried. The delay argument is the number of seconds to wait between
  1190. each retry.
  1191. You might set the number of attempts higher and use a longer delay
  1192. when you expect the MySQL server to be down for maintenance, or
  1193. when you expect the network to be temporarily unavailable.
  1194. 7.2.28. Method MySQLConnection.rollback()
  1195. This method sends the ROLLBACK command to the MySQL server,
  1196. undoing all data changes from the current transaction. Since by
  1197. default, Connector/Python does not auto commit, it is possible to
  1198. cancel transactions when using transactional storage engines such
  1199. as InnoDB.
  1200. See the commit() method for committing
  1201. (http://dev.mysql.com/doc/refman/5.5/en/glossary.html#glos_commit)
  1202. transactions.
  1203. >>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s)",
  1204. ('Jane'))
  1205. >>> cnx.rollback()
  1206. 7.2.29. Method MySQLConnection.set_charset_collation(charset=None,
  1207. collation=None)
  1208. This method sets the character set and collation to be used for
  1209. the current connection. The charset argument can be either the
  1210. name of a character set, or the numerical equivalent as defined in
  1211. constants.CharacterSet.
  1212. When collation is None, the default will be looked up and used.
  1213. The charset argument then be either:
  1214. In the following example, we set the character set to latin1 and
  1215. the collation will be set to the default latin1_swedish_ci:
  1216. >>> cnx = mysql.connector.connect(user='scott')
  1217. >>> cnx.set_charset('latin1')
  1218. Specify a specific collation as follows:
  1219. >>> cnx = mysql.connector.connect(user='scott')
  1220. >>> cnx.set_charset('latin1', 'latin1_general_ci')
  1221. 7.2.30. Method MySQLConnection.set_client_flags(flags)
  1222. This method sets the client flags which are used when connecting
  1223. with the MySQL server and returns the new value. The flags
  1224. argument can be either an integer or a sequence of valid client
  1225. flag values (see Section 7.5, "Class constants.ClientFlag").
  1226. If flags is a sequence, each item in the sequence will set the
  1227. flag when the value is positive or unset it when negative. For
  1228. example, to unset LONG_FLAG and set the FOUND_ROWS flags:
  1229. >>> from mysql.connector.constants import ClientFlag
  1230. >>> cnx.set_client_flags([ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLA
  1231. G])
  1232. >>> cnx.reconnect()
  1233. Note that client flags are only set or used when connecting with
  1234. the MySQL server. It is therefor necessary to reconnect after
  1235. making changes.
  1236. Returns an integer.
  1237. 7.2.31. Property MySQLConnection.autocommit
  1238. This property is used to toggle the auto commit feature of MySQL
  1239. and retrieve the current state. When the value evaluates to True,
  1240. auto commit will be turned, otherwise it is turned off.
  1241. Note that auto commit is disabled by default when connecting
  1242. through Connector/Python. This can be toggled using the connection
  1243. parameter autocommit.
  1244. When the auto commit is turned off, you have to commit
  1245. transactions when using transactional storage engines such as
  1246. InnoDB or NDBCluster.
  1247. >>> cnx.autocommit
  1248. False
  1249. >>> cnx.autocommit = True
  1250. >>> cnx.autocommit
  1251. True
  1252. Returns True or False.
  1253. 7.2.32. Property MySQLConnection.charset_name
  1254. This property returns which character set is used for the
  1255. connection whether it is connected or not.
  1256. Returns a string.
  1257. 7.2.33. Property MySQLConnection.collation_name
  1258. This property returns which collation is used for the connection
  1259. whether it is connected or not.
  1260. Returns a string.
  1261. 7.2.34. Property MySQLConnection.connection_id
  1262. This property returns the connection ID (thread ID or session ID)
  1263. for the current connection or None when not connected.
  1264. Returns a integer or None.
  1265. 7.2.35. Property MySQLConnection.database
  1266. This property is used to set current (active) database executing
  1267. the USE command. The property can also be used to retrieve the
  1268. current database name.
  1269. >>> cnx.database = 'test'
  1270. >>> cnx.database = 'mysql'
  1271. >>> cnx.database
  1272. u'mysql'
  1273. Returns a string.
  1274. 7.2.36. Property MySQLConnection.get_warnings
  1275. This property is used to toggle whether warnings should be fetched
  1276. automatically or not. It accepts True or False (default).
  1277. Fetching warnings automatically could be useful when debugging
  1278. queries. Cursors will make warnings available through the method
  1279. MySQLCursor.fetchwarnings().
  1280. >>> cnx.get_warnings = True
  1281. >>> cursor.execute('SELECT "a"+1')
  1282. >>> cursor.fetchall()
  1283. [(1.0,)]
  1284. >>> cursor.fetchwarnings()
  1285. [(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
  1286. Returns True or False.
  1287. 7.2.37. Property MySQLConnection.raise_on_warnings
  1288. This property is used to toggle whether warnings should raise
  1289. exceptions or not. It accepts True or False (default).
  1290. Toggling raise_on_warnings will also toggle get_warnings since
  1291. warnings need to be fetched so they can be raised as exceptions.
  1292. Note that you might always want to check setting SQL Mode if you
  1293. would like to have the MySQL server directly report warnings as
  1294. errors. It is also good to use transactional engines so
  1295. transactions can be rolled back when catching the exception.
  1296. Result sets needs to be fetched completely before any exception
  1297. can be raised. The following example shows the execution of a
  1298. query which produces a warning
  1299. >>> cnx.raise_on_warnings = True
  1300. >>> cursor.execute('SELECT "a"+1')
  1301. >>> cursor.fetchall()
  1302. ..
  1303. mysql.connector.errors.DataError: 1292: Truncated incorrect DOUBLE va
  1304. lue: 'a'
  1305. Returns True or False.
  1306. 7.2.38. Property MySQLConnection.server_host
  1307. This read-only property returns the hostname or IP address used
  1308. for connecting with the MySQL server.
  1309. Returns a string.
  1310. 7.2.39. Property MySQLConnection.server_port
  1311. This read-only property returns the TCP/IP port used for
  1312. connecting with the MySQL server.
  1313. Returns a integer.
  1314. 7.2.40. Property MySQLConnection.sql_mode
  1315. This property is used to retrieve and set the SQL Modes for the
  1316. current. The value should be list of different modes separated by
  1317. comma (","), or a sequence of modes, preferably using the
  1318. constants.SQLMode class.
  1319. To unset all modes, pass an empty string or an empty sequence.
  1320. >>> cnx.sql_mode = 'TRADITIONAL,NO_ENGINE_SUBSTITUTION'
  1321. >>> cnx.sql_mode.split(',')
  1322. [u'STRICT_TRANS_TABLES', u'STRICT_ALL_TABLES', u'NO_ZERO_IN_DATE',
  1323. u'NO_ZERO_DATE', u'ERROR_FOR_DIVISION_BY_ZERO', u'TRADITIONAL',
  1324. u'NO_AUTO_CREATE_USER', u'NO_ENGINE_SUBSTITUTION']
  1325. >>> from mysql.connector.constants import SQLMode
  1326. >>> cnx.sql_mode = [ SQLMode.NO_ZERO_DATE, SQLMode.REAL_AS_FLOAT]
  1327. >>> cnx.sql_mode
  1328. u'REAL_AS_FLOAT,NO_ZERO_DATE'
  1329. Returns a string.
  1330. 7.2.41. Property MySQLConnection.time_zone
  1331. This property is used to set the time zone session variable for
  1332. the current connection and retrieve it.
  1333. >>> cnx.time_zone = '+00:00'
  1334. >>> cur.execute('SELECT NOW()') ; cur.fetchone()
  1335. (datetime.datetime(2012, 6, 15, 11, 24, 36),)
  1336. >>> cnx.time_zone = '-09:00'
  1337. >>> cur.execute('SELECT NOW()') ; cur.fetchone()
  1338. (datetime.datetime(2012, 6, 15, 2, 24, 44),)
  1339. >>> cnx.time_zone
  1340. u'-09:00'
  1341. Returns a string.
  1342. 7.2.42. Property MySQLConnection.unix_socket
  1343. This read-only property returns the UNIX socket user for
  1344. connecting with the MySQL server.
  1345. Returns a string.
  1346. 7.2.43. Property MySQLConnection.user
  1347. This read-only property returns the username used for connecting
  1348. with the MySQL server.
  1349. Returns a string.
  1350. 7.3. Class cursor.MySQLCursor
  1351. The MySQLCursor class is used to instantiate object which can
  1352. execute operation such as SQL queries. They interact with the
  1353. MySQL server using a MySQLConnection object.
  1354. 7.3.1. Constructor cursor.MySQLCursor
  1355. The constructor initializes the instance with the optional
  1356. connection, which should be an instance of MySQLConnection.
  1357. In most cases, the MySQLConnection method cursor() is used to
  1358. instantiate a MySQLCursor object.
  1359. 7.3.2. Method MySQLCursor.callproc(procname, args=())
  1360. This method calls a stored procedure with the given name. The args
  1361. sequence of parameters must contain one entry for each argument
  1362. that the routine expects. The result is returned as modified copy
  1363. of the input sequence. Input parameters are left untouched, output
  1364. and input/output parameters replaced with possibly new values.
  1365. Result set provided by the stored procedure are automatically
  1366. fetched and stored as MySQLBufferedCursor instances. See
  1367. stored_results() for more information.
  1368. The following example shows how to execute a stored procedure
  1369. which takes two parameters, multiplies the values and returns the
  1370. product:
  1371. # Definition of the multiply stored procedure:
  1372. # CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT
  1373. )
  1374. # BEGIN
  1375. # SET pProd := pFac1 * pFac2;
  1376. # END
  1377. >>> args = (5, 5, 0) # 0 is to hold value of the OUT parameter pProd
  1378. >>> cursor.callproc('multiply', args)
  1379. ('5', '5', 25L)
  1380. 7.3.3. Method MySQLCursor.close()
  1381. This method will close the MySQL cursor, resetting all results and
  1382. removing the connection.
  1383. Use close() every time you are done using the cursor.
  1384. 7.3.4. Method MySQLCursor.execute(operation, params=None,
  1385. multi=False)
  1386. This method prepare the given database operation (query or
  1387. command). The parameters found in the tuple or dictionary params
  1388. will be bound to the variables in the operation. Variables are
  1389. specified using %s markers or named markers %(name)s.
  1390. For example, insert information about a new employee and selecting
  1391. again the data of this person:
  1392. insert = (
  1393. "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  1394. "VALUES (%s, %s, %s, %s)")
  1395. data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
  1396. cursor.execute(insert, data)
  1397. select = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
  1398. cursor.execute(select, { 'emp_no': 2 })
  1399. Note that the data is converted from Python object to something
  1400. MySQL understand. In the above example, the datetime.date()
  1401. instance is converted to '2012-03-23' in the above example.
  1402. When multi is set to True, execute() will be able to execute
  1403. multiple statements. It will return an iterator which makes it
  1404. possible to go through all results for each statement. Note that
  1405. using parameters is not working well in this case, and it's
  1406. usually a good idea to execute each statement on its own.
  1407. In the following example we select and insert data in one
  1408. operation and display the result:
  1409. operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
  1410. for result in cursor.execute(operation):
  1411. if result.with_rows:
  1412. print("Statement '{}' has following rows:".format(
  1413. result.statement))
  1414. print(result.fetchall())
  1415. else:
  1416. print("Affected row(s) by query '{}' was {}".format(
  1417. result.statement, result.rowcount))
  1418. If the connection was configured to fetch warnings, warnings
  1419. generated by the operation will be available through the method
  1420. MySQLCursor.fetchwarnings().
  1421. Returns an iterator when multi is True.
  1422. 7.3.5. Method MySQLCursor.executemany(operation, seq_params)
  1423. This method prepares a database operation (query or command) and
  1424. then execute it against all parameter sequences or mappings found
  1425. in the sequence seq_of_params.
  1426. The executemany() is simply iterating through the sequence of
  1427. parameters calling the execute() method. Inserting data, however,
  1428. is optimized by batching them using the multiple rows syntax.
  1429. In the following example we are inserting 3 records:
  1430. data = [
  1431. ('Jane', date(2005, 2, 12)),
  1432. ('Joe', date(2006, 5, 23)),
  1433. ('John', date(2010, 10, 3)),
  1434. ]
  1435. stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)
  1436. "
  1437. cursor.executemany(stmt, data)
  1438. In the above example, the INSERT statement sent to MySQL would be
  1439. as follows: INSERT INTO employees (first_name, hire_date) VALUES
  1440. ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John',
  1441. '2010-10-03').
  1442. Note that it is not possible to execute multiple statements using
  1443. the executemany() method. Doing so will raise an InternalError
  1444. exception.
  1445. 7.3.6. Method MySQLCursor.fetchall()
  1446. The method fetches all or remaining rows of a query result set,
  1447. returning a list of tuples. An empty list is returned when no rows
  1448. are (anymore) available.
  1449. The following examples shows how to retrieve the first 2 rows of a
  1450. result set, and then retrieve the remaining rows:
  1451. >>> cursor.execute("SELECT * FROM employees ORDER BY emp_no")
  1452. >>> head_rows = cursor.fetchmany(size=2)
  1453. >>> remaining_rows = cursor.fetchall()
  1454. Note that you have to fetch all rows before being able to execute
  1455. new queries using the same connection.
  1456. Returns a list of tuples or empty list when no rows available.
  1457. 7.3.7. Method MySQLCursor.fetchmany(size=1)
  1458. This method fetches the next set of rows of a query results,
  1459. returning a list of tuples. An empty list is returned when no more
  1460. rows are available.
  1461. The number of rows returned can be specified using the size
  1462. argument, which defaults to one. Fewer rows might be returned,
  1463. when there are not more rows available than specified by the
  1464. argument.
  1465. Note that you have to fetch all rows before being able to execute
  1466. new queries using the same connection.
  1467. Returns a list of tuples or empty list when no rows available.
  1468. 7.3.8. Method MySQLCursor.fetchone()
  1469. This method retrieves the next row of a query result set,
  1470. returning a single sequence, or None when no more data is
  1471. available.The returned tuple consists of data returned by the
  1472. MySQL server converted to Python objects.
  1473. The fetchone() method is used by fetchmany() and fetchall(). It is
  1474. also used when using the MySQLCursor instance as an iterator.
  1475. The following examples show how to iterate through the result of a
  1476. query using fetchone():
  1477. # Using a while-loop
  1478. cursor.execute("SELECT * FROM employees")
  1479. row = cursor.fetchone()
  1480. while row is not None:
  1481. print(row)
  1482. row = cursor.fetchone()
  1483. # Using the cursor as iterator
  1484. cursor.execute("SELECT * FROM employees")
  1485. for row in cursor:
  1486. print(row)
  1487. Note that you have to fetch all rows before being able to execute
  1488. new queries using the same connection.
  1489. Returns a tuple or None.
  1490. 7.3.9. Method MySQLCursor.fetchwarnings()
  1491. This method returns a list of tuples containing warnings generated
  1492. by previously executed statement. Use the connection's
  1493. get_warnings property to toggle whether warnings has to be
  1494. fetched.
  1495. The following example shows a SELECT statement which generated a
  1496. warning:
  1497. >>> cnx.get_warnings = True
  1498. >>> cursor.execute('SELECT "a"+1')
  1499. >>> cursor.fetchall()
  1500. [(1.0,)]
  1501. >>> cursor.fetchwarnings()
  1502. [(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
  1503. It is also possible to raise errors when warnings are found. See
  1504. the MySQLConnection property raise_on_warnings.
  1505. Returns a list of tuples.
  1506. 7.3.10. Method MySQLCursor.stored_results()
  1507. This method returns an list iterator object which can be used to
  1508. go through result sets provided by stored procedures after calling
  1509. them using the callproc() method.
  1510. In the following example we execute a stored procedure which will
  1511. provide two result sets. We use stored_results() to retrieve them:
  1512. >>> cursor.callproc('sp1')
  1513. ()
  1514. >>> for result in cursor.stored_results():
  1515. ... print result.fetchall()
  1516. ...
  1517. [(1,)]
  1518. [(2,)]
  1519. Note that the result sets stay available until you executed
  1520. another operation or call another stored procedure.
  1521. Returns a listiterator.
  1522. 7.3.11. Property MySQLCursor.column_names
  1523. This read-only property returns the column names of a result set
  1524. as sequence of (unicode) strings.
  1525. The following example shows how you can create a dictionary out of
  1526. a tuple containing data with keys using column_names:
  1527. cursor.execute("SELECT last_name, first_name, hire_date "
  1528. "FROM employees WHERE emp_no = %s", (123,))
  1529. row = dict(zip(cursor.column_names, cursor.fetchone())
  1530. print("{last_name}, {first_name}: {hire_date}".format(row))
  1531. Returns a tuple.
  1532. 7.3.12. Property MySQLCursor.statement
  1533. This read-only property returns the last executed statement. In
  1534. case multiple statements where executed, it will show the actual
  1535. statement.
  1536. The statement property might be useful for debugging and showing
  1537. what was send to the MySQL server.
  1538. Returns a string.
  1539. 7.3.13. Property MySQLCursor.with_rows
  1540. This read-only property will return True when the result of the
  1541. executed operation provides rows.
  1542. The with_rows property is useful when executing multiple
  1543. statements and you need to fetch rows. In the following example we
  1544. only report the affected rows by the UPDATE statement:
  1545. import mysql.connector
  1546. cnx = mysql.connector.connect(user='scott', database='test')
  1547. cursor = cnx.cursor()
  1548. operation = 'SELECT 1; UPDATE t1 SET c1 = 2; SELECT 2'
  1549. for result in cursor.execute(operation, multi=True):
  1550. if result.with_rows:
  1551. result.fetchall()
  1552. else:
  1553. print("Updated row(s): {}".format(result.rowcount))
  1554. 7.4. Class cursor.MySQLCursorBuffered
  1555. This class is inheriting from cursor.MySQLCursor and if needed
  1556. automatically retrieves rows after an operation has been executed.
  1557. MySQLCursorBuffered can be useful in situations where two queries,
  1558. with small result sets, need to be combined or computed with each
  1559. other.
  1560. You can either use the buffered argument when using the
  1561. connection's cursor() method, or you can use the buffered
  1562. connection option to make all created cursors by default
  1563. buffering.
  1564. import mysql.connector
  1565. cnx = mysql.connector.connect()
  1566. # Only this particular cursor will be buffering results
  1567. cursor.cursor(buffered=True)
  1568. # All cursors by default buffering
  1569. cnx = mysql.connector.connect(buffered=True)
  1570. See Section 5.1, "Tutorial: Raise employee's salary using a
  1571. buffering cursor" for a practical use case.
  1572. 7.5. Class constants.ClientFlag
  1573. This class provides constants defining MySQL client flags which
  1574. can be used upon connection to configure the session. The
  1575. ClientFlag class is available when importing mysql.connector.
  1576. >>> import mysql.connector
  1577. >>> mysql.connector.ClientFlag.FOUND_ROWS
  1578. 2
  1579. See Section 7.2.30, "Method
  1580. MySQLConnection.set_client_flags(flags)" and the connection
  1581. argument client_flag.
  1582. Note that the ClientFlag class can not be instantiated.
  1583. 7.6. Class constants.FieldType
  1584. This class provides all supported MySQL field or data types. They
  1585. can be useful when dealing with raw data or defining your own
  1586. converters. The field type is stored with every cursor in the
  1587. description for each column.
  1588. The following example shows how you can print the name of the data
  1589. types for each of the columns in the result set.
  1590. from __future__ import print_function
  1591. import mysql.connector
  1592. from mysql.connector import FieldType
  1593. cnx = mysql.connector.connect(user='scott', database='test')
  1594. cursor = cnx.cursor()
  1595. cursor.execute(
  1596. "SELECT DATE(NOW()) AS `c1`, TIME(NOW()) AS `c2`, "
  1597. "NOW() AS `c3`, 'a string' AS `c4`, 42 AS `c5`")
  1598. rows = cursor.fetchall()
  1599. for desc in cursor.description:
  1600. colname = desc[0]
  1601. coltype = desc[1]
  1602. print("Column {} has type {}".format(
  1603. colname, FieldType.get_info(coltype)))
  1604. cursor.close()
  1605. cnx.close()
  1606. Note that the FieldType class can not be instantiated.
  1607. 7.7. Class constants.SQLMode
  1608. This class provides all known MySQL Server SQL Modes
  1609. (http://dev.mysql.com/doc/refman/5.5/en/server-sql-mode.html). It
  1610. is mostly used when setting the SQL modes at connection time using
  1611. the connection's property sql_mode. See Section 7.2.40, "Property
  1612. MySQLConnection.sql_mode."
  1613. Note that the SQLMode class can not be instantiated.
  1614. 7.8. Class constants.CharacterSet
  1615. This class provides all known MySQL characters sets and their
  1616. default collations. See Section 7.2.29, "Method
  1617. MySQLConnection.set_charset_collation(charset=None,
  1618. collation=None)" for examples.
  1619. Note that the CharacterSet class can not be instantiated.
  1620. 7.9. Class constants.RefreshOption
  1621. * RefreshOption.GRANT
  1622. Refresh the grant tables, like FLUSH PRIVILEGES
  1623. (http://dev.mysql.com/doc/refman/5.5/en/flush.html).
  1624. * RefreshOption.LOG
  1625. Flush the logs, like FLUSH LOGS
  1626. (http://dev.mysql.com/doc/refman/5.5/en/flush.html).
  1627. * RefreshOption.TABLES
  1628. Flush the table cache, like FLUSH TABLES
  1629. (http://dev.mysql.com/doc/refman/5.5/en/flush.html).
  1630. * RefreshOption.HOSTS
  1631. Flush the host cache, like FLUSH HOSTS
  1632. (http://dev.mysql.com/doc/refman/5.5/en/flush.html).
  1633. * RefreshOption.STATUS
  1634. Reset status variables, like FLUSH STATUS.
  1635. * RefreshOption.THREADS
  1636. Flush the thread cache.
  1637. * RefreshOption.SLAVE
  1638. On a slave replication server, reset the master server
  1639. information and restart the slave, like RESET SLAVE
  1640. (http://dev.mysql.com/doc/refman/5.5/en/reset-slave.html).
  1641. * RefreshOption.MASTER
  1642. On a master replication server, remove the binary log files
  1643. listed in the binary log index and truncate the index file,
  1644. like RESET MASTER
  1645. (http://dev.mysql.com/doc/refman/5.5/en/reset-master.html).
  1646. Chapter 8. MySQL Connector/Python Change History
  1647. 8.1. Changes in MySQL Connector/Python 1.0.8 (Not yet released,
  1648. Generally Available)
  1649. Fixes bugs since the initial 1.0.7 GA release.
  1650. Version 1.0.8 has no changelog entries.
  1651. 8.2. Changes in MySQL Connector/Python 1.0.7 (29 September 2012,
  1652. Generally Available)
  1653. GA release. Connector/Python is now production-ready.
  1654. Functionality Added or Changed
  1655. * Client and server errors have been regenerated using the MySQL
  1656. 5.6.6 development release.
  1657. Bugs Fixed
  1658. * Fixed formatting of client errors changing numeric to string
  1659. placeholders. (Bug #14548043)
  1660. 8.3. Changes in MySQL Connector/Python 1.0.6 (30 August 2012, beta)
  1661. Second beta release.
  1662. Functionality Added or Changed
  1663. * Changed name and version of distributions to align with other
  1664. MySQL projects:
  1665. + The version now includes the suffix 'b' for beta and 'a'
  1666. for alpha followed by a number. This version is used in
  1667. the source and built distributions. GA versions will have
  1668. no suffix.
  1669. + The RPM spec files have been updated to create packages
  1670. whose names are aligned with RPMs from other MySQL
  1671. projects.
  1672. * Changed how MySQL server errors are mapped to Python
  1673. exceptions. We now use the SQLState (when available) to raise
  1674. a better error.
  1675. + Incompatibility: some server errors are now raised with a
  1676. different exception.
  1677. + It is possible to override how errors are raised using
  1678. the mysql.connector.custom_error_exception() function,
  1679. defined in the mysql.connector.errors module. This can be
  1680. useful for certain frameworks to align with other
  1681. database drivers.
  1682. Bugs Fixed
  1683. * Fixed version-specific code so Connector/Python works with
  1684. Python 3.3. (Bug #14524942)
  1685. * Fixed MySQLCursorRaw.fetchall() so it does not raise an
  1686. exception when results are available. (Bug #14517262, Bug
  1687. #66465)
  1688. * Fixed installation of version.py on OS X:
  1689. + version.py is now correctly installed on OS X in the
  1690. mysql.connector package. Previously, it was installed
  1691. through data_files, and version.py ended up in the
  1692. system-wide package location of Python, from which it
  1693. could not be imported.
  1694. + data_files is not used any longer in setup.py and is
  1695. removed. Extra files like version.py are now copied in
  1696. the custom Distutils commands.
  1697. (Bug #14483142)
  1698. * Timeout for unit tests has been set to 10 seconds. Test cases
  1699. can individually adjust it to be higher or lower. (Bug
  1700. #14487502)
  1701. * Fixed test cases in test_mysql_database.py that failed when
  1702. using YEAR(2) with MySQL 5.6.6 and greater. (Bug #14460680)
  1703. * Fixed SSL unit testing for source distributions:
  1704. + The SSL keys and certificates were missing and are now
  1705. added to the source distribution. Now SSL testing works
  1706. properly.
  1707. + Additionally for the Windows platform, forward slashes
  1708. were added to the option file creation so the MySQL
  1709. server can pick up the needed SSL files.
  1710. (Bug #14402737)
  1711. 8.4. Changes in MySQL Connector/Python 1.0.5 (17 July 2012, beta)
  1712. First beta release.
  1713. Functionality Added or Changed
  1714. * Added SQLMode class in the constants module to make it easier
  1715. to set modes. For example:
  1716. cnx.sql_mode = [SQLMode.REAL_AS_FLOAT, SQLMode.NO_ZERO_DATE]
  1717. * Added descriptive error codes for both client and server
  1718. errors in the module errorcode. A new sub-package locales has
  1719. been added, which currently only supports English client error
  1720. messages.
  1721. For example, errorcode.CR_CONNECTION_ERROR is 2002.
  1722. 8.5. Changes in MySQL Connector/Python 1.0.4 (07 July 2012, alpha)
  1723. Internal alpha release.
  1724. Bugs Fixed
  1725. * Incompatible Change: The MySQLConnection methods
  1726. unset_client_flag() and set_client_flag() have been removed.
  1727. Use theset_client_flags() method instead using a sequence.
  1728. (Bug #14259996)
  1729. * Incompatible Change: The method MySQLConnection.set_charset()
  1730. has been removed and replaced by
  1731. MySQLConnection.set_charset_collation() to simplify setting
  1732. and retrieving character set and collation information. The
  1733. MySQLConnection properties collation and charset are now
  1734. read-only. (Bug #14260052)
  1735. * Incompatible Change: Fixed MySQLConnection.cmd_query() to
  1736. raise an error when the operation has multiple statements. We
  1737. introduced a new method MySQLConnection.cmd_query_iter() which
  1738. needs to be used when multiple statements send to the MySQL
  1739. server. It returns a generator object to iterate through
  1740. results.
  1741. When executing single statements, MySQLCursor.execute() will
  1742. always return None. You can use the MySQLCursor property
  1743. with_rows to check whether a result could have rows or not.
  1744. MySQLCursor.execute() returns a generator object with which
  1745. you can iterate over results when executing multiple
  1746. statements.
  1747. The MySQLCursor.next_resultset() became obsolete and was
  1748. removed and the MySQLCursor.next_proc_result() method has been
  1749. renamed to MySQLCursor.proc_results(), which returns a
  1750. generator object. The MySQLCursor.with_rows property can be
  1751. used to check if a result could return rows. The
  1752. multiple_resultset.py example script shows how to go through
  1753. results produced by sending multiple statements. (Bug
  1754. #14208326)
  1755. * Fixed MySQLCursor.executemany() when INSERT statements use the
  1756. ON DUPLICATE KEY clause with a function such as VALUES(). (Bug
  1757. #14259954)
  1758. * Fixed unit testing on the Microsoft Windows platform. (Bug
  1759. #14236592)
  1760. * Fixed converting a datetime.time to a MySQL type using Python
  1761. 2.4 and 2.5. The strftime() function has no support for the %f
  1762. mark in those Python versions. (Bug #14231941)
  1763. * Fixed cursor.CursorBase attributes description, lastrowid and
  1764. rowcount to be read-only properties. (Bug #14231160)
  1765. * Fixed MySQLConnection.cmd_query() and other methods so they
  1766. check first whether there are unread results. (Bug #14184643)
  1767. 8.6. Changes in MySQL Connector/Python 1.0.3 (08 June 2012, alpha)
  1768. Internal alpha release.
  1769. Functionality Added or Changed
  1770. * Adding new Distutils commands to create Windows Installers
  1771. using WiX and RPM packages.
  1772. * Adding support for time values with a fractional part, for
  1773. MySQL 5.6.4 and greater. A new example script microseconds.py
  1774. was added to show this functionality.
  1775. 8.7. Changes in MySQL Connector/Python 1.0.2 (19 May 2012, alpha)
  1776. Internal alpha release.
  1777. Functionality Added or Changed
  1778. * Added more unit tests for modules like connection and network
  1779. as well as testing the SSL functionality.
  1780. Bugs Fixed
  1781. * Fixing and refactoring the mysql.connector.errors module. (Bug
  1782. #14039339)
  1783. * Fixed bootstrapping MySQL 5.6 running unit tests.
  1784. Messages send by the bootstrapped MySQL server to stdout and
  1785. stderr are now discarded. (Bug #14048685)
  1786. 8.8. Changes in MySQL Connector/Python 1.0.1 (26 April 2012, alpha)
  1787. Internal alpha release.
  1788. Functionality Added or Changed
  1789. * Change the version so it only contain integers. The 'a' or
  1790. 'alpha' suffix will not be present in packages, but it will be
  1791. mentioned in the _version.py module since metasetupinfo.py
  1792. uses this information to set, for example, the Trove
  1793. classifiers dynamically.
  1794. 8.9. Changes in MySQL Connector/Python 1.0.0 (22 April 2012, alpha)
  1795. Internal alpha release.
  1796. Functionality Added or Changed
  1797. * Incompatible Change: MySQLConnection.reconnect() can be used
  1798. to reconnect to the MySQL server. It accepts number of retries
  1799. and an optional delay between attempts.
  1800. MySQLConnectiong.ping() is now a method and works the way the
  1801. MySQL C API mysql_ping() function works: it raises an error.
  1802. It can also optionally reconnect.
  1803. MySQLConnection.is_connected() now returns True when
  1804. connection is available, False otherwise.
  1805. ping() and is_connected() are backwards incompatible. (Bug
  1806. #13392739)
  1807. * Refactored the modules connection and protocol and created a
  1808. new module network. The MySQLProtocol does not keep a
  1809. reference to the connection object any more and deals only
  1810. with creating and parsing MySQL packets. Network interaction
  1811. is now done by the MySQLConnection objects (with the exception
  1812. of MySQLProtocol.read_text_result()).
  1813. Bugs Fixed
  1814. * Fixed metasetupinfo.py to use the Connector/Python which is
  1815. being installed instead of the version already installed. (Bug
  1816. #13962765)
  1817. * Fixed MySQLCursor.description so it stores column names as
  1818. Unicode. (Bug #13792575)
  1819. * Fixed dbapi.Binary to be a bytes types for Python 3.x. (Bug
  1820. #13780676)
  1821. * Fixed automatic garbage collection which caused memory usage
  1822. to grow over time. Note that MySQLConnection does not keep
  1823. track of its cursors any longer. (Bug #13435186)
  1824. * Fixed setting time zone for current MySQL session. (Bug
  1825. #13395083)
  1826. * Fixed setting and retrieving character set and collation. (Bug
  1827. #13375632)
  1828. * Fixed handling of errors after authentication for Python 3.
  1829. (Bug #13364285)
  1830. Copyright (c) 2012, Oracle and/or its affiliates. All rights
  1831. reserved. [1]Legal Notices
  1832. References
  1833. 1. file://localhost/data0/users/mysqldoc/docs-build/mysqldoc/topic-guides/topics-common/connector-python-nolink.html#legalnotice