PageRenderTime 68ms CodeModel.GetById 25ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full file

  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…

Large files files are truncated, but you can click here to view the full file