1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575
|
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>MySQL Connector/Python Developer Guide</title><link rel="stylesheet" type="text/css" href="mvl.css"><meta name="generator" content="DocBook XSL Stylesheets V1.79.1"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div lang="en" class="book"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python"></a>MySQL Connector/Python Developer Guide</h1></div><div><div class="abstract"><p class="title"><b>Abstract</b></p><p>
This manual describes how to install and configure MySQL Connector/Python, a
self-contained Python driver for communicating with MySQL
servers, and how to use it to develop database applications.
</p><p>
The latest MySQL Connector/Python version is recommended for use with MySQL
Server version 8.0 and higher.
</p><p>
For notes detailing the changes in each release of Connector/Python, see
<a class="ulink" href="https://dev.mysql.com/doc/relnotes/connector-python/en/" target="_top">MySQL Connector/Python
Release Notes</a>.
</p><p>
For legal information, see the <a class="link" href="#legalnotice" title="Legal Notices">Legal
Notices</a>.
</p><p>
For help with using MySQL, please visit the
<a class="ulink" href="http://forums.mysql.com" target="_top">MySQL Forums</a>, where you
can discuss your issues with other MySQL users.
</p><p><b>Licensing information. </b>
This product may include third-party software, used under
license. If you are using a Commercial release of MySQL Connector/Python, see
the
<a class="ulink" href="https://downloads.mysql.com/docs/licenses/connector-python-9.5-com-en.pdf" target="_top">MySQL Connector/Python
9.5 Commercial License Information User Manual</a> for
licensing information, including licensing information
relating to third-party software that may be included in this
Commercial release. If you are using a Community release of
MySQL Connector/Python, see the
<a class="ulink" href="https://downloads.mysql.com/docs/licenses/connector-python-9.5-gpl-en.pdf" target="_top">MySQL Connector/Python
9.5 Community License Information User Manual</a> for
licensing information, including licensing information
relating to third-party software that may be included in this
Community release.
</p><p>
Document generated on:
2025-10-13
(revision: 83739)
</p></div></div></div><hr></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="preface"><a href="#preface">Preface and Legal Notices</a></span></dt><dt><span class="chapter"><a href="#connector-python-introduction">1 Introduction to MySQL Connector/Python</a></span></dt><dt><span class="chapter"><a href="#connector-python-coding">2 Guidelines for Python Developers</a></span></dt><dt><span class="chapter"><a href="#connector-python-versions">3 Connector/Python Versions</a></span></dt><dt><span class="chapter"><a href="#connector-python-installation">4 Connector/Python Installation</a></span></dt><dd><dl><dt><span class="section"><a href="#quick-installation-guide">4.1 Quick Installation Guide</a></span></dt><dt><span class="section"><a href="#differences-between-binary-and-source-distribution">4.2 Differences Between Binary And Source Distributions</a></span></dt><dt><span class="section"><a href="#connector-python-obtaining">4.3 Obtaining Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-installation-binary">4.4 Installing Connector/Python from a Binary Distribution</a></span></dt><dd><dl><dt><span class="section"><a href="#id1847">4.4.1 Installing Connector/Python with pip</a></span></dt><dt><span class="section"><a href="#installing-from-rpm">4.4.2 Installing by RPMs</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-installation-source">4.5 Installing Connector/Python from a Source Distribution</a></span></dt><dt><span class="section"><a href="#connector-python-verification">4.6 Verifying Your Connector/Python Installation</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-examples">5 Connector/Python Coding Examples</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-example-connecting">5.1 Connecting to MySQL Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-ddl">5.2 Creating Tables Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-transaction">5.3 Inserting Data Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-select">5.4 Querying Data Using Connector/Python</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-tutorials">6 Connector/Python Tutorials</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-tutorial-cursorbuffered">6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-connecting">7 Connector/Python Connection Establishment</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-connectargs">7.1 Connector/Python Connection Arguments</a></span></dt><dt><span class="section"><a href="#connector-python-option-files">7.2 Connector/Python Option-File Support</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-cext">8 The Connector/Python C Extension</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-cext-development">8.1 Application Development with the Connector/Python C Extension</a></span></dt><dt><span class="section"><a href="#connector-python-cext-module">8.2 The _mysql_connector C Extension Module</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-other">9 Connector/Python Other Topics</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-logging">9.1 Connector/Python Logging</a></span></dt><dt><span class="section"><a href="#connector-python-opentelemetry">9.2 Telemetry Support</a></span></dt><dt><span class="section"><a href="#connector-python-multi">9.3 Executing Multiple Statements</a></span></dt><dt><span class="section"><a href="#connector-python-asyncio">9.4 Asynchronous Connectivity</a></span></dt><dt><span class="section"><a href="#connector-python-connection-pooling">9.5 Connector/Python Connection Pooling</a></span></dt><dt><span class="section"><a href="#connector-python-django-backend">9.6 Connector/Python Django Back End</a></span></dt></dl></dd><dt><span class="chapter"><a href="#connector-python-reference">10 Connector/Python API Reference</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysql-connector">10.1 mysql.connector Module</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysql-connector-connect">10.1.1 mysql.connector.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-apilevel">10.1.2 mysql.connector.apilevel Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-paramstyle">10.1.3 mysql.connector.paramstyle Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-threadsafety">10.1.4 mysql.connector.threadsafety Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version">10.1.5 mysql.connector.__version__ Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version-info">10.1.6 mysql.connector.__version_info__ Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnection">10.2 connection.MySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnection-constructor">10.2.1 connection.MySQLConnection() Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-close">10.2.2 MySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-commit">10.2.3 MySQLConnection.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-config">10.2.4 MySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connect">10.2.5 MySQLConnection.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cursor">10.2.6 MySQLConnection.cursor() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-change-user">10.2.7 MySQLConnection.cmd_change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-debug">10.2.8 MySQLConnection.cmd_debug() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-init-db">10.2.9 MySQLConnection.cmd_init_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-ping">10.2.10 MySQLConnection.cmd_ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-info">10.2.11 MySQLConnection.cmd_process_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-kill">10.2.12 MySQLConnection.cmd_process_kill() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query">10.2.13 MySQLConnection.cmd_query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query-iter">10.2.14 MySQLConnection.cmd_query_iter() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-quit">10.2.15 MySQLConnection.cmd_quit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-refresh">10.2.16 MySQLConnection.cmd_refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-reset-connection">10.2.17 MySQLConnection.cmd_reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-shutdown">10.2.18 MySQLConnection.cmd_shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-statistics">10.2.19 MySQLConnection.cmd_statistics() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-disconnect">10.2.20 MySQLConnection.disconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-row">10.2.21 MySQLConnection.get_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-rows">10.2.22 MySQLConnection.get_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-info">10.2.23 MySQLConnection.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-version">10.2.24 MySQLConnection.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-is-connected">10.2.25 MySQLConnection.is_connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-isset-client-flag">10.2.26 MySQLConnection.isset_client_flag() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-ping">10.2.27 MySQLConnection.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reconnect">10.2.28 MySQLConnection.reconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reset-session">10.2.29 MySQLConnection.reset_session() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-rollback">10.2.30 MySQLConnection.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-charset-collation">10.2.31 MySQLConnection.set_charset_collation() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-client-flags">10.2.32 MySQLConnection.set_client_flags() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-shutdown">10.2.33 MySQLConnection.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-start-transaction">10.2.34 MySQLConnection.start_transaction() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-autocommit">10.2.35 MySQLConnection.autocommit Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unread-results">10.2.36 MySQLConnection.unread_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-can-consume-results">10.2.37 MySQLConnection.can_consume_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-charset">10.2.38 MySQLConnection.charset Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-client-flags">10.2.39 MySQLConnection.client_flags Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-collation">10.2.40 MySQLConnection.collation Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connected">10.2.41 MySQLConnection.connected Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connection-id">10.2.42 MySQLConnection.connection_id Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-converter-class">10.2.43 MySQLConnection.converter-class Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-database">10.2.44 MySQLConnection.database Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-warnings">10.2.45 MySQLConnection.get_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-in-transaction">10.2.46 MySQLConnection.in_transaction Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-raise-on-warnings">10.2.47 MySQLConnection.raise_on_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-host">10.2.48 MySQLConnection.server_host Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-info">10.2.49 MySQLConnection.server_info Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-port">10.2.50 MySQLConnection.server_port Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-version">10.2.51 MySQLConnection.server_version Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-sql-mode">10.2.52 MySQLConnection.sql_mode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-time-zone">10.2.53 MySQLConnection.time_zone Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-use-unicode">10.2.54 MySQLConnection.use_unicode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unix-socket">10.2.55 MySQLConnection.unix_socket Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-user">10.2.56 MySQLConnection.user Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool">10.3 pooling.MySQLConnectionPool Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-constructor">10.3.1 pooling.MySQLConnectionPool Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-add-connection">10.3.2 MySQLConnectionPool.add_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-get-connection">10.3.3 MySQLConnectionPool.get_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-set-config">10.3.4 MySQLConnectionPool.set_config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-pool-name">10.3.5 MySQLConnectionPool.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection">10.4 pooling.PooledMySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-constructor">10.4.1 pooling.PooledMySQLConnection Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-close">10.4.2 PooledMySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-config">10.4.3 PooledMySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-pool-name">10.4.4 PooledMySQLConnection.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlcursor">10.5 cursor.MySQLCursor Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursor-constructor">10.5.1 cursor.MySQLCursor Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-add-attribute">10.5.2 MySQLCursor.add_attribute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-clear-attributes">10.5.3 MySQLCursor.clear_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-get-attributes">10.5.4 MySQLCursor.get_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-callproc">10.5.5 MySQLCursor.callproc() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-close">10.5.6 MySQLCursor.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-execute">10.5.7 MySQLCursor.execute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-executemany">10.5.8 MySQLCursor.executemany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchall">10.5.9 MySQLCursor.fetchall() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchmany">10.5.10 MySQLCursor.fetchmany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchone">10.5.11 MySQLCursor.fetchone() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-nextset">10.5.12 MySQLCursor.nextset() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchsets">10.5.13 MySQLCursor.fetchsets() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchwarnings">10.5.14 MySQLCursor.fetchwarnings() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-stored-results">10.5.15 MySQLCursor.stored_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-column-names">10.5.16 MySQLCursor.column_names Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-description">10.5.17 MySQLCursor.description Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-warnings">10.5.18 MySQLCursor.warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-lastrowid">10.5.19 MySQLCursor.lastrowid Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-rowcount">10.5.20 MySQLCursor.rowcount Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-statement">10.5.21 MySQLCursor.statement Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-with-rows">10.5.22 MySQLCursor.with_rows Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-cursor-subclasses">10.6 Subclasses cursor.MySQLCursor</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffered">10.6.1 cursor.MySQLCursorBuffered Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorraw">10.6.2 cursor.MySQLCursorRaw Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursordict">10.6.3 cursor.MySQLCursorDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffereddict">10.6.4 cursor.MySQLCursorBufferedDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorprepared">10.6.5 cursor.MySQLCursorPrepared Class</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-clientflag">10.7 constants.ClientFlag Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-fieldtype">10.8 constants.FieldType Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-sqlmode">10.9 constants.SQLMode Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-characterset">10.10 constants.CharacterSet Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-refreshoption">10.11 constants.RefreshOption Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors">10.12 Errors and Exceptions</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-errorcode">10.12.1 errorcode Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-error">10.12.2 errors.Error Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-dataerror">10.12.3 errors.DataError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-databaseerror">10.12.4 errors.DatabaseError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-integrityerror">10.12.5 errors.IntegrityError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-interfaceerror">10.12.6 errors.InterfaceError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-internalerror">10.12.7 errors.InternalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-notsupportederror">10.12.8 errors.NotSupportedError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-operationalerror">10.12.9 errors.OperationalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-poolerror">10.12.10 errors.PoolError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-programmingerror">10.12.11 errors.ProgrammingError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-warning">10.12.12 errors.Warning Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-custom-error-exception">10.12.13 errors.custom_error_exception() Function</a></span></dt></dl></dd></dl></dd><dt><span class="chapter"><a href="#connector-python-cext-reference">11 Connector/Python C Extension API Reference</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-cext-mysql-connector">11.1 _mysql_connector Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-mysql">11.2 _mysql_connector.MySQL() Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-affected-rows">11.3 _mysql_connector.MySQL.affected_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-autocommit">11.4 _mysql_connector.MySQL.autocommit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-buffered">11.5 _mysql_connector.MySQL.buffered() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-change-user">11.6 _mysql_connector.MySQL.change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-character-set-name">11.7 _mysql_connector.MySQL.character_set_name() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-close">11.8 _mysql_connector.MySQL.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-commit">11.9 _mysql_connector.MySQL.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connect">11.10 _mysql_connector.MySQL.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connected">11.11 _mysql_connector.MySQL.connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-consume-result">11.12 _mysql_connector.MySQL.consume_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-convert-to-mysql">11.13 _mysql_connector.MySQL.convert_to_mysql() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-escape-string">11.14 _mysql_connector.MySQL.escape_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-fields">11.15 _mysql_connector.MySQL.fetch_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-row">11.16 _mysql_connector.MySQL.fetch_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-field-count">11.17 _mysql_connector.MySQL.field_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-free-result">11.18 _mysql_connector.MySQL.free_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-character-set-info">11.19 _mysql_connector.MySQL.get_character_set_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-info">11.20 _mysql_connector.MySQL.get_client_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-version">11.21 _mysql_connector.MySQL.get_client_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-host-info">11.22 _mysql_connector.MySQL.get_host_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-proto-info">11.23 _mysql_connector.MySQL.get_proto_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-info">11.24 _mysql_connector.MySQL.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-version">11.25 _mysql_connector.MySQL.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-ssl-cipher">11.26 _mysql_connector.MySQL.get_ssl_cipher() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-hex-string">11.27 _mysql_connector.MySQL.hex_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-insert-id">11.28 _mysql_connector.MySQL.insert_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-more-results">11.29 _mysql_connector.MySQL.more_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-next-result">11.30 _mysql_connector.MySQL.next_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-fields">11.31 _mysql_connector.MySQL.num_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-rows">11.32 _mysql_connector.MySQL.num_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-ping">11.33 _mysql_connector.MySQL.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-query">11.34 _mysql_connector.MySQL.query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-raw">11.35 _mysql_connector.MySQL.raw() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-refresh">11.36 _mysql_connector.MySQL.refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-reset-connection">11.37 _mysql_connector.MySQL.reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-rollback">11.38 _mysql_connector.MySQL.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-select-db">11.39 _mysql_connector.MySQL.select_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-set-character-set">11.40 _mysql_connector.MySQL.set_character_set() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-shutdown">11.41 _mysql_connector.MySQL.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-stat">11.42 _mysql_connector.MySQL.stat() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-thread-id">11.43 _mysql_connector.MySQL.thread_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-use-unicode">11.44 _mysql_connector.MySQL.use_unicode() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-warning-count">11.45 _mysql_connector.MySQL.warning_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-have-result-set">11.46 _mysql_connector.MySQL.have_result_set Property</a></span></dt></dl></dd><dt><span class="index"><a href="#ix01">Index</a></span></dt></dl></div><div class="preface"><div class="titlepage"><div><div><h1 class="title"><a name="preface"></a>Preface and Legal Notices</h1></div></div></div><p>
This manual describes how to install, configure, and develop
database applications using MySQL Connector/Python, the Python driver for
communicating with MySQL servers.
</p><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="legalnotice"></a>Legal Notices</h2></div></div></div><p>
Copyright © 2012, 2025, Oracle and/or its affiliates.
</p><p>
<span class="strong"><strong>License Restrictions</strong></span>
</p><p>
This software and related documentation are provided under a license
agreement containing restrictions on use and disclosure and are
protected by intellectual property laws. Except as expressly
permitted in your license agreement or allowed by law, you may not
use, copy, reproduce, translate, broadcast, modify, license,
transmit, distribute, exhibit, perform, publish, or display any
part, in any form, or by any means. Reverse engineering,
disassembly, or decompilation of this software, unless required by
law for interoperability, is prohibited.
</p><p>
<span class="strong"><strong>Warranty Disclaimer</strong></span>
</p><p>
The information contained herein is subject to change without notice
and is not warranted to be error-free. If you find any errors,
please report them to us in writing.
</p><p>
<span class="strong"><strong>Restricted Rights Notice</strong></span>
</p><p>
If this is software, software documentation, data (as defined in the
Federal Acquisition Regulation), or related documentation that is
delivered to the U.S. Government or anyone licensing it on behalf of
the U.S. Government, then the following notice is applicable:
</p><p>
U.S. GOVERNMENT END USERS: Oracle programs (including any operating
system, integrated software, any programs embedded, installed, or
activated on delivered hardware, and modifications of such programs)
and Oracle computer documentation or other Oracle data delivered to
or accessed by U.S. Government end users are "commercial computer
software," "commercial computer software documentation," or "limited
rights data" pursuant to the applicable Federal Acquisition
Regulation and agency-specific supplemental regulations. As such,
the use, reproduction, duplication, release, display, disclosure,
modification, preparation of derivative works, and/or adaptation of
i) Oracle programs (including any operating system, integrated
software, any programs embedded, installed, or activated on
delivered hardware, and modifications of such programs), ii) Oracle
computer documentation and/or iii) other Oracle data, is subject to
the rights and limitations specified in the license contained in the
applicable contract. The terms governing the U.S. Government's use
of Oracle cloud services are defined by the applicable contract for
such services. No other rights are granted to the U.S. Government.
</p><p>
<span class="strong"><strong>Hazardous Applications Notice</strong></span>
</p><p>
This software or hardware is developed for general use in a variety
of information management applications. It is not developed or
intended for use in any inherently dangerous applications, including
applications that may create a risk of personal injury. If you use
this software or hardware in dangerous applications, then you shall
be responsible to take all appropriate fail-safe, backup,
redundancy, and other measures to ensure its safe use. Oracle
Corporation and its affiliates disclaim any liability for any
damages caused by use of this software or hardware in dangerous
applications.
</p><p>
<span class="strong"><strong>Trademark Notice</strong></span>
</p><p>
Oracle, Java, MySQL, and NetSuite are registered trademarks of
Oracle and/or its affiliates. Other names may be trademarks of their
respective owners.
</p><p>
Intel and Intel Inside are trademarks or registered trademarks of
Intel Corporation. All SPARC trademarks are used under license and
are trademarks or registered trademarks of SPARC International, Inc.
AMD, Epyc, and the AMD logo are trademarks or registered trademarks
of Advanced Micro Devices. UNIX is a registered trademark of The
Open Group.
</p><p>
<span class="strong"><strong>Third-Party Content, Products, and Services Disclaimer</strong></span>
</p><p>
This software or hardware and documentation may provide access to or
information about content, products, and services from third
parties. Oracle Corporation and its affiliates are not responsible
for and expressly disclaim all warranties of any kind with respect
to third-party content, products, and services unless otherwise set
forth in an applicable agreement between you and Oracle. Oracle
Corporation and its affiliates will not be responsible for any loss,
costs, or damages incurred due to your access to or use of
third-party content, products, or services, except as set forth in
an applicable agreement between you and Oracle.
</p><p>
<span class="strong"><strong>Use of This Documentation</strong></span>
</p><p>
This documentation is NOT distributed under a GPL license. Use of
this documentation is subject to the following terms:
</p><p>
You may create a printed copy of this documentation solely for your
own personal use. Conversion to other formats is allowed as long as
the actual content is not altered or edited in any way. You shall
not publish or distribute this documentation in any form or on any
media, except if you distribute the documentation in a manner
similar to how Oracle disseminates it (that is, electronically for
download on a Web site with the software) or on a CD-ROM or similar
medium, provided however that the documentation is disseminated
together with the software on the same medium. Any other use, such
as any dissemination of printed copies or use of this documentation,
in whole or in part, in another publication, requires the prior
written consent from an authorized representative of Oracle. Oracle
and/or its affiliates reserve any and all rights to this
documentation not expressly granted above.
</p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="id1556"></a>Documentation Accessibility</h2></div></div></div><p>
For information about Oracle's commitment to accessibility, visit
the Oracle Accessibility Program website at
<a class="ulink" href="http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc" target="_top">http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc</a>.
</p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="id1560"></a>Access to Oracle Support for Accessibility</h2></div></div></div><p>
Oracle customers that have purchased support have access to
electronic support through My Oracle Support. For information, visit
<a class="ulink" href="http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info" target="_top">http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info</a>
or visit
<code class="code"><a class="ulink" href="http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs" target="_top">http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs</a></code>
if you are hearing impaired.
</p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-introduction"></a>Chapter 1 Introduction to MySQL Connector/Python</h1></div></div></div><a class="indexterm" name="id1567"></a><a class="indexterm" name="id1569"></a><a class="indexterm" name="id1571"></a><a class="indexterm" name="id1573"></a><p>
MySQL Connector/Python enables Python programs to access MySQL databases, using an
API that is compliant with the
<a class="ulink" href="http://www.python.org/dev/peps/pep-0249/" target="_top">Python
Database API Specification v2.0 (PEP 249)</a>.
</p><p>
For notes detailing the changes in each release of Connector/Python, see
<a class="ulink" href="https://dev.mysql.com/doc/relnotes/connector-python/en/" target="_top">MySQL Connector/Python Release
Notes</a>.
</p><p>
MySQL Connector/Python includes support for:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Almost all features provided by MySQL Server version 8.0 and
higher.
</p></li><li class="listitem"><p>
Connector/Python supports X DevAPI. For X DevAPI specific documentation,
see <a class="ulink" href="https://dev.mysql.com/doc/x-devapi-userguide/en/" target="_top">X DevAPI User Guide</a>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
X DevAPI support was separated into its own package
(<code class="literal">mysqlx-connector-python</code>) in Connector/Python 8.3.0.
For related information, see
<a class="xref" href="#connector-python-installation" title="Chapter 4 Connector/Python Installation">Chapter 4, <i>Connector/Python Installation</i></a>.
</p></div></li><li class="listitem"><p>
Converting parameter values back and forth between Python and
MySQL data types, for example Python <code class="literal">datetime</code>
and MySQL <code class="literal">DATETIME</code>. You can turn automatic
conversion on for convenience, or off for optimal performance.
</p></li><li class="listitem"><p>
All MySQL extensions to standard SQL syntax.
</p></li><li class="listitem"><p>
Protocol compression, which enables compressing the data stream
between the client and server.
</p></li><li class="listitem"><p>
Connections using TCP/IP sockets and on Unix using Unix sockets.
</p></li><li class="listitem"><p>
Secure TCP/IP connections using SSL.
</p></li><li class="listitem"><p>
Self-contained driver. Connector/Python does not require the MySQL client
library or any Python modules outside the standard library.
</p></li></ul></div><p>
For information about which versions of Python can be used with
different versions of MySQL Connector/Python, see
<a class="xref" href="#connector-python-versions" title="Chapter 3 Connector/Python Versions">Chapter 3, <i>Connector/Python Versions</i></a>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Connector/Python does not support the old MySQL Server authentication
methods, which means that MySQL versions prior to 4.1 will not
work.
</p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-coding"></a>Chapter 2 Guidelines for Python Developers</h1></div></div></div><p>
The following guidelines cover aspects of developing MySQL
applications that might not be immediately obvious to developers
coming from a Python background:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
For security, do not hardcode the values needed to connect and
log into the database in your main script. Python has the
convention of a <code class="literal">config.py</code> module, where you
can keep such values separate from the rest of your code.
</p></li><li class="listitem"><p>
Python scripts often build up and tear down large data
structures in memory, up to the limits of available RAM. Because
MySQL often deals with data sets that are many times larger than
available memory, techniques that optimize storage space and
disk I/O are especially important. For example, in MySQL tables,
you typically use numeric IDs rather than string-based
dictionary keys, so that the key values are compact and have a
predictable length. This is especially important for columns
that make up the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_primary_key" target="_top">primary
key</a> for an <code class="literal">InnoDB</code> table, because those
column values are duplicated within each
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_secondary_index" target="_top">secondary index</a>.
</p></li><li class="listitem"><p>
Any application that accepts input must expect to handle bad
data.
</p><p>
The bad data might be accidental, such as out-of-range values or
misformatted strings. The application can use server-side checks
such as <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_unique_constraint" target="_top">unique
constraints</a> and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_not_null_constraint" target="_top">NOT NULL
constraints</a>, to keep the bad data from ever reaching the
database. On the client side, use techniques such as exception
handlers to report any problems and take corrective action.
</p><p>
The bad data might also be deliberate, representing an
<span class="quote">“<span class="quote">SQL injection</span>”</span> attack. For example, input values
might contain quotation marks, semicolons, <code class="literal">%</code>
and <code class="literal">_</code> wildcard characters and other
characters significant in SQL statements. Validate input values
to make sure they have only the expected characters. Escape any
special characters that could change the intended behavior when
substituted into an SQL statement. Never concatenate a user
input value into an SQL statement without doing validation and
escaping first. Even when accepting input generated by some
other program, expect that the other program could also have
been compromised and be sending you incorrect or malicious data.
</p></li><li class="listitem"><p>
Because the result sets from SQL queries can be very large, use
the appropriate method to retrieve items from the result set as
you loop through them.
<a class="link" href="#connector-python-api-mysqlcursor-fetchone" title="10.5.11 MySQLCursor.fetchone() Method">fetchone()</a>
retrieves a single item, when you know the result set contains a
single row.
<a class="link" href="#connector-python-api-mysqlcursor-fetchall" title="10.5.9 MySQLCursor.fetchall() Method">fetchall()</a>
retrieves all the items, when you know the result set contains a
limited number of rows that can fit comfortably into memory.
<a class="link" href="#connector-python-api-mysqlcursor-fetchmany" title="10.5.10 MySQLCursor.fetchmany() Method">fetchmany()</a>
is the general-purpose method when you cannot predict the size
of the result set: you keep calling it and looping through the
returned items, until there are no more results to process.
</p></li><li class="listitem"><p>
Since Python already has convenient modules such as
<code class="literal">pickle</code> and <code class="literal">cPickle</code> to read
and write data structures on disk, data that you choose to store
in MySQL instead is likely to have special characteristics:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
<span class="bold"><strong>Too large to all fit in memory at one
time.</strong></span> You use
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statements to query
only the precise items you need, and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html" target="_top">aggregate
functions</a> to perform calculations across multiple
items. You configure the
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html#sysvar_innodb_buffer_pool_size" target="_top"><code class="literal">innodb_buffer_pool_size</code></a>
option within the MySQL server to dedicate a certain amount
of RAM for caching table and index data.
</p></li><li class="listitem"><p>
<span class="bold"><strong>Too complex to be represented by a
single data structure.</strong></span> You divide the data
between different SQL tables. You can recombine data from
multiple tables by using a
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_join" target="_top">join</a> query. You make sure
that related data is kept in sync between different tables
by setting up <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_foreign_key" target="_top">foreign
key</a> relationships.
</p></li><li class="listitem"><p>
<span class="bold"><strong>Updated frequently, perhaps by
multiple users simultaneously.</strong></span> The updates might
only affect a small portion of the data, making it wasteful
to write the whole structure each time. You use the SQL
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a>,
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a>, and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/delete.html" target="_top"><code class="literal">DELETE</code></a> statements to update
different items concurrently, writing only the changed
values to disk. You use <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/innodb-storage-engine.html" target="_top"><code class="literal">InnoDB</code></a>
tables and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_transaction" target="_top">transactions</a> to keep
write operations from conflicting with each other, and to
return consistent query results even as the underlying data
is being updated.
</p></li></ul></div></li><li class="listitem"><p>
Using MySQL best practices for performance can help your
application to scale without requiring major rewrites and
architectural changes. See <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/optimization.html" target="_top">Optimization</a> for
best practices for MySQL performance. It offers guidelines and
tips for SQL tuning, database design, and server configuration.
</p></li><li class="listitem"><p>
You can avoid reinventing the wheel by learning the MySQL SQL
statements for common operations: operators to use in queries,
techniques for bulk loading data, and so on. Some statements and
clauses are extensions to the basic ones defined by the SQL
standard. See
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-data-manipulation-statements.html" target="_top">Data Manipulation Statements</a>,
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-data-definition-statements.html" target="_top">Data Definition Statements</a>, and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top">SELECT Statement</a> for the main classes of statements.
</p></li><li class="listitem"><p>
Issuing SQL statements from Python typically involves declaring
very long, possibly multi-line string literals. Because string
literals within the SQL statements could be enclosed by single
quotation, double quotation marks, or contain either of those
characters, for simplicity you can use Python's triple-quoting
mechanism to enclose the entire statement. For example:
</p><pre data-lang="python" class="programlisting">'''It doesn't matter if this string contains 'single'
or "double" quotes, as long as there aren't 3 in a
row.'''
</pre><p>
You can use either of the <code class="literal">'</code> or
<code class="literal">"</code> characters for triple-quoting multi-line
string literals.
</p></li><li class="listitem"><p>
Many of the secrets to a fast, scalable MySQL application
involve using the right syntax at the very start of your setup
procedure, in the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html" target="_top"><code class="literal">CREATE TABLE</code></a>
statements. For example, Oracle recommends the
<code class="literal">ENGINE=INNODB</code> clause for most tables, and
makes <code class="literal">InnoDB</code> the default storage engine in
MySQL 5.5 and up. Using <code class="literal">InnoDB</code> tables enables
transactional behavior that helps scalability of read-write
workloads and offers automatic
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_crash_recovery" target="_top">crash recovery</a>.
Another recommendation is to declare a numeric
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_primary_key" target="_top">primary key</a> for each
table, which offers the fastest way to look up values and can
act as a pointer to associated values in other tables (a
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_foreign_key" target="_top">foreign key</a>). Also
within the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html" target="_top"><code class="literal">CREATE TABLE</code></a>
statement, using the most compact column data types that meet
your application requirements helps performance and scalability
because that enables the database server to move less data back
and forth between memory and disk.
</p></li></ul></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-versions"></a>Chapter 3 Connector/Python Versions</h1></div></div></div><p>
This section describes both version releases, such as 8.0.34, along
with notes specific to the two implementations (C Extension and Pure
Python).
</p><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="connector-python-versions-releases"></a>Connector/Python Releases</h2></div></div></div><p>
The following table summarizes the available Connector/Python versions. For
series that have reached General Availability (GA) status,
development releases in the series prior to the GA version are no
longer supported.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
MySQL Connectors and other MySQL client tools and applications
now synchronize the first digit of their version number with the
(highest) MySQL server version they support. For example, MySQL Connector/Python
8.0.12 would be designed to support all features of MySQL server
version 8 (or lower). This change makes it easy and intuitive to
decide which client version to use for which server version.
</p><p>
Connector/Python 8.0.4 is the first release to use the new numbering. It is
the successor to Connector/Python 2.2.3.
</p></div><div class="table"><a name="connector-python-versions-listing"></a><p class="title"><b>Table 3.1 Connector/Python Version Reference</b></p><div class="table-contents"><table summary="For each Connector/Python version, this table lists the corresponding MySQL Server versions that it works with, the corresponding Python versions that it works with, and its status."><col width="20%"><col width="20%"><col width="20%"><col width="20%"><thead><tr>
<th scope="col">Connector/Python Version</th>
<th scope="col">MySQL Server Versions</th>
<th scope="col">Python Versions</th>
<th scope="col">Connector Status</th>
</tr></thead><tbody><tr>
<th scope="row">9.5.0 and later</th>
<td>8.0 and later</td>
<td>3.14, 3.13*, 3.12, 3.11, 3.10</td>
<td>General Availability</td>
</tr><tr>
<th scope="row">9.10 - 9.4.0</th>
<td>8.0 and later</td>
<td>3.13*, 3.12, 3.11, 3.10, 3.9</td>
<td>General Availability</td>
</tr><tr>
<th scope="row">8.4.0 and 9.0.0</th>
<td>8.0 and later</td>
<td>3.12, 3.11, 3.10, 3.9, 3.8</td>
<td>General Availability</td>
</tr><tr>
<th scope="row">8.1.0 - 8.3.0</th>
<td>5.7 and later</td>
<td>3.12 (8.2.0+), 3.11, 3.10, 3.9, 3.8</td>
<td>General Availability</td>
</tr><tr>
<th scope="row">8.0</th>
<td>8.0, 5.7, 5.6, 5.5</td>
<td>3.11, 3.10, 3.9, 3.8, 3.7, (3.6 before 8.0.29), (2.7 and 3.5 before
8.0.24)</td>
<td>General Availability</td>
</tr><tr>
<th scope="row">2.2 (continues as 8.0)</th>
<td>5.7, 5.6, 5.5</td>
<td>3.5, 3.4, 2.7</td>
<td>Developer Milestone, No releases</td>
</tr><tr>
<th scope="row">2.1</th>
<td>5.7, 5.6, 5.5</td>
<td>3.5, 3.4, 2.7, 2.6</td>
<td>General Availability</td>
</tr><tr>
<th scope="row">2.0</th>
<td>5.7, 5.6, 5.5</td>
<td>3.5, 3.4, 2.7, 2.6</td>
<td>GA, final release on 2016-10-26</td>
</tr><tr>
<th scope="row">1.2</th>
<td>5.7, 5.6, 5.5 (5.1, 5.0, 4.1)</td>
<td>3.4, 3.3, 3.2, 3.1, 2.7, 2.6</td>
<td>GA, final release on 2014-08-22</td>
</tr></tbody></table></div></div><br class="table-break"><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
MySQL server and Python versions within parentheses are known to
work with Connector/Python, but are not officially supported. Bugs might
not get fixed for those versions.
</p></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Python 3.13 enables <code class="literal">ssl.VERIFY_X509_STRICT</code>
SSL validation by default, which means SSL certificates must now
be RFC-5280 compliant when using Python 3.13 and higher.
</p></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
On macOS x86_64 ARM: Python 3.7 is not supported with the c-ext
implementation; note this is a non-default version of Python on
macOS.
</p></div></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h2 class="title" style="clear: both"><a name="connector-python-versions-implementations"></a>Connector/Python Implementations</h2></div></div></div><p>
Connector/Python implements the MySQL client/server protocol two ways:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
As pure Python; an implementation written in Python. It
depends on the Python Standard Library.
</p><p>
The X DevAPI variant of the connector requires Python
Protobuf. The required version is 5.29.4.
</p></li><li class="listitem"><p>
As a C Extension that interfaces with the MySQL C client
library. This implementation of the protocol is dependent on
the client library, but can use the library provided by MySQL
Server packages (see <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/c-api-implementations.html" target="_top">MySQL C API Implementations</a>).
</p></li></ul></div><p>
Neither implementation of the client/server protocol has any
third-party dependencies. However, if you need SSL support, verify
that your Python installation has been compiled using the
<a class="ulink" href="http://www.openssl.org/" target="_top">OpenSSL</a> libraries.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Support for distutils was removed in Connector/Python 8.0.32.
</p></div><p>
Python terminology regarding distributions:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<span class="bold"><strong>Built Distribution</strong></span>: A package
created in the native packaging format intended for a given
platform. It contains both sources and platform-independent
bytecode. Connector/Python binary distributions are built distributions.
</p></li><li class="listitem"><p>
<span class="bold"><strong>Source Distribution</strong></span>: A
distribution that contains only source files and is generally
platform independent.
</p></li></ul></div></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-installation"></a>Chapter 4 Connector/Python Installation</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#quick-installation-guide">4.1 Quick Installation Guide</a></span></dt><dt><span class="section"><a href="#differences-between-binary-and-source-distribution">4.2 Differences Between Binary And Source Distributions</a></span></dt><dt><span class="section"><a href="#connector-python-obtaining">4.3 Obtaining Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-installation-binary">4.4 Installing Connector/Python from a Binary Distribution</a></span></dt><dd><dl><dt><span class="section"><a href="#id1847">4.4.1 Installing Connector/Python with pip</a></span></dt><dt><span class="section"><a href="#installing-from-rpm">4.4.2 Installing by RPMs</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-installation-source">4.5 Installing Connector/Python from a Source Distribution</a></span></dt><dt><span class="section"><a href="#connector-python-verification">4.6 Verifying Your Connector/Python Installation</a></span></dt></dl></div><p>
Connector/Python runs on any platform where Python is installed. Make sure
Python is installed on your platform:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Python comes preinstalled on most Unix and Unix-like systems,
such as Linux, macOS, and FreeBSD. If your system does not have
Python preinstalled for some reasons, use its software
management system to install it.
</p></li><li class="listitem"><p>
For Microsoft Windows, a Python installer is available at the
<a class="ulink" href="http://python.org/download/" target="_top">Python
Download website</a> or via the Microsoft Store.
</p></li></ul></div><p>
Also make sure Python in your system path.
</p><p>
Connector/Python includes the classic and X DevAPI APIs, which are
installed separately. Each can be installed by a binary or source
distribution.
</p><p>
Binaries of Connector/Python are distributed in the
<a class="ulink" href="https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/8/html/packaging_and_distributing_software/introduction-to-rpm_packaging-and-distributing-software" target="_top">RPM</a>
and the
<a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-wheel" target="_top">wheel</a>
package formats. The source code, on the other hand, is distributed
as a compressed archive of source files, from which a wheel package
can be built.
</p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="quick-installation-guide"></a>4.1 Quick Installation Guide</h2></div></div></div><p>
The recommended way to install Connector/Python is by
<a class="ulink" href="https://pip.pypa.io/en/stable/" target="_top">pip</a> and wheel
packages. If your system does not have <code class="literal">pip</code>, you
can install it with your system's software manager, or with a
<a class="ulink" href="https://pip.pypa.io/en/latest/installation/" target="_top">standalone
pip installer</a>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
You are strongly recommended to use the latest version of
<code class="literal">pip</code> to install Connector/Python. Upgrade your
<code class="literal">pip</code> version if needed.
</p></div><p>
Install the Connector/Python interfaces for the classic MySQL
protocol and the X Protocol, respectively, with the following
commands.
</p><pre class="programlisting"># classic API
$ pip install mysql-connector-python
# X DevAPI
$ pip install mysqlx-connector-python
</pre><p>
Refer to the
<a class="ulink" href="https://dev.mysql.com/doc/dev/connector-python/installation.html" target="_top">installation
tutorial</a> for alternate means to install X DevAPI.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="differences-between-binary-and-source-distribution"></a>4.2 Differences Between Binary And Source Distributions</h2></div></div></div><p>
Installing from a
<a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-wheel" target="_top">wheel</a>
(<code class="literal">bdist</code> package) is the recommended, except for
Enterprise Linux systems, on which the RPM-based installation
method may be preferred.
</p><p>
Wheels can be directly and easily installed without an extra build
step. However, a wheel package is often specific to a particular
platform and Python version, so there may be cases in which
<code class="literal">pip</code> cannot find a suitable wheel package based
on your platform or your Python version. When that happens, you
can get the
<a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-source-distribution" target="_top">source
distribution</a> (<code class="literal">sdist</code>) and produce a
wheel package from it for installing Connector/Python.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Creating a wheel package from an <code class="literal">sdist</code> may
fail for some older Python version, as the Connector/Python
source code is only compatible with a specific subset of Python
versions.
</p></div><p>
In summary, the recommendation is to use a
<code class="literal">bdist</code> unless <code class="literal">pip</code> cannot find
a suitable wheel package for your setup, or if you need to custom
build a wheel package for some special reasons.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-obtaining"></a>4.3 Obtaining Connector/Python</h2></div></div></div><p>
Using <span class="command"><strong>pip</strong></span> is the preferred method to obtain,
install, and upgrade Connector/Python. For alternatives, see the
<a class="ulink" href="https://dev.mysql.com/downloads/connector/python/" target="_top">Connector/Python download
site</a>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
The <code class="literal">mysql-connector-python</code> package installs
an interface to the classic MySQL protocol. The X DevAPI is
available by its own <code class="literal">mysqlx-connector-python</code>
package. Prior to Connector/Python 8.3.0,
<code class="literal">mysql-connector-python</code> installed interfaces
to both the X and classic protocols.
</p></div><p>
Most Linux installation packages (except RPMs for Enterprise
Linux) are no longer available from Oracle since Connector/Python
9.0.0. Using <code class="literal">pip</code> to manage Connector/Python on
those Linux distributions is recommended.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-installation-binary"></a>4.4 Installing Connector/Python from a Binary Distribution</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#id1847">4.4.1 Installing Connector/Python with pip</a></span></dt><dt><span class="section"><a href="#installing-from-rpm">4.4.2 Installing by RPMs</a></span></dt></dl></div><p>
Connector/Python includes the classic and X DevAPI connector APIs,
which are installed separately. Each can be installed by a binary
distribution.
</p><p>
Binaries are distributed in the
<a class="ulink" href="https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/8/html/packaging_and_distributing_software/introduction-to-rpm_packaging-and-distributing-software" target="_top">RPM</a>
and the
<a class="ulink" href="https://packaging.python.org/en/latest/discussions/package-formats/#what-is-a-wheel" target="_top">wheel</a>
package formats.
</p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="id1847"></a>4.4.1 Installing Connector/Python with pip</h3></div></div></div><p>
Installation via <span class="command"><strong>pip</strong></span> is supported on Windows,
macOS, and Linux platforms.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
For macOS platforms, DMG installer packages were available for
Connector/Python 8.0 and earlier.
</p></div><p>
Use <span class="command"><strong>pip</strong></span> to install and upgrade Connector/Python:
</p><pre data-lang="terminal" class="programlisting"># Installation
$> pip install mysql-connector-python
# Upgrade
$> pip install mysql-connector-python --upgrade
# Optionally, install X DevAPI
$> pip install mysqlx-connector-python
# Upgrade X DevAPI
$> pip install mysqlx-connector-python --upgrade
</pre><p>
In case the wheel package you want to install is found in your
local file system (for example, you produced a wheel package
from a source distribution or downloaded it from somewhere), you
can install it as follows:
</p><pre data-lang="css" class="programlisting"># Installation
$ pip install <em class="replaceable"><code>/path/to/wheel/<wheel package name></code></em>.whl
</pre><h4><a name="id1859"></a>Installation of Optional Features</h4><p>
Installation from wheels allow you to install optional
dependencies to enable certain features with Connector/Python.
For example:
</p><pre class="programlisting"># 3rd party packages to enable the telemetry functionality are installed
$ pip install mysql-connector-python[telemetry]
</pre><p>
Similarly, for X DevAPI:
</p><pre class="programlisting"># 3rd party packages to enable the compression functionality are installed
$ pip install mysqlx-connector-python[compression]
</pre><p>
These installation options are shortcuts to install all the
dependencies needed by some particular features (they are only
for your convenience, and you can always install the required
dependencies for a feature by yourself):
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
For the classic protocol:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
dns-srv
</p></li><li class="listitem"><p>
gssapi
</p></li><li class="listitem"><p>
fido2
</p></li><li class="listitem"><p>
telemetry
</p></li></ul></div></li><li class="listitem"><p>
For X Protocol:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
dns-srv
</p></li><li class="listitem"><p>
compression
</p></li></ul></div></li></ul></div><p>
You can specify a multiple of these options in your installation
command, for example:
</p><pre class="programlisting">$ pip install mysql-connector-python[telemetry,dns-srv,<em class="replaceable"><code>...</code></em>]</pre><p>
Or, if are installing a wheel package from your local file
system:
</p><pre class="programlisting">$ pip install <em class="replaceable"><code>/path/to/wheel/<wheel package name></code></em>.whl[telemetry,dns-srv,<em class="replaceable"><code>...</code></em>] </pre><p>
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="installing-from-rpm"></a>4.4.2 Installing by RPMs</h3></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#using-the-mysql-yum-repository">4.4.2.1 Using the MySQL Yum Repository</a></span></dt><dt><span class="section"><a href="#using-an-rpm-package">4.4.2.2 Using an RPM Package</a></span></dt></dl></div><p>
Installation by RPMs is only supported on RedHat Enterprise
Linux and Oracle Linux, and is performed using the MySQL Yum
Repository or by using RPM packages downloaded directly from
Oracle.
</p><div class="section"><div class="titlepage"><div><div><h4 class="title"><a name="using-the-mysql-yum-repository"></a>4.4.2.1 Using the MySQL Yum Repository</h4></div></div></div><p>
RedHat Enterprise Linux and Oracle Linux platforms can install
Connector/Python using the MySQL Yum repository (see
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/linux-installation-yum-repo.html#yum-repo-setup" target="_top">Adding
the MySQL Yum Repository</a> and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/linux-installation-yum-repo.html#yum-install-components" target="_top">Installing
Additional MySQL Products and Components with Yum</a>).
</p><h5><a name="id1898"></a>Prerequisites</h5><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<span class="emphasis"><em>For installing X DevAPI only:</em></span>Because
the required <code class="literal">python3-protobuf</code> RPM
package is not available for Python 3.8 on the RedHat
Enterprise Linux and Oracle Linux platforms, it has to be
manually installed with, for example, <code class="literal">pip install
protobuf</code>. This is required for Connector/Python
8.0.29 or later.
</p></li><li class="listitem"><p>
The <code class="literal">mysql-community-client-plugins</code>
package is required for using robust authentication
methods like <code class="literal">caching_sha2_password</code>,
which is the default authentication method for MySQL 8.0
and later. Install it using the Yum repository
</p><pre class="programlisting"> $ sudo yum install mysql-community-client-plugins
</pre></li></ul></div><h5><a name="id1910"></a>Installation</h5><p>
Use the following commands to install Connector/Python:
</p><pre class="programlisting">$ sudo yum install mysql-connector-python
# Optionally, install also X DevAPI
$ sudo yum install mysqlx-connector-python
</pre></div><div class="section"><div class="titlepage"><div><div><h4 class="title"><a name="using-an-rpm-package"></a>4.4.2.2 Using an RPM Package</h4></div></div></div><p>
Connector/Python RPM packages (<code class="literal">.rpm</code> files)
are available from the
<a class="ulink" href="https://dev.mysql.com/downloads/connector/python/" target="_top">Connector/Python
download site</a>.
</p><p>
You can verify the integrity and authenticity of the RPM
packages before installing them. To learn more, see
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.4/en/verifying-package-integrity.html" target="_top">Verifying
Package Integrity Using MD5 Checksums or GnuPG</a>.
</p><h5><a name="id1920"></a>Prerequisites</h5><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<span class="emphasis"><em>For installing X DevAPI only:</em></span>Because
the required <code class="literal">python3-protobuf</code> RPM
package is not available for Python 3.8 on the RedHat
Enterprise Linux and Oracle Linux platforms, it has to be
manually installed with, for example, <code class="literal">pip install
protobuf</code>. This is required for Connector/Python
8.0.29 or later.
</p></li><li class="listitem"><p>
The <code class="literal">mysql-community-client-plugins</code>
package is required for using robust authentication
methods like <code class="literal">caching_sha2_password</code>,
which is the default authentication method for MySQL 8.0
and later.
</p><pre class="programlisting"> $ rpm -i mysql-community-client-plugins-<em class="replaceable"><code>ver</code></em>.<em class="replaceable"><code>distro</code></em>.<em class="replaceable"><code>architecture</code></em>.rpm</pre></li></ul></div><h5><a name="id1935"></a>Installation</h5><p>
To install Connector/Python using the downloaded RPM packages:
</p><pre class="programlisting">$ rpm -i mysql-connector-python-<em class="replaceable"><code>ver</code></em>.<em class="replaceable"><code>distro</code></em>.<em class="replaceable"><code>architecture</code></em>.rpm
# Optionally, install X DevAPI
$ rpm -i mysqlx-connector-python-<em class="replaceable"><code>ver</code></em>.<em class="replaceable"><code>distro</code></em>.<em class="replaceable"><code>architecture</code></em>.rpm
</pre></div></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-installation-source"></a>4.5 Installing Connector/Python from a Source Distribution</h2></div></div></div><p>
The Connector/Python source distribution is platform independent, and is
packaged in the compressed <code class="literal">tar</code> archive format
(<code class="filename">.tar.gz</code> file). See
<a class="link" href="#connector-python-obtaining" title="4.3 Obtaining Connector/Python">Obtaining
Connector/Python</a>) on how to download them.
</p><h3><a name="id1950"></a>Prerequisites for Compiling Connector/Python with the C Extension</h3><p>
Source distributions include the C Extension that interfaces with
the MySQL C client library. <span class="emphasis"><em>You can build the
distribution with or without support for this
extension.</em></span> To build Connector/Python with support for the C
Extension, the following prerequisites must be satisfied:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Compiling tools:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p>
<span class="emphasis"><em>For Linux platforms:</em></span> A C/C++
compiler, such as <span class="command"><strong>gcc</strong></span>.
</p></li><li class="listitem"><p>
<span class="emphasis"><em>For Windows platforms:</em></span> Current
version of Visual Studio.
</p></li></ul></div></li><li class="listitem"><p>
Python development files.
</p></li><li class="listitem"><p>
<span class="emphasis"><em>For installing the classic interface
only:</em></span> MySQL Server binaries (server may be
installed or not installed on the system), including
development files (to obtain the MySQL Server binaries, visit
the
<a class="ulink" href="https://dev.mysql.com/downloads/" target="_top">MySQL
download site</a>).
</p></li><li class="listitem"><p>
<span class="emphasis"><em>For installing the X DevAPI interface only:</em></span> Protobuf C++ (version
<code class="code">5.29.4</code>). </p></li></ul></div><h3><a name="id1974"></a>Installing Connector/Python from Source Code Using
<code class="literal">pip</code></h3><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
We recommend leveraging
<a class="ulink" href="https://docs.python.org/3/tutorial/venv.html" target="_top">python
virtual environments</a> to encapsulate the package
installation instead of installing packages directly into the
Python system environment.
</p></div><p>
<span class="bold"><strong>For installing the classic
interface:</strong></span>
</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
Download the latest version of the <code class="literal">sdist</code> of
Connector/Python for the classic MySQL protocol, whose name is
in the format of
<code class="code">mysql_connector_python-x.y.z.tar.gz</code>.
</p></li><li class="listitem"><p>
<span class="emphasis"><em>Optional: To include the C Extension</em></span>, use
these steps to provide the path to the installation directory
of MySQL Server (or to the folder where the server binaries
are located) with the <code class="literal">MYSQL_CAPI</code> system
variable before running the installation step. On Linux
platforms:
</p><pre class="programlisting"> $ export MYSQL_CAPI=<path to server binaries>
</pre><p>
On Windows platforms:
</p><pre class="programlisting"> > $env:MYSQL_CAPI=<path to server binaries>
</pre><p>
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
It is not required that the server is actually installed
on the system; for compiling the C-extension, the presence
of libraries are sufficient
</p></div><p>
</p></li><li class="listitem"><p>
Perform the installation using this command:
</p><pre class="programlisting"> pip install ./mysql_connector_python-x.y.z.tar.gz</pre><div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Warning</div><p>
DO NOT use <code class="literal">mysql-connector-python</code> instead
of <code class="literal">./mysql_connector_python-x.y.z.tar.gz</code>,
as the former will install the WHEEL package from the PyPI
repository, and the latter will install the local WHEEL that
is compiled from the source code.
</p></div></li></ol></div><p>
<span class="bold"><strong>For installing X DevAPI:</strong></span>
</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
Download the latest version of the <code class="literal">sdist</code> of
Connector/Python for the MySQL X Protocol, whose name is in
the format of
<code class="code">mysqlx_connector_python-x.y.z.tar.gz</code>.
</p></li><li class="listitem"><p>
<span class="emphasis"><em>Optional: To include the Protobuf
C-Extension,</em></span> use these commands on Linux platforms
to provide the paths to the Protobuf folders by the
<code class="literal">MYSQLXPB_*</code> system variables before the
installation step:
</p><pre class="programlisting"> $ export MYSQLXPB_PROTOBUF=<em class="replaceable"><code><path to protobuf binaries></code></em>
$ export MYSQLXPB_PROTOBUF_INCLUDE_DIR="${MYSQLXPB_PROTOBUF}/include"
$ export MYSQLXPB_PROTOBUF_LIB_DIR="${MYSQLXPB_PROTOBUF}/lib"
$ export MYSQLXPB_PROTOC="${MYSQLXPB_PROTOBUF}/bin/protoc"
</pre><p>
Or these commands on Windows platforms:
</p><pre class="programlisting"> > $env:PROTOBUF=<em class="replaceable"><code><path to protobuf binaries></code></em>
> $env:PROTOBUF_INCLUDE_DIR=$env:PROTOBUF+"\include"
> $env:PROTOBUF_LIB_DIR=$env:PROTOBUF+"\lib"
> $env:PROTOC=$env:PROTOBUF+"\bin\protoc.exe"
</pre></li><li class="listitem"><p>
Perform the installation using this command:
</p><pre class="programlisting"> pip install ./mysqlx_connector_python-x.y.z.tar.gz</pre><div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Warning</div><p>
DO NOT use <code class="literal">mysqlx-connector-python</code>
instead of
<code class="literal">./mysqlx_connector_python-x.y.z.tar.gz</code>,
as the former will install the WHEEL package from the PyPI
repository, and the latter will install the local WHEEL that
is compiled from the source code.
</p></div></li></ol></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-verification"></a>4.6 Verifying Your Connector/Python Installation</h2></div></div></div><h3><a name="verify-installation-pip"></a>Verifying Installations by <code class="literal">pip</code></h3><p>
To verify that a Connector/Python package has been installed
successfully using <code class="literal">pip</code>, use the following
command:
</p><pre class="programlisting">$ pip install list
</pre><p>
If you have installed the classic interface, you should see an
output similar to the following:
</p><pre class="programlisting">Package Version
---------------------------------------- ----------
... ...
mysql-connector-python x.y.z
... ...
</pre><p>
If you have installed X DevAPI, you should see an output similar
to the following:
</p><pre class="programlisting">Package Version
---------------------------------------- ----------
... ...
mysqlx-connector-python x.y.z
...
</pre><h3><a name="verify-installation-rpm"></a>Installed from an RPM</h3><p>
The default Connector/Python installation location is
<code class="filename">/<em class="replaceable"><code>prefix</code></em>/python<em class="replaceable"><code>X.Y</code></em>/site-packages/</code>,
where <em class="replaceable"><code>prefix</code></em> is the location where
Python is installed and <em class="replaceable"><code>X.Y</code></em> is the
Python version.
</p><p>
The C Extension is installed as
<code class="filename">_mysql_connector.so</code> and
<code class="filename">_mysqlxpb.so</code> in the
<code class="filename">site-packages</code> directory, not in the
<code class="filename">mysql/connector</code> and
<code class="filename">mysqlx</code> directories for the classic interface
and X DevAPI, respectively.
</p><h3><a name="verify-installation-c-extension"></a>Verify the C-extension</h3><p>
To verify the C-extension of the classic package is available, run
this command:
</p><pre class="programlisting">$ python -c "import mysql.connector; assert mysql.connector.HAVE_CEXT; print(f'C-ext is {mysql.connector.HAVE_CEXT}')"
</pre><p>
If no error is returned, the C-extension has been correctly built
and installed.
</p><p>
Similarly, to verify the C-extension of the X DevAPI package is
available, run this command and see if it returns any errors:
</p><pre class="programlisting">$ python -c "import mysqlx; assert mysqlx.protobuf.HAVE_MYSQLXPB_CEXT; print(f'C-ext is {mysqlx.protobuf.HAVE_MYSQLXPB_CEXT}')"
</pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-examples"></a>Chapter 5 Connector/Python Coding Examples</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-example-connecting">5.1 Connecting to MySQL Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-ddl">5.2 Creating Tables Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-transaction">5.3 Inserting Data Using Connector/Python</a></span></dt><dt><span class="section"><a href="#connector-python-example-cursor-select">5.4 Querying Data Using Connector/Python</a></span></dt></dl></div><p>
These coding examples illustrate how to develop Python applications
and scripts which connect to MySQL Server using MySQL Connector/Python.
</p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-connecting"></a>5.1 Connecting to MySQL Using Connector/Python</h2></div></div></div><p>
The <code class="literal">connect()</code> constructor creates a connection
to the MySQL server and returns a
<code class="literal">MySQLConnection</code> object.
</p><p>
The following example shows how to connect to the MySQL server:
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
host='127.0.0.1',
database='employees')
cnx.close()
</pre><p>
<a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a> describes the
permitted connection arguments.
</p><p>
It is also possible to create connection objects using the
<a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">connection.MySQLConnection()</a>
class:
</p><pre data-lang="python" class="programlisting">from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='scott', password='<em class="replaceable"><code>password</code></em>',
host='127.0.0.1',
database='employees')
cnx.close()
</pre><p>
Both forms (either using the <code class="literal">connect()</code>
constructor or the class directly) are valid and functionally
equal, but using <code class="literal">connect()</code> is preferred and
used by most examples in this manual.
</p><p>
To handle connection errors, use the <code class="literal">try</code>
statement and catch all errors using the
<a class="link" href="#connector-python-api-errors-error" title="10.12.2 errors.Error Exception">errors.Error</a>
exception:
</p><pre data-lang="python" class="programlisting">import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(user='scott',
database='employ')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
</pre><p>
Defining connection arguments in a dictionary and using the
<code class="literal">**</code> operator is another option:
</p><pre data-lang="python" class="programlisting">import mysql.connector
config = {
'user': 'scott',
'password': '<em class="replaceable"><code>password</code></em>',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True
}
cnx = mysql.connector.connect(**config)
cnx.close()
</pre><p>
Defining Logger options, a reconnection routine, and defined as a
connection method named connect_to_mysql:
</p><pre data-lang="python" class="programlisting">
import logging
import time
import mysql.connector
# Set up logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# Log to console
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
# Also log to a file
file_handler = logging.FileHandler("cpy-errors.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
def connect_to_mysql(config, attempts=3, delay=2):
attempt = 1
# Implement a reconnection routine
while attempt < attempts + 1:
try:
return mysql.connector.connect(**config)
except (mysql.connector.Error, IOError) as err:
if (attempts is attempt):
# Attempts to reconnect failed; returning None
logger.info("Failed to connect, exiting without a connection: %s", err)
return None
logger.info(
"Connection failed: %s. Retrying (%d/%d)...",
err,
attempt,
attempts-1,
)
# progressive reconnect delay
time.sleep(delay ** attempt)
attempt += 1
return None
</pre><p>
Connecting and using the Sakila database using the above routine,
assuming it's defined in a file named
<code class="filename">myconnection.py</code>:
</p><pre data-lang="python" class="programlisting">
from myconnection import connect_to_mysql
config = {
"host": "127.0.0.1",
"user": "user",
"password": "pass",
"database": "sakila",
}
cnx = connect_to_mysql(config, attempts=3)
if cnx and cnx.is_connected():
with cnx.cursor() as cursor:
result = cursor.execute("SELECT * FROM actor LIMIT 5")
rows = cursor.fetchall()
for rows in rows:
print(rows)
cnx.close()
else:
print("Could not connect")
</pre><h3><a name="id2089"></a>Using the Connector/Python Python or C Extension</h3><p>
Connector/Python offers two implementations: a pure Python interface and a C
extension that uses the MySQL C client library (see
<a class="xref" href="#connector-python-cext" title="Chapter 8 The Connector/Python C Extension">Chapter 8, <i>The Connector/Python C Extension</i></a>). This can be configured
at runtime using the <code class="literal">use_pure</code> connection
argument. It defaults to <code class="literal">False</code> as of MySQL 8,
meaning the C extension is used. If the C extension is not
available on the system then <code class="literal">use_pure</code> defaults
to <code class="literal">True</code>. Setting
<code class="literal">use_pure=False</code> causes the connection to use the
C Extension if your Connector/Python installation includes it, while
<code class="literal">use_pure=True</code> to <code class="literal">False</code> means
the Python implementation is used if available.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
The <code class="literal">use_pure</code> option and C extension were
added in Connector/Python 2.1.1.
</p></div><p>
The following example shows how to set <code class="literal">use_pure</code>
to False.
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
host='127.0.0.1',
database='employees',
use_pure=False)
cnx.close()
</pre><p>
It is also possible to use the C Extension directly by importing
the <code class="literal">_mysql_connector</code> module rather than the
<code class="literal">mysql.connector</code> module. For more information,
see <a class="xref" href="#connector-python-cext-module" title="8.2 The _mysql_connector C Extension Module">Section 8.2, “The _mysql_connector C Extension Module”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-ddl"></a>5.2 Creating Tables Using Connector/Python</h2></div></div></div><p>
All <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_ddl" target="_top">DDL</a> (Data Definition Language)
statements are executed using a handle structure known as a
cursor. The following examples show how to create the tables of
the
<a class="ulink" href="http://dev.mysql.com/doc/employee/en/index.html" target="_top">Employee
Sample Database</a>. You need them for the other examples.
</p><p>
In a MySQL server, tables are very long-lived objects, and are
often accessed by multiple applications written in different
languages. You might typically work with tables that are already
set up, rather than creating them within your own application.
Avoid setting up and dropping tables over and over again, as that
is an expensive operation. The exception is
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_temporary_table" target="_top">temporary tables</a>,
which can be created and dropped quickly within an application.
</p><pre data-lang="python" class="programlisting">from __future__ import print_function
import mysql.connector
from mysql.connector import errorcode
DB_NAME = 'employees'
TABLES = {}
TABLES['employees'] = (
"CREATE TABLE `employees` ("
" `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
" `birth_date` date NOT NULL,"
" `first_name` varchar(14) NOT NULL,"
" `last_name` varchar(16) NOT NULL,"
" `gender` enum('M','F') NOT NULL,"
" `hire_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB")
TABLES['departments'] = (
"CREATE TABLE `departments` ("
" `dept_no` char(4) NOT NULL,"
" `dept_name` varchar(40) NOT NULL,"
" PRIMARY KEY (`dept_no`), UNIQUE KEY `dept_name` (`dept_name`)"
") ENGINE=InnoDB")
TABLES['salaries'] = (
"CREATE TABLE `salaries` ("
" `emp_no` int(11) NOT NULL,"
" `salary` int(11) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`,`from_date`), KEY `emp_no` (`emp_no`),"
" CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`emp_no`) "
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
TABLES['dept_emp'] = (
"CREATE TABLE `dept_emp` ("
" `emp_no` int(11) NOT NULL,"
" `dept_no` char(4) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`,`dept_no`), KEY `emp_no` (`emp_no`),"
" KEY `dept_no` (`dept_no`),"
" CONSTRAINT `dept_emp_ibfk_1` FOREIGN KEY (`emp_no`) "
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
" CONSTRAINT `dept_emp_ibfk_2` FOREIGN KEY (`dept_no`) "
" REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
TABLES['dept_manager'] = (
" CREATE TABLE `dept_manager` ("
" `emp_no` int(11) NOT NULL,"
" `dept_no` char(4) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`,`dept_no`),"
" KEY `emp_no` (`emp_no`),"
" KEY `dept_no` (`dept_no`),"
" CONSTRAINT `dept_manager_ibfk_1` FOREIGN KEY (`emp_no`) "
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
" CONSTRAINT `dept_manager_ibfk_2` FOREIGN KEY (`dept_no`) "
" REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
TABLES['titles'] = (
"CREATE TABLE `titles` ("
" `emp_no` int(11) NOT NULL,"
" `title` varchar(50) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date DEFAULT NULL,"
" PRIMARY KEY (`emp_no`,`title`,`from_date`), KEY `emp_no` (`emp_no`),"
" CONSTRAINT `titles_ibfk_1` FOREIGN KEY (`emp_no`)"
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
</pre><p>
The preceding code shows how we are storing the
<code class="literal">CREATE</code> statements in a Python dictionary called
<code class="literal">TABLES</code>. We also define the database in a global
variable called <code class="literal">DB_NAME</code>, which enables you to
easily use a different schema.
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='scott')
cursor = cnx.cursor()
</pre><p>
A single MySQL server can manage multiple
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_database" target="_top">databases</a>. Typically, you
specify the database to switch to when connecting to the MySQL
server. This example does not connect to the database upon
connection, so that it can make sure the database exists, and
create it if not:
</p><pre data-lang="python" class="programlisting">def create_database(cursor):
try:
cursor.execute(
"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
exit(1)
try:
cursor.execute("USE {}".format(DB_NAME))
except mysql.connector.Error as err:
print("Database {} does not exists.".format(DB_NAME))
if err.errno == errorcode.ER_BAD_DB_ERROR:
create_database(cursor)
print("Database {} created successfully.".format(DB_NAME))
cnx.database = DB_NAME
else:
print(err)
exit(1)
</pre><p>
We first try to change to a particular database using the
<code class="literal">database</code> property of the connection object
<code class="literal">cnx</code>. If there is an error, we examine the error
number to check if the database does not exist. If so, we call the
<code class="literal">create_database</code> function to create it for us.
</p><p>
On any other error, the application exits and displays the error
message.
</p><p>
After we successfully create or change to the target database, we
create the tables by iterating over the items of the
<code class="literal">TABLES</code> dictionary:
</p><pre data-lang="python" class="programlisting">for table_name in TABLES:
table_description = TABLES[table_name]
try:
print("Creating table {}: ".format(table_name), end='')
cursor.execute(table_description)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")
cursor.close()
cnx.close()
</pre><p>
To handle the error when the table already exists, we notify the
user that it was already there. Other errors are printed, but we
continue creating tables. (The example shows how to handle the
<span class="quote">“<span class="quote">table already exists</span>”</span> condition for illustration
purposes. In a real application, we would typically avoid the
error condition entirely by using the <code class="literal">IF NOT
EXISTS</code> clause of the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/create-table.html" target="_top"><code class="literal">CREATE
TABLE</code></a> statement.)
</p><p>
The output would be something like this:
</p><pre data-lang="none" class="programlisting">Database employees does not exists.
Database employees created successfully.
Creating table employees: OK
Creating table departments: already exists.
Creating table salaries: already exists.
Creating table dept_emp: OK
Creating table dept_manager: OK
Creating table titles: OK
</pre><p>
To populate the employees tables, use the dump files of the
<a class="ulink" href="http://dev.mysql.com/doc/employee/en/index.html" target="_top">Employee
Sample Database</a>. Note that you only need the data dump
files that you will find in an archive named like
<code class="literal">employees_db-dump-files-1.0.5.tar.bz2</code>. After
downloading the dump files, execute the following commands, adding
connection options to the <span class="command"><strong>mysql</strong></span> commands if
necessary:
</p><pre data-lang="terminal" class="programlisting">$> <strong class="userinput"><code>tar xzf employees_db-dump-files-1.0.5.tar.bz2</code></strong>
$> <strong class="userinput"><code>cd employees_db</code></strong>
$> <strong class="userinput"><code>mysql employees < load_employees.dump</code></strong>
$> <strong class="userinput"><code>mysql employees < load_titles.dump</code></strong>
$> <strong class="userinput"><code>mysql employees < load_departments.dump</code></strong>
$> <strong class="userinput"><code>mysql employees < load_salaries.dump</code></strong>
$> <strong class="userinput"><code>mysql employees < load_dept_emp.dump</code></strong>
$> <strong class="userinput"><code>mysql employees < load_dept_manager.dump</code></strong>
</pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-cursor-transaction"></a>5.3 Inserting Data Using Connector/Python</h2></div></div></div><p>
Inserting or updating data is also done using the handler
structure known as a cursor. When you use a transactional storage
engine such as <code class="literal">InnoDB</code> (the default in MySQL 5.5
and higher), you must <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_commit" target="_top">commit</a>
the data after a sequence of
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a>,
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/delete.html" target="_top"><code class="literal">DELETE</code></a>, and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a> statements.
</p><p>
This example shows how to insert new data. The second
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> depends on the value of the
newly created <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_primary_key" target="_top">primary key</a>
of the first. The example also demonstrates how to use extended
formats. The task is to add a new employee starting to work
tomorrow with a salary set to 50000.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
The following example uses tables created in the example
<a class="xref" href="#connector-python-example-ddl" title="5.2 Creating Tables Using Connector/Python">Section 5.2, “Creating Tables Using Connector/Python”</a>. The
<code class="literal">AUTO_INCREMENT</code> column option for the primary
key of the <code class="literal">employees</code> table is important to
ensure reliable, easily searchable data.
</p></div><pre data-lang="python" class="programlisting">from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
tomorrow = datetime.now().date() + timedelta(days=1)
add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid
# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)
# Make sure data is committed to the database
cnx.commit()
cursor.close()
cnx.close()
</pre><p>
We first open a connection to the MySQL server and store the
<a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">connection
object</a> in the variable <code class="literal">cnx</code>. We then
create a new cursor, by default a
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
object, using the connection's
<a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
method.
</p><p>
We could calculate tomorrow by calling a database function, but
for clarity we do it in Python using the
<code class="literal">datetime</code> module.
</p><p>
Both <code class="literal">INSERT</code> statements are stored in the
variables called <code class="literal">add_employee</code> and
<code class="literal">add_salary</code>. Note that the second
<code class="literal">INSERT</code> statement uses extended Python format
codes.
</p><p>
The information of the new employee is stored in the tuple
<code class="literal">data_employee</code>. The query to insert the new
employee is executed and we retrieve the newly inserted value for
the <code class="literal">emp_no</code> column (an
<code class="literal">AUTO_INCREMENT</code> column) using the
<code class="literal">lastrowid</code> property of the cursor object.
</p><p>
Next, we insert the new salary for the new employee, using the
<code class="literal">emp_no</code> variable in the dictionary holding the
data. This dictionary is passed to the
<code class="literal">execute()</code> method of the cursor object if an
error occurred.
</p><p>
Since by default Connector/Python turns
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_autocommit" target="_top">autocommit</a> off, and MySQL
5.5 and higher uses transactional <code class="literal">InnoDB</code> tables
by default, it is necessary to commit your changes using the
connection's <code class="literal">commit()</code> method. You could also
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_rollback" target="_top">roll back</a> using the
<code class="literal">rollback()</code> method.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-example-cursor-select"></a>5.4 Querying Data Using Connector/Python</h2></div></div></div><p>
The following example shows how to
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_query" target="_top">query</a> data using a cursor
created using the connection's
<a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
method. The data returned is formatted and printed on the console.
</p><p>
The task is to select all employees hired in the year 1999 and
print their names and hire dates to the console.
</p><pre data-lang="python" class="programlisting">import datetime
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()
</pre><p>
We first open a connection to the MySQL server and store the
<a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">connection
object</a> in the variable <code class="literal">cnx</code>. We then
create a new cursor, by default a
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
object, using the connection's
<a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
method.
</p><p>
In the preceding example, we store the <code class="literal">SELECT</code>
statement in the variable <code class="literal">query</code>. Note that we
are using unquoted <code class="literal">%s</code>-markers where dates
should have been. Connector/Python converts <code class="literal">hire_start</code> and
<code class="literal">hire_end</code> from Python types to a data type that
MySQL understands and adds the required quotes. In this case, it
replaces the first <code class="literal">%s</code> with
<code class="literal">'1999-01-01'</code>, and the second with
<code class="literal">'1999-12-31'</code>.
</p><p>
We then execute the operation stored in the
<code class="literal">query</code> variable using the
<a class="link" href="#connector-python-api-mysqlcursor-execute" title="10.5.7 MySQLCursor.execute() Method"><code class="literal">execute()</code></a>
method. The data used to replace the <code class="literal">%s</code>-markers
in the query is passed as a tuple: <code class="literal">(hire_start,
hire_end)</code>.
</p><p>
After executing the query, the MySQL server is ready to send the
data. The result set could be zero rows, one row, or 100 million
rows. Depending on the expected volume, you can use different
techniques to process this result set. In this example, we use the
<code class="literal">cursor</code> object as an iterator. The first column
in the row is stored in the variable
<code class="literal">first_name</code>, the second in
<code class="literal">last_name</code>, and the third in
<code class="literal">hire_date</code>.
</p><p>
We print the result, formatting the output using Python's built-in
<code class="literal">format()</code> function. Note that
<code class="literal">hire_date</code> was converted automatically by Connector/Python
to a Python <code class="literal">datetime.date</code> object. This means
that we can easily format the date in a more human-readable form.
</p><p>
The output should be something like this:
</p><pre data-lang="none" class="programlisting">..
Wilharm, LiMin was hired on 16 Dec 1999
Wielonsky, Lalit was hired on 16 Dec 1999
Kamble, Dannz was hired on 18 Dec 1999
DuBourdieux, Zhongwei was hired on 19 Dec 1999
Fujisawa, Rosita was hired on 20 Dec 1999
..
</pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-tutorials"></a>Chapter 6 Connector/Python Tutorials</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-tutorial-cursorbuffered">6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor</a></span></dt></dl></div><p>
These tutorials illustrate how to develop Python applications and
scripts that connect to a MySQL database server using MySQL Connector/Python.
</p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-tutorial-cursorbuffered"></a>6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor</h2></div></div></div><p>
The following example script gives a long-overdue 15% raise
effective tomorrow to all employees who joined in the year 2000
and are still with the company.
</p><p>
To iterate through the selected employees, we use buffered
cursors. (A buffered cursor fetches and buffers the rows of a
result set after executing a query; see
<a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.) This
way, it is unnecessary to fetch the rows in a new variables.
Instead, the cursor can be used as an iterator.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
This script is an example; there are other ways of doing this
simple task.
</p></div><pre data-lang="python" class="programlisting">from __future__ import print_function
from decimal import Decimal
from datetime import datetime, date, timedelta
import mysql.connector
# Connect with the MySQL Server
cnx = mysql.connector.connect(user='scott', database='employees')
# Get two buffered cursors
curA = cnx.cursor(buffered=True)
curB = cnx.cursor(buffered=True)
# Query to get employees who joined in a period defined by two dates
query = (
"SELECT s.emp_no, salary, from_date, to_date FROM employees AS e "
"LEFT JOIN salaries AS s USING (emp_no) "
"WHERE to_date = DATE('9999-01-01')"
"AND e.hire_date BETWEEN DATE(%s) AND DATE(%s)")
# UPDATE and INSERT statements for the old and new salary
update_old_salary = (
"UPDATE salaries SET to_date = %s "
"WHERE emp_no = %s AND from_date = %s")
insert_new_salary = (
"INSERT INTO salaries (emp_no, from_date, to_date, salary) "
"VALUES (%s, %s, %s, %s)")
# Select the employees getting a raise
curA.execute(query, (date(2000, 1, 1), date(2000, 12, 31)))
# Iterate through the result of curA
for (emp_no, salary, from_date, to_date) in curA:
# Update the old and insert the new salary
new_salary = int(round(salary * Decimal('1.15')))
curB.execute(update_old_salary, (tomorrow, emp_no, from_date))
curB.execute(insert_new_salary,
(emp_no, tomorrow, date(9999, 1, 1,), new_salary))
# Commit the changes
cnx.commit()
cnx.close()
</pre></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-connecting"></a>Chapter 7 Connector/Python Connection Establishment</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-connectargs">7.1 Connector/Python Connection Arguments</a></span></dt><dt><span class="section"><a href="#connector-python-option-files">7.2 Connector/Python Option-File Support</a></span></dt></dl></div><p>
Connector/Python provides a <code class="literal">connect()</code> call used to establish
connections to the MySQL server. The following sections describe the
permitted arguments for <code class="literal">connect()</code> and describe
how to use option files that supply additional arguments.
</p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-connectargs"></a>7.1 Connector/Python Connection Arguments</h2></div></div></div><p>
A connection with the MySQL server can be established using either
the <code class="literal">mysql.connector.connect()</code> function or the
<code class="literal">mysql.connector.MySQLConnection()</code> class:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='joe', database='test')
cnx = MySQLConnection(user='joe', database='test')
</pre><p>
The following table describes the arguments that can be used to
initiate a connection. An asterisk (*) following an argument
indicates a synonymous argument name, available only for
compatibility with other Python MySQL drivers. Oracle recommends
not to use these alternative names.
</p><div class="table"><a name="connector-python-connectargs-listing"></a><p class="title"><b>Table 7.1 Connection Arguments for Connector/Python</b></p><div class="table-contents"><table><col width="30%"><col width="15%"><col width="55%"><thead><tr>
<th scope="col">Argument Name</th>
<th scope="col">Default</th>
<th scope="col">Description</th>
</tr></thead><tbody><tr>
<th scope="row"><code class="literal">user</code> (<code class="literal">username</code>*)</th>
<td></td>
<td>The user name used to authenticate with the MySQL server.</td>
</tr><tr>
<th scope="row"><code class="literal">password</code> (<code class="literal">passwd</code>*)</th>
<td></td>
<td>The password to authenticate the user with the MySQL server.</td>
</tr><tr>
<th scope="row"><code class="literal">password1</code>, <code class="literal">password2</code>, and
<code class="literal">password3</code></th>
<td></td>
<td>For Multi-Factor Authentication (MFA); <code class="option">password1</code> is an
alias for <code class="option">password</code>. Added in 8.0.28.</td>
</tr><tr>
<th scope="row"><code class="literal">database</code> (<code class="literal">db</code>*)</th>
<td></td>
<td>The database name to use when connecting with the MySQL server.</td>
</tr><tr>
<th scope="row"><code class="literal">host</code></th>
<td>127.0.0.1</td>
<td>The host name or IP address of the MySQL server.</td>
</tr><tr>
<th scope="row"><code class="literal">unix_socket</code></th>
<td></td>
<td>The location of the Unix socket file.</td>
</tr><tr>
<th scope="row"><code class="literal">port</code></th>
<td>3306</td>
<td>The TCP/IP port of the MySQL server. Must be an integer.</td>
</tr><tr>
<th scope="row"><code class="literal">conn_attrs</code></th>
<td></td>
<td><p>
Standard
<code class="literal">performance_schema.session_connect_attrs</code>
values are sent; use <code class="literal">conn_attrs</code> to
optionally set additional custom connection attributes as
defined by a dictionary such as
<span class="emphasis"><em>config['conn_attrs'] = {"foo":
"bar"}</em></span>.
</p><p>
The c-ext and pure python implementations differ. The
c-ext implementation depends on the mysqlclient library so
its standard conn_attrs values originate from it. For
example, '_client_name' is 'libmysql' with c-ext but
'mysql-connector-python' with pure python. C-ext adds
these additional attributes: '_connector_version',
'_connector_license', '_connector_name', and
'_source_host'.
</p><p>
This option was added in 8.0.17, as was the default
session_connect_attrs behavior.
</p></td>
</tr><tr>
<th scope="row"><code class="literal">init_command</code></th>
<td></td>
<td>Command (SQL query) executed immediately after the connection is
established as part of the initialization process. Added in
8.0.32.</td>
</tr><tr>
<th scope="row"><code class="literal">auth_plugin</code></th>
<td></td>
<td>Authentication plugin to use. Added in 1.2.1.</td>
</tr><tr id="connector-python-connectargs-listing-fido_callback">
<th scope="row"><code class="literal">fido_callback</code></th>
<td></td>
<td><p>
Deprecated as of 8.2.0 and removed in 8.4.0; instead use
<code class="option">webauthn_callback</code>.
</p><p>
A callable defined by the optional
<code class="literal">fido_callback</code> option is executed when
it's ready for user interaction with the hardware FIDO
device. This option can be a callable object or a string
path that the connector can import in runtime and execute.
It does not block and is only used to notify the user of
the need for interaction with the hardware FIDO device.
</p><p>
This functionality was only available in the C extension.
A <span class="emphasis"><em>NotSupportedError</em></span> was raised when
using the pure Python implementation.
</p></td>
</tr><tr id="connector-python-connectargs-listing-webauthn_callback">
<th scope="row"><code class="literal">webauthn_callback</code></th>
<td></td>
<td><p>
A callable defined by the optional
<code class="literal">webauthn_callback</code> option is executed
when it's ready for user interaction with the hardware
WebAuthn device. This option can be a callable object or a
string path that the connector can import in runtime and
execute. It does not block and is only used to notify the
user of the need for interaction with the hardware FIDO
device. Enable the
<code class="literal">authentication_webauthn_client</code>
auth_plugin in the connection configuration to use.
</p><p>
This option was added in 8.2.0, and it deprecated the
<code class="literal">fido_callback</code> option that was removed
in version 8.4.0.
</p></td>
</tr><tr>
<th scope="row"><code class="literal">openid_token_file</code></th>
<td></td>
<td>Path to the file containing the OpenID JWT formatted identity token.
Added in 9.1.0.</td>
</tr><tr>
<th scope="row"><code class="literal">use_unicode</code></th>
<td><code class="literal">True</code></td>
<td>Whether to use Unicode.</td>
</tr><tr>
<th scope="row"><code class="literal">charset</code></th>
<td><code class="literal">utf8mb4</code></td>
<td>Which MySQL character set to use.</td>
</tr><tr>
<th scope="row"><code class="literal">collation</code></th>
<td><code class="literal">utf8mb4_general_ai_ci</code> (is
<code class="literal">utf8_general_ci</code> in 2.x</td>
<td>Which MySQL collation to use. The 8.x default values are generated from
the latest MySQL Server 8.0 defaults.</td>
</tr><tr>
<th scope="row"><code class="literal">autocommit</code></th>
<td><code class="literal">False</code></td>
<td>Whether to <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_autocommit" target="_top">autocommit</a>
transactions.</td>
</tr><tr>
<th scope="row"><code class="literal">time_zone</code></th>
<td></td>
<td>Set the <code class="literal">time_zone</code> session variable at connection
time.</td>
</tr><tr>
<th scope="row"><code class="literal">sql_mode</code></th>
<td></td>
<td>Set the <code class="literal">sql_mode</code> session variable at connection time.</td>
</tr><tr>
<th scope="row"><code class="literal">get_warnings</code></th>
<td><code class="literal">False</code></td>
<td>Whether to fetch warnings.</td>
</tr><tr>
<th scope="row"><code class="literal">raise_on_warnings</code></th>
<td><code class="literal">False</code></td>
<td>Whether to raise an exception on warnings.</td>
</tr><tr>
<th scope="row"><code class="literal">connection_timeout</code>
(<code class="literal">connect_timeout</code>*)</th>
<td></td>
<td>Timeout for the TCP and Unix socket connections.</td>
</tr><tr>
<th scope="row"><code class="literal">read_timeout</code></th>
<td><code class="literal">None</code></td>
<td>Time limit to receive a response from the server before raising a
<code class="literal">ReadTimeoutError</code> level error. The default
value (None) sets the wait time to indefinitely. Option
added in 9.2.0.</td>
</tr><tr>
<th scope="row"><code class="literal">write_timeout</code></th>
<td><code class="literal">None</code></td>
<td>Time limit to send data to the server before raising a
<code class="literal">WriteTimeoutError</code> level error. The
default value (None) sets the wait time to indefinitely.
Option added in 9.2.0.</td>
</tr><tr>
<th scope="row"><code class="literal">client_flags</code></th>
<td></td>
<td>MySQL client flags.</td>
</tr><tr>
<th scope="row"><code class="literal">buffered</code></th>
<td><code class="literal">False</code></td>
<td>Whether cursor objects fetch the results immediately after executing
queries.</td>
</tr><tr>
<th scope="row"><code class="literal">raw</code></th>
<td><code class="literal">False</code></td>
<td>Whether MySQL results are returned as is, rather than converted to
Python types.</td>
</tr><tr>
<th scope="row"><code class="literal">consume_results</code></th>
<td>False</td>
<td>Whether to automatically read result sets.</td>
</tr><tr>
<th scope="row"><code class="literal">tls_versions</code></th>
<td>["TLSv1.2", "TLSv1.3"]</td>
<td>TLS versions to support; allowed versions are TLSv1.2 and TLSv1.3.
Versions TLSv1 and TLSv1.1 were removed in Connector/Python 8.0.28.</td>
</tr><tr>
<th scope="row"><code class="literal">ssl_ca</code></th>
<td></td>
<td>File containing the SSL certificate authority.</td>
</tr><tr>
<th scope="row"><code class="literal">ssl_cert</code></th>
<td></td>
<td>File containing the SSL certificate file.</td>
</tr><tr>
<th scope="row"><code class="literal">ssl_disabled</code></th>
<td><code class="literal">False</code></td>
<td><code class="literal">True</code> disables SSL/TLS usage. The TLSv1 and TLSv1.1
connection protocols are deprecated as of Connector/Python 8.0.26 and
removed as of Connector/Python 8.0.28.</td>
</tr><tr>
<th scope="row"><code class="literal">ssl_key</code></th>
<td></td>
<td>File containing the SSL key.</td>
</tr><tr>
<th scope="row"><code class="literal">ssl_verify_cert</code></th>
<td><code class="literal">False</code></td>
<td>When set to <code class="literal">True</code>, checks the server certificate
against the certificate file specified by the
<code class="literal">ssl_ca</code> option. Any mismatch causes a
<code class="literal">ValueError</code> exception.</td>
</tr><tr>
<th scope="row"><code class="literal">ssl_verify_identity</code></th>
<td><code class="literal">False</code></td>
<td>When set to <code class="literal">True</code>, additionally perform host name
identity verification by checking the host name that the
client uses for connecting to the server against the
identity in the certificate that the server sends to the
client. Option added in Connector/Python 8.0.14.</td>
</tr><tr>
<th scope="row"><code class="literal">force_ipv6</code></th>
<td><code class="literal">False</code></td>
<td>When set to <code class="literal">True</code>, uses IPv6 when an address resolves
to both IPv4 and IPv6. By default, IPv4 is used in such
cases.</td>
</tr><tr>
<th scope="row"><code class="literal">kerberos_auth_mode</code></th>
<td><code class="literal">SSPI</code></td>
<td>Windows-only, for choosing between SSPI and GSSAPI at runtime for the
<code class="literal">authentication_kerberos_client</code>
authentication plugin on Windows. Option added in Connector/Python
8.0.32.</td>
</tr><tr>
<th scope="row"><code class="literal">oci_config_file</code></th>
<td><code class="literal">""</code></td>
<td><p>
Optionally define a specific path to the
<code class="literal">authentication_oci</code> server-side
authentication configuration file. The profile name can be
configured with <code class="literal">oci_config_profile</code>.
</p><p>
The default file path on Linux and macOS is
<code class="literal">~/.oci/config</code>, and
<code class="literal">%HOMEDRIVE%%HOMEPATH%\.oci\config</code> on
Windows.
</p></td>
</tr><tr>
<th scope="row"><code class="literal">oci_config_profile</code></th>
<td><code class="literal">"DEFAULT"</code></td>
<td><p>
Used to specify a profile to use from the OCI
configuration file that contains the generated ephemeral
key pair and security token. The OCI configuration file
location can be defined by
<code class="literal">oci_config_file</code>. Option
<code class="literal">oci_config_profile</code> was added in Connector/Python
8.0.33.
</p></td>
</tr><tr>
<th scope="row"><code class="literal">dsn</code></th>
<td></td>
<td>Not supported (raises <code class="literal">NotSupportedError</code> when used).</td>
</tr><tr>
<th scope="row"><code class="literal">pool_name</code></th>
<td></td>
<td>Connection pool name. The pool name is restricted to alphanumeric
characters and the special characters <code class="literal">.</code>,
<code class="literal">_</code>, <code class="literal">*</code>,
<code class="literal">$</code>, and <code class="literal">#</code>. The pool
name must be no more than
<code class="literal">pooling.CNX_POOL_MAXNAMESIZE</code> characters
long (default 64).</td>
</tr><tr>
<th scope="row"><code class="literal">pool_size</code></th>
<td>5</td>
<td>Connection pool size. The pool size must be greater than 0 and less than
or equal to <code class="literal">pooling.CNX_POOL_MAXSIZE</code>
(default 32).</td>
</tr><tr>
<th scope="row"><code class="literal">pool_reset_session</code></th>
<td><code class="literal">True</code></td>
<td>Whether to reset session variables when connection is returned to pool.</td>
</tr><tr>
<th scope="row"><code class="literal">compress</code></th>
<td><code class="literal">False</code></td>
<td>Whether to use compressed client/server protocol.</td>
</tr><tr>
<th scope="row"><code class="literal">converter_class</code></th>
<td></td>
<td>Converter class to use.</td>
</tr><tr>
<th scope="row"><code class="literal">converter_str_fallback</code></th>
<td><code class="literal">False</code></td>
<td>Enable the conversion to str of value types not supported by the
Connector/Python converter class or by a custom converter
class.</td>
</tr><tr>
<th scope="row"><code class="literal">failover</code></th>
<td></td>
<td>Server failover sequence.</td>
</tr><tr>
<th scope="row"><code class="literal">option_files</code></th>
<td></td>
<td>Which option files to read. Added in 2.0.0.</td>
</tr><tr>
<th scope="row"><code class="literal">option_groups</code></th>
<td><code class="literal">['client', 'connector_python']</code></td>
<td>Which groups to read from option files. Added in 2.0.0.</td>
</tr><tr>
<th scope="row"><code class="literal">allow_local_infile</code></th>
<td><code class="literal">True</code></td>
<td>Whether to enable <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/load-data.html" target="_top"><code class="literal">LOAD DATA
LOCAL INFILE</code></a>. Added in 2.0.0.</td>
</tr><tr>
<th scope="row"><code class="literal">use_pure</code></th>
<td><code class="literal">False</code> as of 8.0.11, and <code class="literal">True</code> in
earlier versions. If only one implementation (C or Python)
is available, then then the default value is set to enable
the available implementation.</td>
<td>Whether to use pure Python or C Extension. If
<code class="literal">use_pure=False</code> and the C Extension is not
available, then Connector/Python will automatically fall
back to the pure Python implementation. Can be set with
<span class="emphasis"><em>mysql.connector.connect()</em></span> but not
<span class="emphasis"><em>MySQLConnection.connect()</em></span>. Added in
2.1.1.</td>
</tr><tr>
<th scope="row"><code class="literal">krb_service_principal</code></th>
<td>The "@realm" defaults to the default realm, as configured in the
<code class="filename">krb5.conf</code> file.</td>
<td>Must be a string in the form "primary/instance@realm" such as
"ldap/ldapauth@MYSQL.COM" where "@realm" is optional. Added
in 8.0.23.</td>
</tr></tbody></table></div></div><br class="table-break"><h3><a name="id2624"></a>MySQL Authentication Options</h3><p>
Authentication with MySQL typically uses a
<code class="literal">username</code> and <code class="literal">password</code>.
</p><p>
When the <code class="literal">database</code> argument is given, the
current database is set to the given value. To change the current
database later, execute a <code class="literal">USE</code> SQL statement or
set the <code class="literal">database</code> property of the
<code class="literal">MySQLConnection</code> instance.
</p><p>
By default, Connector/Python tries to connect to a MySQL server running on
the local host using TCP/IP. The <code class="literal">host</code> argument
defaults to IP address 127.0.0.1 and <code class="literal">port</code> to
3306. Unix sockets are supported by setting
<code class="literal">unix_socket</code>. Named pipes on the Windows
platform are not supported.
</p><p>
Connector/Python supports authentication plugins available as of MySQL 8.0,
including the preferred
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html" target="_top">caching_sha2_password</a>
authentication plugin.
</p><p>
The deprecated
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/native-pluggable-authentication.html" target="_top">mysql_native_password</a>
plugin is supported, but it is disabled by default as of MySQL
Server 8.4.0 and removed as of MySQL Server 9.0.0.
</p><p>
The <code class="literal">connect()</code> method supports an
<code class="literal">auth_plugin</code> argument that can be used to force
use of a particular authentication plugin.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
MySQL Connector/Python does not support the old, less-secure password protocols
of MySQL versions prior to 4.1.
</p></div><p>
Connector/Python supports the
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/kerberos-pluggable-authentication.html" target="_top">Kerberos
authentication protocol</a> for passwordless authentication.
Linux clients are supported as of Connector/Python 8.0.26, and Windows
support was added in Connector/Python 8.0.27 with the C extension
implementation, and in Connector/Python 8.0.29 with the pure Python
implementation. For Windows, the related
<code class="option">kerberos_auth_mode</code> connection option was added in
8.0.32 to configure the mode as either SSPI (default) or GSSAPI
(via the pure Python implementation, or the C extension
implementation as of 8.4.0). While Windows supports both modes,
Linux only supports GSSAPI.
</p><p>
Optionally use the <code class="literal">[gssapi]</code> shortcut when
installing the <code class="literal">mysql-connector-python</code> pip
package to pull in specific GSSAPI versions as defined by the
connector, which is v1.8.3 as of Connector/Python 9.1.0:
</p><pre class="programlisting">$ pip install mysql-connector-python[gssapi]
</pre><p>
The following example assumes
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/ldap-pluggable-authentication.html" target="_top">LDAP Pluggable Authentication</a> is set up to
utilize GSSAPI/Kerberos SASL authentication:
</p><pre data-lang="python" class="programlisting">import mysql.connector as cpy
import logging
logging.basicConfig(level=logging.DEBUG)
SERVICE_NAME = "ldap"
LDAP_SERVER_IP = "server_ip or hostname" # e.g., winexample01
config = {
"host": "127.0.0.1",
"port": 3306,
"user": "myuser@example.com",
"password": "s3cret",
"use_pure": True,
"krb_service_principal": f"{SERVICE_NAME}/{LDAP_SERVER_IP}"
}
with cpy.connect(**config) as cnx:
with cnx.cursor() as cur:
cur.execute("SELECT @@version")
res = cur.fetchone()
print(res[0])
</pre><p>
Connector/Python supports Multi-Factor Authentication (MFA) as of v8.0.28 by
utilizing the <code class="option">password1</code> (alias of
<code class="option">password</code>), <code class="option">password2</code>, and
<code class="option">password3</code> connection options.
</p><p>
Connector/Python supports
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.4/en/webauthn-pluggable-authentication.html" target="_top">WebAuthn
Pluggable Authentication</a> as of Connector/Python 8.2.0, which is
supported in MySQL Enterprise Edition. Optionally use the Connector/Python
<a class="link" href="#connector-python-connectargs-listing-webauthn_callback">webauthn_callback</a>
connection option to notify users that they need to touch the
hardware device. This functionality is present in the C
implementation (which uses libmysqlclient) but the pure Python
implementation requires the FIDO2 dependency that is not provided
with the MySQL connector and is assumed to already be present in
your environment. It can be independently installed using:
</p><pre data-lang="terminal" class="programlisting">$> pip install fido2
</pre><p>
Previously, the now removed (as of version 8.4.0)
<code class="literal">authentication_fido</code> MySQL Server plugin was
supported using the
<a class="link" href="#connector-python-connectargs-listing-fido_callback">fido_callback</a>
option that was available in the C extension implementation.
</p><p>
Connector/Python supports <span class="emphasis"><em>OpenID Connect</em></span> as of Connector/Python
9.1.0. Functionality is enabled with the
<code class="literal">authentication_openid_connect_client</code>
client-side authentication plugin connecting to MySQL Enterprise Edition with the
<code class="literal">authentication_openid_connect</code> authentication
plugin. These examples enable the plugin with
<code class="literal">auth_plugin</code> and defines the JWT Identity Token
file location with <code class="literal">openid_token_file</code>:
</p><pre data-lang="python" class="programlisting"># Standard connection
import mysql.connector as cpy
config = {
"host": "localhost",
"port": 3306,
"user": "root",
"openid_token_file": "{path-to-id-token-file}",
"auth_plugin": "authentication_openid_connect_client",
"use_pure": True, # Use False for C-Extension
}
with cpy.connect(**config) as cnx:
with cnx.cursor() as cur:
cur.execute("SELECT @@version")
print(cur.fetchall())
# Or, using an async connection
import mysql.connector.aio as cpy_async
import asyncio
config = {
"host": "localhost",
"port": 3306,
"user": "root",
"auth_plugin": "authentication_openid_connect_client",
"openid_token_file": "{path-to-id-token-file}",
}
async def test():
async with await cpy_async.connect(**config) as cnx:
async with await cnx.cursor() as cur:
await cur.execute("SELECT @@version")
print(await cur.fetchall())
asyncio.run(test())
</pre><h3><a name="id2677"></a>Character Encoding</h3><p>
By default, strings coming from MySQL are returned as Python
Unicode literals. To change this behavior, set
<code class="literal">use_unicode</code> to <code class="literal">False</code>. You
can change the character setting for the client connection through
the <code class="literal">charset</code> argument. To change the character
set after connecting to MySQL, set the <code class="literal">charset</code>
property of the <code class="literal">MySQLConnection</code> instance. This
technique is preferred over using the <code class="literal">SET NAMES</code>
SQL statement directly. Similar to the <code class="literal">charset</code>
property, you can set the <code class="literal">collation</code> for the
current MySQL session.
</p><h3><a name="id2687"></a>Transactions</h3><p>
The <code class="literal">autocommit</code> value defaults to
<code class="literal">False</code>, so transactions are not automatically
committed. Call the <code class="literal">commit()</code> method of the
<code class="literal">MySQLConnection</code> instance within your
application after doing a set of related insert, update, and
delete operations. For data consistency and high throughput for
write operations, it is best to leave the
<code class="literal">autocommit</code> configuration option turned off when
using <code class="literal">InnoDB</code> or other transactional tables.
</p><h3><a name="id2695"></a>Time Zones</h3><p>
The time zone can be set per connection using the
<code class="literal">time_zone</code> argument. This is useful, for
example, if the MySQL server is set to UTC and
<code class="literal">TIMESTAMP</code> values should be returned by MySQL
converted to the <code class="literal">PST</code> time zone.
</p><h3><a name="id2700"></a>SQL Modes</h3><p>
MySQL supports so-called SQL Modes. which change the behavior of
the server globally or per connection. For example, to have
warnings raised as errors, set <code class="literal">sql_mode</code> to
<code class="literal">TRADITIONAL</code>. For more information, see
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">Server SQL Modes</a>.
</p><h3><a name="id2705"></a>Troubleshooting and Error Handling</h3><p>
Warnings generated by queries are fetched automatically when
<code class="literal">get_warnings</code> is set to <code class="literal">True</code>.
You can also immediately raise an exception by setting
<code class="literal">raise_on_warnings</code> to <code class="literal">True</code>.
Consider using the MySQL <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">sql_mode</a>
setting for turning warnings into errors.
</p><p>
To set a timeout value for connections, use
<code class="literal">connection_timeout</code>.
</p><h3><a name="id2714"></a>Enabling and Disabling Features Using Client Flags</h3><p>
MySQL uses <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-real-connect.html" target="_top">client flags</a>
to enable or disable features. Using the
<code class="literal">client_flags</code> argument, you have control of what
is set. To find out what flags are available, use the following:
</p><pre data-lang="python" class="programlisting">from mysql.connector.constants import ClientFlag
print '\n'.join(ClientFlag.get_full_info())
</pre><p>
If <code class="literal">client_flags</code> is not specified (that is, it
is zero), defaults are used for MySQL 4.1 and higher. If you
specify an integer greater than <code class="literal">0</code>, make sure
all flags are set properly. A better way to set and unset flags
individually is to use a list. For example, to set
<code class="literal">FOUND_ROWS</code>, but disable the default
<code class="literal">LONG_FLAG</code>:
</p><pre data-lang="python" class="programlisting">flags = [ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG]
mysql.connector.connect(client_flags=flags)
</pre><h3><a name="id2725"></a>Result Set Handling</h3><p>
By default, MySQL Connector/Python does not buffer or prefetch results. This means
that after a query is executed, your program is responsible for
fetching the data. This avoids excessive memory use when queries
return large result sets. If you know that the result set is small
enough to handle all at once, you can fetch the results
immediately by setting <code class="literal">buffered</code> to
<code class="literal">True</code>. It is also possible to set this per
cursor (see
<a class="xref" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method">Section 10.2.6, “MySQLConnection.cursor() Method”</a>).
</p><p>
Results generated by queries normally are not read until the
client program fetches them. To automatically consume and discard
result sets, set the <code class="literal">consume_results</code> option to
<code class="literal">True</code>. The result is that all results are read,
which for large result sets can be slow. (In this case, it might
be preferable to close and reopen the connection.)
</p><h3><a name="id2733"></a>Type Conversions</h3><p>
By default, MySQL types in result sets are converted automatically
to Python types. For example, a <code class="literal">DATETIME</code> column
value becomes a
<a class="ulink" href="http://docs.python.org/library/datetime.html#datetime.datetime" target="_top">datetime.datetime</a>
object. To disable conversion, set the <code class="literal">raw</code>
option to <code class="literal">True</code>. You might do this to get better
performance or perform different types of conversion yourself.
</p><h3><a name="id2739"></a>Connecting through SSL</h3><p>
Using SSL connections is possible when your
<a class="ulink" href="http://docs.python.org/library/ssl.html" target="_top">Python
installation supports SSL</a>, that is, when it is compiled
against the OpenSSL libraries. When you provide the
<code class="literal">ssl_ca</code>, <code class="literal">ssl_key</code> and
<code class="literal">ssl_cert</code> options, the connection switches to
SSL, and the <code class="literal">client_flags</code> option includes the
<code class="literal">ClientFlag.SSL</code> value automatically. You can use
this in combination with the <code class="literal">compressed</code> option
set to <code class="literal">True</code>.
</p><p>
As of Connector/Python 2.2.2, if the MySQL server supports SSL connections,
Connector/Python attempts to establish a secure (encrypted) connection by
default, falling back to an unencrypted connection otherwise.
</p><p>
From Connector/Python 1.2.1 through Connector/Python 2.2.1, it is possible to establish
an SSL connection using only the <code class="literal">ssl_ca</code> opion.
The <code class="literal">ssl_key</code> and <code class="literal">ssl_cert</code>
arguments are optional. However, when either is given, both must
be given or an <code class="literal">AttributeError</code> is raised.
</p><pre data-lang="python" class="programlisting"># Note (Example is valid for Python v2 and v3)
from __future__ import print_function
import sys
#sys.path.insert(0, 'python{0}/'.format(sys.version_info[0]))
import mysql.connector
from mysql.connector.constants import ClientFlag
config = {
'user': 'ssluser',
'password': '<em class="replaceable"><code>password</code></em>',
'host': '127.0.0.1',
'client_flags': [ClientFlag.SSL],
'ssl_ca': '/opt/mysql/ssl/ca.pem',
'ssl_cert': '/opt/mysql/ssl/client-cert.pem',
'ssl_key': '/opt/mysql/ssl/client-key.pem',
}
cnx = mysql.connector.connect(**config)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
print(cur.fetchone())
cur.close()
cnx.close()
</pre><h3><a name="id2758"></a>Connection Pooling</h3><p>
With either the <code class="literal">pool_name</code> or
<code class="literal">pool_size</code> argument present, Connector/Python creates the
new pool. If the <code class="literal">pool_name</code> argument is not
given, the <code class="literal">connect()</code> call automatically
generates the name, composed from whichever of the
<code class="literal">host</code>, <code class="literal">port</code>,
<code class="literal">user</code>, and <code class="literal">database</code>
connection arguments are given, in that order. If the
<code class="literal">pool_size</code> argument is not given, the default
size is 5 connections.
</p><p>
The <code class="literal">pool_reset_session</code> permits control over
whether session variables are reset when the connection is
returned to the pool. The default is to reset them.
</p><p>
For additional information about connection pooling, see
<a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
</p><h3><a name="id2773"></a>Protocol Compression</h3><p>
The boolean <code class="literal">compress</code> argument indicates whether
to use the compressed client/server protocol (default
<code class="literal">False</code>). This provides an easier alternative to
setting the <code class="literal">ClientFlag.COMPRESS</code> flag. This
argument is available as of Connector/Python 1.1.2.
</p><h3><a name="id2778"></a>Converter Class</h3><p>
The <code class="literal">converter_class</code> argument takes a class and
sets it when configuring the connection. An
<code class="literal">AttributeError</code> is raised if the custom
converter class is not a subclass of
<code class="literal">conversion.MySQLConverterBase</code>.
</p><h3><a name="id2783"></a>Server Failover</h3><p>
The <code class="literal">connect()</code> method accepts a
<code class="literal">failover</code> argument that provides information to
use for server failover in the event of connection failures. The
argument value is a tuple or list of dictionaries (tuple is
preferred because it is nonmutable). Each dictionary contains
connection arguments for a given server in the failover sequence.
Permitted dictionary values are: <code class="literal">user</code>,
<code class="literal">password</code>, <code class="literal">host</code>,
<code class="literal">port</code>, <code class="literal">unix_socket</code>,
<code class="literal">database</code>, <code class="literal">pool_name</code>,
<code class="literal">pool_size</code>. This failover option was added in
Connector/Python 1.2.1.
</p><h3><a name="id2795"></a>Option File Support</h3><p>
As of Connector/Python 2.0.0, option files are supported using two options
for <code class="literal">connect()</code>:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">option_files</code>: Which option files to read.
The value can be a file path name (a string) or a sequence of
path name strings. By default, Connector/Python reads no option files, so
this argument must be given explicitly to cause option files
to be read. Files are read in the order specified.
</p></li><li class="listitem"><p>
<code class="literal">option_groups</code>: Which groups to read from
option files, if option files are read. The value can be an
option group name (a string) or a sequence of group name
strings. If this argument is not given, the default value is
<code class="literal">['client', 'connector_python']</code> to read the
<code class="literal">[client]</code> and
<code class="literal">[connector_python]</code> groups.
</p></li></ul></div><p>
For more information, see
<a class="xref" href="#connector-python-option-files" title="7.2 Connector/Python Option-File Support">Section 7.2, “Connector/Python Option-File Support”</a>.
</p><h3><a name="id2810"></a>LOAD DATA LOCAL INFILE</h3><p>
Prior to Connector/Python 2.0.0, to enable use of
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/load-data.html" target="_top"><code class="literal">LOAD DATA LOCAL
INFILE</code></a>, clients had to explicitly set the
<code class="literal">ClientFlag.LOCAL_FILES</code> flag. As of 2.0.0, this
flag is enabled by default. To disable it, the
<code class="literal">allow_local_infile</code> connection option can be set
to <code class="literal">False</code> at connect time (the default is
<code class="literal">True</code>).
</p><h3><a name="id2818"></a>Compatibility with Other Connection Interfaces</h3><p>
<code class="literal">passwd</code>, <code class="literal">db</code> and
<code class="literal">connect_timeout</code> are valid for compatibility
with other MySQL interfaces and are respectively the same as
<code class="literal">password</code>, <code class="literal">database</code> and
<code class="literal">connection_timeout</code>. The latter take precedence.
Data source name syntax or <code class="literal">dsn</code> is not used; if
specified, it raises a <code class="literal">NotSupportedError</code>
exception.
</p><h3><a name="id2828"></a>Client/Server Protocol Implementation</h3><p>
Connector/Python can use a pure Python interface to MySQL, or a C Extension
that uses the MySQL C client library. The
<code class="literal">use_pure</code>
<span class="emphasis"><em>mysql.connector.connect()</em></span> connection argument
determines which. The default changed in Connector/Python 8 from
<code class="literal">True</code> (use the pure Python implementation) to
<code class="literal">False</code>. Setting <code class="literal">use_pure</code>
changes the implementation used.
</p><p>
The <code class="literal">use_pure</code> argument is available as of Connector/Python
2.1.1. For more information about the C extension, see
<a class="xref" href="#connector-python-cext" title="Chapter 8 The Connector/Python C Extension">Chapter 8, <i>The Connector/Python C Extension</i></a>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-option-files"></a>7.2 Connector/Python Option-File Support</h2></div></div></div><p>
Connector/Python can read options from option files. (For general information
about option files in MySQL, see <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/option-files.html" target="_top">Using Option Files</a>.)
Two arguments for the <code class="literal">connect()</code> call control
use of option files in Connector/Python programs:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">option_files</code>: Which option files to read.
The value can be a file path name (a string) or a sequence of
path name strings. By default, Connector/Python reads no option files, so
this argument must be given explicitly to cause option files
to be read. Files are read in the order specified.
</p></li><li class="listitem"><p>
<code class="literal">option_groups</code>: Which groups to read from
option files, if option files are read. The value can be an
option group name (a string) or a sequence of group name
strings. If this argument is not given, the default value is
<code class="literal">['client', 'connector_python']</code>, to read the
<code class="literal">[client]</code> and
<code class="literal">[connector_python]</code> groups.
</p></li></ul></div><p>
Connector/Python also supports the <code class="literal">!include</code> and
<code class="literal">!includedir</code> inclusion directives within option
files. These directives work the same way as for other MySQL
programs (see <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/option-files.html" target="_top">Using Option Files</a>).
</p><p>
This example specifies a single option file as a string:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf')
</pre><p>
This example specifies multiple option files as a sequence of
strings:
</p><pre data-lang="python" class="programlisting">mysql_option_files = [
'/etc/mysql/connectors.cnf',
'./development.cnf',
]
cnx = mysql.connector.connect(option_files=mysql_option_files)
</pre><p>
Connector/Python reads no option files by default, for backward compatibility
with versions older than 2.0.0. This differs from standard MySQL
clients such as <span class="command"><strong>mysql</strong></span> or
<span class="command"><strong>mysqldump</strong></span>, which do read option files by
default. To find out which option files the standard clients read
on your system, invoke one of them with its
<code class="option">--help</code> option and examine the output. For
example:
</p><pre data-lang="terminal" class="programlisting">$> <strong class="userinput"><code>mysql --help</code></strong>
...
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf
...
</pre><p>
If you specify the <code class="literal">option_files</code> connection
argument to read option files, Connector/Python reads the
<code class="literal">[client]</code> and
<code class="literal">[connector_python]</code> option groups by default. To
specify explicitly which groups to read, use the
<code class="literal">option_groups</code> connection argument. The
following example causes only the
<code class="literal">[connector_python]</code> group to be read:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf',
option_groups='connector_python')
</pre><p>
Other connection arguments specified in the
<code class="literal">connect()</code> call take precedence over options
read from option files. Suppose that
<code class="filename">/etc/mysql/connectors.conf</code> contains these
lines:
</p><pre data-lang="ini" class="programlisting">[client]
database=cpyapp
</pre><p>
The following <code class="literal">connect()</code> call includes no
<code class="literal">database</code> connection argument. The resulting
connection uses <code class="literal">cpyapp</code>, the database specified
in the option file:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf')
</pre><p>
By contrast, the following <code class="literal">connect()</code> call
specifies a default database different from the one found in the
option file. The resulting connection uses
<code class="literal">cpyapp_dev</code> as the default database, not
<code class="literal">cpyapp</code>:
</p><pre data-lang="python" class="programlisting">cnx2 = mysql.connector.connect(option_files='/etc/mysql/connectors.cnf',
database='cpyapp_dev')
</pre><p>
Connector/Python raises a <code class="literal">ValueError</code> if an option file
cannot be read, or has already been read. This includes files read
by inclusion directives.
</p><p>
For the <code class="literal">[connector_python]</code> group, only options
supported by Connector/Python are accepted. Unrecognized options cause a
<code class="literal">ValueError</code> to be raised.
</p><p>
For other option groups, Connector/Python ignores unrecognized options.
</p><p>
It is not an error for a named option group not to exist.
</p><h3><a name="id2896"></a>Option Parsing</h3><p>
Connector/Python reads the option values in option files as strings, and
attempts to parse them using Python's
<code class="literal">ast.literal_eval</code> function. This allows
specifying values like numbers, tuples, lists, and booleans in the
option files. If a value can't be parsed by
<code class="literal">ast.literal_eval</code> then it's passed as a literal
string.
</p><p>
For example, this option file has options with values using a
number, a string, and a tuple of dictionaries that are correctly
parsed for the <code class="literal">[connector_python]</code> group:
</p><pre data-lang="ini" class="programlisting">[connector_python]
database=cpyapp
port=3656
failover=({'host': '203.0.113.1', 'port': 3640}, {'host': '203.0.113.101', 'port': 3650})
</pre><p>
For additional information, review Python's
<a class="ulink" href="https://docs.python.org/3/library/ast.html#ast.literal_eval" target="_top">ast.literal_eval</a>
documentation including how to handle unsanitized data that could
crash the Python interpreter. Confirm that the option file values
are trustworthy and valid before parsing.
</p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-cext"></a>Chapter 8 The Connector/Python C Extension</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-cext-development">8.1 Application Development with the Connector/Python C Extension</a></span></dt><dt><span class="section"><a href="#connector-python-cext-module">8.2 The _mysql_connector C Extension Module</a></span></dt></dl></div><p>
Connector/Python supports a C extension that interfaces with the MySQL C client
library. For queries that return large result sets, using the C
Extension can improve performance compared to a <span class="quote">“<span class="quote">pure
Python</span>”</span> implementation of the MySQL client/server protocol.
<a class="xref" href="#connector-python-cext-development" title="8.1 Application Development with the Connector/Python C Extension">Section 8.1, “Application Development with the Connector/Python C Extension”</a>, describes how
applications that use the <code class="literal">mysql.connector</code> module
can use the C Extension. It is also possible to use the C Extension
directly, by importing the <code class="literal">_mysql_connector</code>
module rather than the <code class="literal">mysql.connector</code> module.
See <a class="xref" href="#connector-python-cext-module" title="8.2 The _mysql_connector C Extension Module">Section 8.2, “The _mysql_connector C Extension Module”</a>. For information
about installing the C Extension, see
<a class="xref" href="#connector-python-installation" title="Chapter 4 Connector/Python Installation">Chapter 4, <i>Connector/Python Installation</i></a>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
The C extension was added in version 2.1.1 and is enabled by
default as of 8.0.11. The <code class="literal">use_pure</code> option
determines whether the Python or C version of this connector is
enabled and used.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-cext-development"></a>8.1 Application Development with the Connector/Python C Extension</h2></div></div></div><p>
Installations of Connector/Python from version 2.1.1 on support a
<code class="literal">use_pure</code> argument to
<code class="literal">mysql.connector.connect()</code> that indicates
whether to use the pure Python interface to MySQL or the C
Extension that uses the MySQL C client library:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
By default, <code class="literal">use_pure</code> (use the pure Python
implementation) is <code class="literal">False</code> as of MySQL 8 and
defaults to <code class="literal">True</code> in earlier versions. If
the C extension is not available on the system then
<code class="literal">use_pure</code> is <code class="literal">True</code>.
</p></li><li class="listitem"><p>
On Linux, the C and Python implementations are available as
different packages. You can install one or both
implementations on the same system. On Windows and macOS, the
packages include both implementations.
</p><p>
For Connector/Python installations that include both implementations, it
can optionally be toggled it by passing
<code class="literal">use_pure=False</code> (to use C implementation) or
<code class="literal">use_pure=True</code> (to use the Python
implementation) as an argument to
<code class="literal">mysql.connector.connect()</code>.
</p></li><li class="listitem"><p>
For Connector/Python installations that do not include the C Extension,
passing <code class="literal">use_pure=False</code> to
<code class="literal">mysql.connector.connect()</code> raises an
exception.
</p></li><li class="listitem"><p>
For older Connector/Python installations that know nothing of the C
Extension (before version 2.1.1), passing
<code class="literal">use_pure</code> to
<code class="literal">mysql.connector.connect()</code> raises an
exception regardless of its value.
</p></li></ul></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
On macOS, if your Connector/Python installation includes the C Extension,
but Python scripts are unable to use it, try setting your
<code class="literal">DYLD_LIBRARY_PATH</code> environment variable the
directory containing the C client library. For example:
</p><a class="indexterm" name="id2948"></a><a class="indexterm" name="id2950"></a><pre data-lang="terminal" class="programlisting">export DYLD_LIBRARY_PATH=/usr/local/mysql/lib (for sh)
setenv DYLD_LIBRARY_PATH /usr/local/mysql/lib (for tcsh)
</pre><p>
If you built the C Extension from source, this directory should
be the one containing the C client library against which the
extension was built.
</p></div><p>
If you need to check whether your Connector/Python installation is aware of
the C Extension, test the <code class="literal">HAVE_CEXT</code> value.
There are different approaches for this. Suppose that your usual
arguments for <code class="literal">mysql.connector.connect()</code> are
specified in a dictionary:
</p><pre data-lang="python" class="programlisting">config = {
'user': 'scott',
'password': '<em class="replaceable"><code>password</code></em>',
'host': '127.0.0.1',
'database': 'employees',
}
</pre><p>
The following example illustrates one way to add
<code class="literal">use_pure</code> to the connection arguments:
</p><pre data-lang="python" class="programlisting">import mysql.connector
if mysql.connector.__version_info__ > (2, 1) and mysql.connector.HAVE_CEXT:
config['use_pure'] = False
</pre><p>
If <code class="literal">use_pure=False</code> and the C Extension is not
available, then Connector/Python will automatically fall back to
the pure Python implementation.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-cext-module"></a>8.2 The _mysql_connector C Extension Module</h2></div></div></div><p>
To use the C Extension directly, import the
<code class="literal">_mysql_connector</code> module rather than
<code class="literal">mysql.connector</code>, then use the
<code class="literal">_mysql_connector.MySQL()</code> class to obtain a
<code class="literal">MySQL</code> instance. For example:
</p><pre data-lang="python" class="programlisting">import _mysql_connector
ccnx = _mysql_connector.MySQL()
ccnx.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
host='127.0.0.1', database='employees')
ccnx.query("SHOW VARIABLES LIKE 'version%'")
row = ccnx.fetch_row()
while row:
print(row)
row = ccnx.fetch_row()
ccnx.free_result()
ccnx.close()
</pre><p>
For more information, see
<a class="xref" href="#connector-python-cext-reference" title="Chapter 11 Connector/Python C Extension API Reference">Chapter 11, <i>Connector/Python C Extension API Reference</i></a>.
</p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-other"></a>Chapter 9 Connector/Python Other Topics</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-logging">9.1 Connector/Python Logging</a></span></dt><dt><span class="section"><a href="#connector-python-opentelemetry">9.2 Telemetry Support</a></span></dt><dt><span class="section"><a href="#connector-python-multi">9.3 Executing Multiple Statements</a></span></dt><dt><span class="section"><a href="#connector-python-asyncio">9.4 Asynchronous Connectivity</a></span></dt><dt><span class="section"><a href="#connector-python-connection-pooling">9.5 Connector/Python Connection Pooling</a></span></dt><dt><span class="section"><a href="#connector-python-django-backend">9.6 Connector/Python Django Back End</a></span></dt></dl></div><p></p><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-logging"></a>9.1 Connector/Python Logging</h2></div></div></div><p>
By default, logging functionality follows the default Python
logging behavior. If logging functionality is not configured, only
events with a severity level of WARNING and greater are printed to
sys.stderr. For related information, see Python's
<a class="ulink" href="https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library" target="_top">Configuring
Logging for a Library</a> documentation.
</p><p>
Outputting additional levels requires configuration. For example,
to output debug events to sys.stderr set logging.DEBUG and add the
logging.StreamHandler handler. Additional handles can also be
added, such as logging.FileHandler. This example sets both:
</p><pre data-lang="python" class="programlisting"># Classic Protocol Example
import logging
import mysql.connector
logger = logging.getLogger("mysql.connector")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s- %(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
file_handler = logging.FileHandler("cpy.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# XDevAPI Protocol Example
import logging
import mysqlx
logger = logging.getLogger("mysqlx")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s- %(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
file_handler = logging.FileHandler("cpy.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
</pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-opentelemetry"></a>9.2 Telemetry Support</h2></div></div></div><p>
MySQL Server added OpenTelemetry support in MySQL Enterprise Edition version 8.1.0,
which is a <a class="ulink" href="https://www.mysql.com/products/enterprise/" target="_top">commercial
product</a>. OpenTelemetry tracing support was added in Connector/Python
8.1.0.
</p><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-introduction"></a>Introduction to OpenTelemetry</h3></div></div></div><p>
<span class="emphasis"><em>OpenTelemetry</em></span> is an observability framework
and toolkit designed to create and manage telemetry data such as
traces, metrics, and logs. Visit
<a class="ulink" href="https://opentelemetry.io/docs/what-is-opentelemetry/" target="_top">What
is OpenTelemetry?</a> for an explanation of what
OpenTelemetry offers.
</p><p>
Connector/Python only supports tracing, so this guide does not include
information about metric and log signals.
</p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-installation"></a>Installing Telemetry Support</h3></div></div></div><p>
Install the OpenTelemetry API, SDK, and OTLP Exporter packages
on the system along with Connector/Python. Optionally use the
<code class="literal">[telemetry]</code> shortcut when installing the
<code class="literal">mysql-connector-python</code> pip package to pull in
specific OpenTelemetry versions as defined by the connector.
</p><p>
Manual installation:
</p><pre data-lang="terminal" class="programlisting">pip install opentelemetry-api
pip install opentelemetry-sdk
pip install opentelemetry-exporter-otlp-proto-http
pip install mysql-connector-python
</pre><p>
Or pass in [telemetry] when installing Connector/Python to perform the
same actions except it installs a specific and tested
OpenTelemetry version, which for Connector/Python 9.4.0 and later is
OpenTelemetry v1.33.1:
</p><pre data-lang="terminal" class="programlisting">pip install mysql-connector-python[telemetry]
</pre><p>
Connector/Python 8.1.0 through 8.4.0 included an [opentelemetry] option
that installed a bundled version of the OpenTelemetry SDK/API
libraries. Doing so in those versions was not recommended.
</p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-instrumentation"></a>Instrumentation</h3></div></div></div><p>
For instrumenting an application, Connector/Python utilizes the official
OpenTelemetry SDK to initialize OpenTelemetry, and the official
OpenTelemetry API to instrument the application's code. This
emits telemetry from the application and from utilized libraries
that include instrumentation.
</p><p>
An application can be instrumented as demonstrated by this
generic example:
</p><pre data-lang="python" class="programlisting">from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("app"):
my_app()
</pre><p>
To better understand and get started using OpenTelemetry tracing
for Python, see the official
<a class="ulink" href="https://opentelemetry.io/docs/instrumentation/python/manual/" target="_top">OpenTelemetry
Python Instrumentation</a> guide.
</p></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-connector"></a>MySQL Connector/Python</h3></div></div></div><p>
Connector/Python includes a MySQL instrumentor to instrument MySQL
connections. This instrumentor provides an API and usage similar
to OpenTelemetry's own MySQL package named
<a class="ulink" href="https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-mysql" target="_top">opentelemetry-instrumentation-mysql</a>.
</p><p>
An exception is raised if a system does not support
OpenTelemetry when attempting to use the instrumentor.
</p><p>
An example that utilizes the system's OpenTelemetry SDK/API and
implements tracing with MySQL Connector/Python:
</p><pre data-lang="python" class="programlisting">import os
import mysql.connector
# An instrumentor that comes with mysql-connector-python
from mysql.connector.opentelemetry.instrumentation import (
MySQLInstrumentor as OracleMySQLInstrumentor,
)
# Loading SDK from the system
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
config = {
"host": "127.0.0.1",
"user": "root",
"password": os.environ.get("password"),
"use_pure": True,
"port": 3306,
"database": "test",
}
# Global instrumentation: all connection objects returned by
# mysql.connector.connect will be instrumented.
OracleMySQLInstrumentor().instrument()
with tracer.start_as_current_span("client_app"):
with mysql.connector.connect(**config) as cnx:
with cnx.cursor() as cur:
cur.execute("SELECT @@version")
_ = cur.fetchall()
</pre></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-morphology"></a>Morphology of the Emitted Traces</h3></div></div></div><p>
A trace generated by the Connector/Python instrumentor contains one
connection span, and zero or more query spans as described in
the rest of this section.
</p><p>
<span class="emphasis"><em>Connection Span</em></span>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Time from connection initialization to the moment the
connection ends. The span is named
<code class="literal">connection</code>.
</p></li><li class="listitem"><p>
If the application does not provide a span, the connection
span generated is a ROOT span, originating in the connector.
</p></li><li class="listitem"><p>
If the application does provide a span, the query span
generated is a CHILD span, originating in the connector.
</p></li></ul></div><p>
<span class="emphasis"><em>Query Span</em></span>
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Time from when an SQL statement is requested (on the
connector side) to the moment the connector finishes
processing the server's reply to this statement.
</p></li><li class="listitem"><p>
A query span is created for each query request sent to the
server. If the application does not provide a span, the
query span generated is a ROOT span, originating in the
connector.
</p></li><li class="listitem"><p>
If the application does provide a span, the query span
generated is a CHILD span, originating in the connector.
</p></li><li class="listitem"><p>
The query span is linked to the existing connection span of
the connection the query was executed.
</p></li><li class="listitem"><p>
Query attributes with prepared statements is supported as of
MySQL Enterprise Edition 8.3.0.
</p></li><li class="listitem"><p>
Query spans for the connection object is supported as of
Connector/Python 8.3.0, which includes methods such as commit(),
rollback(), and cmd_change_user().
</p></li></ul></div><p>
<span class="emphasis"><em>Context Propagation</em></span>
</p><p>
By default, the trace context of the span in progress (if any)
is propagated to the MySQL server.
</p><p>
Propagation has no effect when the MySQL server either disabled
or does not support OpenTelemetry (the trace context is ignored
by the server), however, when connecting to a server with
OpenTelemetry enabled and configured, the server processes the
propagated traces and creates parent-child relationships between
the spans from the connector and those from the server. In other
words, this provides trace continuity.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Context propagation with prepared statements is supported as
of MySQL Enterprise Edition 8.3.0.
</p></div><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
The trace context is propagated for statements with query
attributes defined in the MySQL client/server protocol, such
as COM_QUERY.
</p><p>
The trace context is not propagated for statements without
query attributes defined in the MySQL client/server
protocol, statements such as COM_PING.
</p></li><li class="listitem"><p>
Trace context propagation is done via query attributes where
a new attribute named "traceparent" is defined. Its value is
based on the current span context. For details on how this
value is computed, read the
<a class="ulink" href="https://www.w3.org/TR/trace-context/#traceparent-header" target="_top">traceparent
header W3C specification</a>.
</p><p>
If the "traceparent" query attribute is manually set for a
query, then it is not be overwritten by the connector; it's
assumed that it provides OTel context intended to forward to
the server.
</p></li></ul></div></div><div class="simplesect"><div class="titlepage"><div><div class="simple"><h3 class="title"><a name="connector-python-opentelemetry-disabling-trace"></a>Disabling Trace Context Propagation</h3></div></div></div><p>
The boolean connection property named
<code class="option">otel_context_propagation</code> is
<code class="literal">True</code> by default. Setting it to
<code class="literal">False</code> disables context propagation.
</p><p>
Since <code class="option">otel_context_propagation</code> is a connection
property that can be changed after a connection is established
(a connection object is created), setting such property to
<code class="literal">False</code> does not have an effect over the spans
generated during the connection phase. In other words, spans
generated during the connection phase are always propagated
since <code class="option">otel_context_propagation</code> is
<code class="literal">True</code> by default.
</p><p>
This implementation is distinct from the implementation provided
through the MySQL client library (or the related
<code class="literal">telemetry_client</code> client-side plugin).
</p></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-multi"></a>9.3 Executing Multiple Statements</h2></div></div></div><p>
Connector/Python can execute either a single or multiple statements, this
section references multiple statement and associated delimiter
support.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Before Connector/Python 9.2.0, the <code class="option">multi</code> option was
required to execute multiple statements. This option provided
inconsistent results and was removed in 9.2.0.
</p></div><p>
Basic usage example:
</p><pre data-lang="python" class="programlisting">sql_operation = """
SET @a=1, @b='2024-02-01';
SELECT @a, LENGTH('hello'), @b;
SELECT @@version;
"""
with cnx.cursor() as cur:
# Execute SQL; it can contain one or multiple statements
cur.execute(sql_operation)
# Fetch result set, see other examples for additional information
</pre><p>
Custom delimiters are also supported (as of Connector/Python 9.2.0),
including in scripts that include delimiters and multiple
statements. The Sakila sample database file
<code class="filename">sakila-schema.sql</code> is an example:
</p><pre data-lang="python" class="programlisting">with cnx.cursor() as cur:
with open(
os.path.join("/path/to/files", "sakila-schema.sql"), encoding="utf-8"
) as code:
cur.execute(code.read())
# Fetch result set, see other examples for additional information
</pre><h3><a name="id3085"></a>Multiple Statement Result Mapping</h3><p>
The optional <code class="literal">map_results</code> option (defaults to
<code class="literal">False</code>) makes each statement relate to its
corresponding result set.
</p><pre data-lang="python" class="programlisting">sql_operation = ...
with cnx.cursor() as cur:
# Execute SQL; it can contain one or multiple statements
cur.execute(sql_operation, map_results=True)
# Fetch result set, see other examples for additional information
</pre><p>
A MySQL multi statement or script is composed of one or more
single statements. There are two types of single statements:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">Simple</code>: these do not include a
<code class="literal">BEGIN-END</code> body declaration.
</p></li><li class="listitem"><p>
<code class="literal">Compound</code>: these do include a
<code class="literal">BEGIN-END</code> body declaration, such as:
</p><pre data-lang="sql" class="programlisting">CREATE PROCEDURE dorepeat(p1 INT)
BEGIN
SET @x = 0;
REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT;
END;
</pre></li></ul></div><p>
Connector/Python uses custom delimiters to break up a multi statement into
individual statements when handling compound single statements,
like how the MySQL client does. Simple single statements do not
require custom delimiters but they can be used.
</p><p>
If no delimiters are utilized when working with compound single
statements, the statement-result mapping may cause unexpected
results. If mapping is disabled, compound single statements may or
may not utilize delimiters.
</p><p>
An example using a mix of simple and compound statements:
</p><pre data-lang="sql" class="programlisting">DROP PROCEDURE IF EXISTS dorepeat;
DELIMITER //
CREATE PROCEDURE dorepeat(p1 INT)
BEGIN
SET @x = 0;
REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT;
END//
DELIMITER ;
SELECT @x;
</pre><p>
Connector/Python carries on a pre-processing step for handling delimiters
that may affect performance for large scripts. There are also
limitations when working with custom delimiters:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">Unsupported delimiters</code>: the following
characters are not supported by the connector in
<code class="literal">DELIMITER</code> statements:
</p><pre data-lang="simple" class="programlisting">double quote: "
single quote: '
hash: #
slash plus star: /*
star plus slash: */
</pre><p>
Avoid using these symbols as part of a string representing a
delimiter.
</p></li><li class="listitem"><p>
<code class="literal">DELIMITER</code>: the word DELIMITER and any of
its lower and upper case combinations such as delimiter,
DeLiMiter, and so on, are considered reserved words by the
connector. Users must quote these when included in multi
statements for other purposes different from declaring an
actual statement delimiter; such as names for tables, columns,
variables, in comments, and so on. Example:
</p><pre data-lang="sql" class="programlisting">CREATE TABLE `delimiter` (begin INT, end INT); -- I am a `DELimiTer` comment
</pre></li></ul></div><h3><a name="id3117"></a>Fetching Result Sets</h3><p>
Basic usage (mapping disabled):
</p><pre data-lang="python" class="programlisting">sql_operation = """
SET @a=1, @b='2024-02-01';
SELECT @a, LENGTH('hello'), @b;
SELECT @@version;
"""
with cnx.cursor() as cur:
# Execute a statement; it can be single or multi.
cur.execute(sql_operation)
# Fetch result sets and do something with them
result_set = cur.fetchall()
# do something with result set
...
while cur.nextset():
result_set = cur.fetchall()
# do something with result set
...
</pre><p>
The multi statement execution generates one or more result sets,
in other words a set of result sets. The first result set is
loadable after execution completes. You might fetch (using
<code class="literal">fetchall()</code>) the current result set and process
it, or not, and move onto the next one.
</p><p>
Alternatively, use the
<a class="link" href="#connector-python-api-mysqlcursor-nextset" title="10.5.12 MySQLCursor.nextset() Method">nextset()</a>
cursor API method to traverse a result set. This method makes the
cursor skip to the next available set, discarding any remaining
rows from the current set.
</p><p>
For executions generating only one result set, which happens when
your script only includes one statement, the call to
<a class="link" href="#connector-python-api-mysqlcursor-nextset" title="10.5.12 MySQLCursor.nextset() Method">nextset()</a>
can be omitted as at most one result set is expected. Calling it
returns <code class="literal">None</code> as there are no more sets.
</p><p>
With Statement-ResultSet mapping usage:
</p><pre data-lang="python" class="programlisting">sql_operation = ...
with cnx.cursor() as cur:
# Execute a statement; it can be single or multi.
cur.execute(sql_operation, map_results=True)
# Fetch result sets and do something with them.
# statement 1 is `SET @a=1, @b='2025-01-01'`,
# result set from statement 1 is `[]` - aka, an empty set.
result_set, statement = cur.fetchall(), cur.statement
# do something with result set
...
# 1st call to `nextset()` will load the result set from statement 2,
# statement 2 is `SELECT @a, LENGTH('hello'), @b`,
# result set from statement 2 is `[(1, 5, '2025-01-01')]`.
#
# 2nd call to `nextset()` will load the result set from statement 3,
# statement 3 is `SELECT @@version`,
# result set from statement 3 is `[('9.2.0',)]`.
#
# 3rd call to `nextset()` will return `None` as there are no more sets,
# leading to the end of the consumption process of result sets.
while cur.nextset():
result_set, statement = cur.fetchall(), cur.statement
# do something with result set
...
</pre><p>
When the mapping is disabled
(<code class="literal">map_results=False</code>), all result sets are
related to the same statement, which is the one provided when
calling <code class="literal">execute()</code>. In other words, the
<code class="literal">statement</code> property does not change while result
sets are consumed, which differs from when mapping is enabled,
when the <code class="literal">statement</code> property returns the
statement that caused the current result set. Therefore, the value
of statement changes accordingly while the result sets are
traversed.
</p><h3><a name="id3134"></a>Shortcut for consuming result sets</h3><p>
A fetch-related API command shortcut is available to consume
result sets, this example is equivalent to the previously
presented workflow.
</p><pre data-lang="python" class="programlisting">sql_operation = '''
SET @a=1, @b='2025-01-01';
SELECT @a, LENGTH('hello'), @b;
SELECT @@version;
'''
with cnx.cursor() as cur:
cur.execute(sql_operation, map_results=True)
for statement, result_set in cur.fetchsets():
# do something with result set
</pre><p>
The
<a class="link" href="#connector-python-api-mysqlcursor-fetchsets" title="10.5.13 MySQLCursor.fetchsets() Method">fetchsets()</a>
method returns a generator where each item is a 2-tuple; the first
element is the statement that caused the result set, and the
second is the result set itself. If mapping is disabled, statement
will not change as result sets are consumed.
</p><p>
If statement is not needed, then consider this simpler option:
</p><pre data-lang="python" class="programlisting">sql_operation = ...
with cnx.cursor() as cur:
cur.execute(...)
for _, result_set in cur.fetchsets():
# do something with result set
</pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-asyncio"></a>9.4 Asynchronous Connectivity</h2></div></div></div><p>
Installing Connector/Python also installs the
<code class="literal">mysql.connector.aio</code> package that integrates
<a class="ulink" href="https://docs.python.org/3/library/asyncio.html" target="_top">asyncio</a>
with the connector to allow integrating asynchronous MySQL
interactions with an application.
</p><p>
Here are code examples that integrate
<code class="literal">mysql.connector.aio</code> functionality:
</p><h3><a name="id3148"></a>Basic Usage:</h3><pre data-lang="python" class="programlisting">from mysql.connector.aio import connect
# Connect to a MySQL server and get a cursor
cnx = await connect(user="myuser", password="mypass")
cur = await cnx.cursor()
# Execute a non-blocking query
await cur.execute("SELECT version()")
# Retrieve the results of the query asynchronously
results = await cur.fetchall()
print(results)
# Close cursor and connection
await cur.close()
await cnx.close()
</pre><h3><a name="id3150"></a>Usage with context managers:</h3><pre data-lang="python" class="programlisting">from mysql.connector.aio import connect
# Connect to a MySQL server and get a cursor
async with await connect(user="myuser", password="mypass") as cnx:
async with await cnx.cursor() as cur:
# Execute a non-blocking query
await cur.execute("SELECT version()")
# Retrieve the results of the query asynchronously
results = await cur.fetchall()
print(results)
</pre><h3><a name="id3152"></a>Running Multiple Tasks Asynchronously</h3><p>
This example showcases how to run tasks asynchronously and the
usage of to_thread, which is the backbone to asynchronously run
blocking functions:
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
The synchronous version of this example implements coroutines
instead of following a common synchronous approach; this to
explicitly demonstrate that only awaiting coroutines does not
make the code run asynchronously. Functions included in the
asyncio API must be used to achieve asynchronicity.
</p></div><pre data-lang="python" class="programlisting">import asyncio
import os
import time
from mysql.connector.aio import connect
# Global variable which will help to format the job sequence output.
# DISCLAIMER: this is an example for showcasing/demo purposes,
# you should avoid global variables usage for production code.
global indent
indent = 0
# MySQL Connection arguments
config = {
"host": "127.0.0.1",
"user": "root",
"password": os.environ.get("MYPASS", ":("),
"use_pure": True,
"port": 3306,
}
async def job_sleep(n):
"""Take a nap for n seconds.
This job represents any generic task - it may be or not an IO task.
"""
# Increment indent
global indent
offset = "\t" * indent
indent += 1
# Emulating a generic job/task
print(f"{offset}START_SLEEP")
await asyncio.sleep(n)
print(f"{offset}END_SLEEP")
return f"I slept for {n} seconds"
async def job_mysql():
"""Connect to a MySQL Server and do some operations.
Run queries, run procedures, insert data, etc.
"""
# Increment indent
global indent
offset = "\t" * indent
indent += 1
# MySQL operations
print(f"{offset}START_MYSQL_OPS")
async with await connect(**config) as cnx:
async with await cnx.cursor() as cur:
await cur.execute("SELECT @@version")
res = await cur.fetchone()
time.sleep(1) # for simulating that the fetch isn't immediate
print(f"{offset}END_MYSQL_OPS")
# return server version
return res
async def job_io():
"""Emulate an IO operation.
`to_thread` allows to run a blocking function asynchronously.
References:
[asyncio.to_thread]: https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
"""
# Emulating a native blocking IO procedure
def io():
"""Blocking IO operation."""
time.sleep(5)
# Increment indent
global indent
offset = "\t" * indent
indent += 1
# Showcasing how a native blocking IO procedure can be awaited,
print(f"{offset}START_IO")
await asyncio.to_thread(io)
print(f"{offset}END_IO")
return "I am an IO operation"
async def main_asynchronous():
"""Running tasks asynchronously.
References:
[asyncio.gather]: https://docs.python.org/3/library/asyncio-task.html#asyncio.gather
"""
print("-------------------- ASYNCHRONOUS --------------------")
# reset indent
global indent
indent = 0
clock = time.time()
# `asyncio.gather()` allows to run awaitable objects
# in the aws sequence asynchronously.\
# If all awaitables are completed successfully,
# the result is an aggregate list of returned values.
aws = (job_io(), job_mysql(), job_sleep(4))
returned_vals = await asyncio.gather(*aws)
print(f"Elapsed time: {time.time() - clock:0.2f}")
# The order of result values corresponds to the
# order of awaitables in aws.
print(returned_vals, end="\n" * 2)
# Example expected output
# -------------------- ASYNCHRONOUS --------------------
# START_IO
# START_MYSQL_OPS
# START_SLEEP
# END_MYSQL_OPS
# END_SLEEP
# END_IO
# Elapsed time: 5.01
# ['I am an IO operation', ('8.3.0-commercial',), 'I slept for 4 seconds']
async def main_non_asynchronous():
"""Running tasks non-asynchronously"""
print("------------------- NON-ASYNCHRONOUS -------------------")
# reset indent
global indent
indent = 0
clock = time.time()
# Sequence of awaitable objects
aws = (job_io(), job_mysql(), job_sleep(4))
# The line below this docstring is the short version of:
# coro1, coro2, coro3 = *aws
# res1 = await coro1
# res2 = await coro2
# res3 = await coro3
# returned_vals = [res1, res2, res3]
# NOTE: Simply awaiting a coro does not make the code run asynchronously!
returned_vals = [await coro for coro in aws] # this will run synchronously
print(f"Elapsed time: {time.time() - clock:0.2f}")
print(returned_vals, end="\n")
# Example expected output
# ------------------- NON-ASYNCHRONOUS -------------------
# START_IO
# END_IO
# START_MYSQL_OPS
# END_MYSQL_OPS
# START_SLEEP
# END_SLEEP
# Elapsed time: 10.07
# ['I am an IO operation', ('8.3.0-commercial',), 'I slept for 4 seconds']
if __name__ == "__main__":
# `asyncio.run()`` allows to execute a coroutine (`coro`) and return the result.
# You cannot run a coro without it.
# References:
# [asyncio.run]: https://docs.python.org/3/library/asyncio-runner.html#asyncio.run
assert asyncio.run(main_asynchronous()) == asyncio.run(main_non_asynchronous())
</pre><p>
It shows these three jobs running asynchronously:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">job_io</code>: Emulate an I/O operation; with
to_thread to allow running a blocking function asynchronously.
</p><p>
Starts first, and takes five seconds to complete so is the
last job to finish.
</p></li><li class="listitem"><p>
<code class="literal">job_mysql</code>: Connects to a MySQL server to
perform operations such as queries and stored procedures.
</p><p>
Starts second, and takes one second to complete so is the
first job to finish.
</p></li><li class="listitem"><p>
<code class="literal">job_sleep</code>: Sleeps for n seconds to
represent a generic task.
</p><p>
Starts last, and takes four seconds to complete so is the
second job to finish.
</p></li></ul></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
A lock/mutex wasn't added to the <code class="literal">indent</code>
variable because multithreading isn't used; instead the unique
active thread executes all of the jobs. Asynchronous execution
is about completing other jobs while waiting for the result of
an I/O operation.
</p></div><h3><a name="id3174"></a>Asynchronous MySQL Queries</h3><p>
This is a similar example that uses MySQL queries instead of
generic jobs.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
While cursors are not utilized in the these examples, the
principles and workflow could apply to cursors by letting every
connection object create a cursor to operate from.
</p></div><p>
Synchronous code to create and populate hundreds of tables:
</p><pre data-lang="python" class="programlisting">import os
import time
from typing import TYPE_CHECKING, Callable, List, Tuple
from mysql.connector import connect
if TYPE_CHECKING:
from mysql.connector.abstracts import (
MySQLConnectionAbstract,
)
# MySQL Connection arguments
config = {
"host": "127.0.0.1",
"user": "root",
"password": os.environ.get("MYPASS", ":("),
"use_pure": True,
"port": 3306,
}
exec_sequence = []
def create_table(
exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
) -> None:
"""Creates a table."""
if i >= len(table_names):
return False
exec_seq.append(f"start_{i}")
stmt = f"""
CREATE TABLE IF NOT EXISTS {table_names[i]} (
dish_id INT(11) UNSIGNED AUTO_INCREMENT UNIQUE KEY,
category TEXT,
dish_name TEXT,
price FLOAT,
servings INT,
order_time TIME
)
"""
cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
cnx.cmd_query(stmt)
exec_seq.append(f"end_{i}")
return True
def drop_table(
exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
) -> None:
"""Drops a table."""
if i >= len(table_names):
return False
exec_seq.append(f"start_{i}")
cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
exec_seq.append(f"end_{i}")
return True
def main(
kernel: Callable[[List[str], List[str], "MySQLConnectionAbstract", int], None],
table_names: List[str],
) -> Tuple[List, List]:
exec_seq = []
database_name = "TABLE_CREATOR"
with connect(**config) as cnx:
# Create/Setup database
cnx.cmd_query(f"CREATE DATABASE IF NOT EXISTS {database_name}")
cnx.cmd_query(f"USE {database_name}")
# Execute Kernel: Create or Delete tables
for i in range(len(table_names)):
kernel(exec_seq, table_names, cnx, i)
# Show tables
cnx.cmd_query("SHOW tables")
show_tables = cnx.get_rows()[0]
# Return execution sequence and table names retrieved with `SHOW tables;`.
return exec_seq, show_tables
if __name__ == "__main__":
# with num_tables=511 -> Elapsed time ~ 25.86
clock = time.time()
print_exec_seq = False
num_tables = 511
table_names = [f"table_sync_{n}" for n in range(num_tables)]
print("-------------------- SYNC CREATOR --------------------")
exec_seq, show_tables = main(kernel=create_table, table_names=table_names)
assert len(show_tables) == num_tables
if print_exec_seq:
print(exec_seq)
print("-------------------- SYNC DROPPER --------------------")
exec_seq, show_tables = main(kernel=drop_table, table_names=table_names)
assert len(show_tables) == 0
if print_exec_seq:
print(exec_seq)
print(f"Elapsed time: {time.time() - clock:0.2f}")
# Expected output with num_tables = 11:
# -------------------- SYNC CREATOR --------------------
# [
# "start_0",
# "end_0",
# "start_1",
# "end_1",
# "start_2",
# "end_2",
# "start_3",
# "end_3",
# "start_4",
# "end_4",
# "start_5",
# "end_5",
# "start_6",
# "end_6",
# "start_7",
# "end_7",
# "start_8",
# "end_8",
# "start_9",
# "end_9",
# "start_10",
# "end_10",
# ]
# -------------------- SYNC DROPPER --------------------
# [
# "start_0",
# "end_0",
# "start_1",
# "end_1",
# "start_2",
# "end_2",
# "start_3",
# "end_3",
# "start_4",
# "end_4",
# "start_5",
# "end_5",
# "start_6",
# "end_6",
# "start_7",
# "end_7",
# "start_8",
# "end_8",
# "start_9",
# "end_9",
# "start_10",
# "end_10",
# ]
</pre><p>
That script creates and deletes {num_tables} tables, and is fully
sequential in that it creates and deletes table_{i} before moving
to table_{i+1}.
</p><p>
An asynchronous code example for the same task:
</p><pre class="programlisting">import asyncio
import os
import time
from typing import TYPE_CHECKING, Callable, List, Tuple
from mysql.connector.aio import connect
if TYPE_CHECKING:
from mysql.connector.aio.abstracts import (
MySQLConnectionAbstract,
)
# MySQL Connection arguments
config = {
"host": "127.0.0.1",
"user": "root",
"password": os.environ.get("MYPASS", ":("),
"use_pure": True,
"port": 3306,
}
exec_sequence = []
async def create_table(
exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
) -> None:
"""Creates a table."""
if i >= len(table_names):
return False
exec_seq.append(f"start_{i}")
stmt = f"""
CREATE TABLE IF NOT EXISTS {table_names[i]} (
dish_id INT(11) UNSIGNED AUTO_INCREMENT UNIQUE KEY,
category TEXT,
dish_name TEXT,
price FLOAT,
servings INT,
order_time TIME
)
"""
await cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
await cnx.cmd_query(stmt)
exec_seq.append(f"end_{i}")
return True
async def drop_table(
exec_seq: List[str], table_names: List[str], cnx: "MySQLConnectionAbstract", i: int
) -> None:
"""Drops a table."""
if i >= len(table_names):
return False
exec_seq.append(f"start_{i}")
await cnx.cmd_query(f"DROP TABLE IF EXISTS {table_names[i]}")
exec_seq.append(f"end_{i}")
return True
async def main_async(
kernel: Callable[[List[str], List[str], "MySQLConnectionAbstract", int], None],
table_names: List[str],
num_jobs: int = 2,
) -> Tuple[List, List]:
"""The asynchronous tables creator...
Reference:
[as_completed]: https://docs.python.org/3/library/asyncio-task.html#asyncio.as_completed
"""
exec_seq = []
database_name = "TABLE_CREATOR"
# Create/Setup database
# ---------------------
# No asynchronous execution is done here.
# NOTE: observe usage WITH context manager.
async with await connect(**config) as cnx:
await cnx.cmd_query(f"CREATE DATABASE IF NOT EXISTS {database_name}")
await cnx.cmd_query(f"USE {database_name}")
config["database"] = database_name
# Open connections
# ----------------
# `as_completed` allows to run awaitable objects in the `aws` iterable asynchronously.
# NOTE: observe usage WITHOUT context manager.
aws = [connect(**config) for _ in range(num_jobs)]
cnxs: List["MySQLConnectionAbstract"] = [
await coro for coro in asyncio.as_completed(aws)
]
# Execute Kernel: Create or Delete tables
# -------------
# N tables must be created/deleted and we can run up to `num_jobs` jobs asynchronously,
# therefore we execute jobs in batches of size num_jobs`.
returned_values, i = [True], 0
while any(returned_values): # Keep running until i >= len(table_names) for all jobs
# Prepare coros: map connections/cursors and table-name IDs to jobs.
aws = [
kernel(exec_seq, table_names, cnx, i + idx) for idx, cnx in enumerate(cnxs)
]
# When i >= len(table_names) coro simply returns False, else True.
returned_values = [await coro for coro in asyncio.as_completed(aws)]
# Update table-name ID offset based on the number of jobs
i += num_jobs
# Close cursors
# -------------
# `as_completed` allows to run awaitable objects in the `aws` iterable asynchronously.
for coro in asyncio.as_completed([cnx.close() for cnx in cnxs]):
await coro
# Load table names
# ----------------
# No asynchronous execution is done here.
async with await connect(**config) as cnx:
# Show tables
await cnx.cmd_query("SHOW tables")
show_tables = (await cnx.get_rows())[0]
# Return execution sequence and table names retrieved with `SHOW tables;`.
return exec_seq, show_tables
if __name__ == "__main__":
# `asyncio.run()`` allows to execute a coroutine (`coro`) and return the result.
# You cannot run a coro without it.
# References:
# [asyncio.run]: https://docs.python.org/3/library/asyncio-runner.html#asyncio.run
# with num_tables=511 and num_jobs=3 -> Elapsed time ~ 19.09
# with num_tables=511 and num_jobs=12 -> Elapsed time ~ 13.15
clock = time.time()
print_exec_seq = False
num_tables = 511
num_jobs = 12
table_names = [f"table_async_{n}" for n in range(num_tables)]
print("-------------------- ASYNC CREATOR --------------------")
exec_seq, show_tables = asyncio.run(
main_async(kernel=create_table, table_names=table_names, num_jobs=num_jobs)
)
assert len(show_tables) == num_tables
if print_exec_seq:
print(exec_seq)
print("-------------------- ASYNC DROPPER --------------------")
exec_seq, show_tables = asyncio.run(
main_async(kernel=drop_table, table_names=table_names, num_jobs=num_jobs)
)
assert len(show_tables) == 0
if print_exec_seq:
print(exec_seq)
print(f"Elapsed time: {time.time() - clock:0.2f}")
# Expected output with num_tables = 11 and num_jobs = 3:
# -------------------- ASYNC CREATOR --------------------
# 11
# [
# "start_2",
# "start_1",
# "start_0",
# "end_2",
# "end_0",
# "end_1",
# "start_5",
# "start_3",
# "start_4",
# "end_3",
# "end_5",
# "end_4",
# "start_8",
# "start_7",
# "start_6",
# "end_7",
# "end_8",
# "end_6",
# "start_10",
# "start_9",
# "end_9",
# "end_10",
# ]
# -------------------- ASYNC DROPPER --------------------
# [
# "start_1",
# "start_2",
# "start_0",
# "end_1",
# "end_2",
# "end_0",
# "start_3",
# "start_5",
# "start_4",
# "end_4",
# "end_5",
# "end_3",
# "start_6",
# "start_8",
# "start_7",
# "end_7",
# "end_6",
# "end_8",
# "start_10",
# "start_9",
# "end_9",
# "end_10",
# ]
</pre><p>
This output shows how the job flow isn't sequential in that up to
{num_jobs} can be executed asynchronously. The jobs are run
following a batch-like approach of {num_jobs} and waits until all
terminate before launching the next batch, and the loop ends once
no tables remain to create.
</p><p>
Performance comparison for these examples: the asynchronous
implementation is about 26% faster when using 3 jobs, and 49%
faster using 12 jobs. Note that increasing the number of jobs does
add job management overhead which at some point evaporates the
initial speed-up. The optimal number of jobs is problem-dependent,
and is a value determined with experience.
</p><p>
As demonstrated, the asynchronous version requires more code to
function than the non-asynchronous variant. Is it worth the
effort? It depends on the goal as asynchronous code better
optimizes performance, such as CPU usage, whereas writing standard
synchronous code is simpler.
</p><p>
For additional information about the asyncio module, see the
official
<a class="ulink" href="https://docs.python.org/3/library/asyncio.html#module-asyncio" target="_top">Asynchronous
I/O Python Documentation</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-connection-pooling"></a>9.5 Connector/Python Connection Pooling</h2></div></div></div><p>
Simple connection pooling is supported that has these
characteristics:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
The <code class="literal">mysql.connector.pooling</code> module
implements pooling.
</p></li><li class="listitem"><p>
A pool opens a number of connections and handles thread safety
when providing connections to requesters.
</p></li><li class="listitem"><p>
The size of a connection pool is configurable at pool creation
time. It cannot be resized thereafter.
</p></li><li class="listitem"><p>
A connection pool can be named at pool creation time. If no
name is given, one is generated using the connection
parameters.
</p></li><li class="listitem"><p>
The connection pool name can be retrieved from the connection
pool or connections obtained from it.
</p></li><li class="listitem"><p>
It is possible to have multiple connection pools. This enables
applications to support pools of connections to different
MySQL servers, for example.
</p></li><li class="listitem"><p>
For each connection request, the pool provides the next
available connection. No round-robin or other scheduling
algorithm is used. If a pool is exhausted, a
<code class="literal">PoolError</code> is raised.
</p></li><li class="listitem"><p>
It is possible to reconfigure the connection parameters used
by a pool. These apply to connections obtained from the pool
thereafter. Reconfiguring individual connections obtained from
the pool by calling the connection <code class="literal">config()</code>
method is not supported.
</p></li></ul></div><p>
Applications that can benefit from connection-pooling capability
include:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Middleware that maintains multiple connections to multiple
MySQL servers and requires connections to be readily
available.
</p></li><li class="listitem"><p>
websites that can have more <span class="quote">“<span class="quote">permanent</span>”</span>
connections open to the MySQL server.
</p></li></ul></div><p>
A connection pool can be created implicitly or explicitly.
</p><p>
<span class="bold"><strong>To create a connection pool
implicitly:</strong></span> Open a connection and specify one or more
pool-related arguments (<code class="literal">pool_name</code>,
<code class="literal">pool_size</code>). For example:
</p><pre data-lang="python" class="programlisting">dbconfig = {
"database": "test",
"user": "joe"
}
cnx = mysql.connector.connect(pool_name = "mypool",
pool_size = 3,
**dbconfig)
</pre><p>
The pool name is restricted to alphanumeric characters and the
special characters <code class="literal">.</code>, <code class="literal">_</code>,
<code class="literal">*</code>, <code class="literal">$</code>, and
<code class="literal">#</code>. The pool name must be no more than
<code class="literal">pooling.CNX_POOL_MAXNAMESIZE</code> characters long
(default 64).
</p><p>
The pool size must be greater than 0 and less than or equal to
<code class="literal">pooling.CNX_POOL_MAXSIZE</code> (default 32).
</p><p>
With either the <code class="literal">pool_name</code> or
<code class="literal">pool_size</code> argument present, Connector/Python creates the
new pool. If the <code class="literal">pool_name</code> argument is not
given, the <code class="literal">connect()</code> call automatically
generates the name, composed from whichever of the
<code class="literal">host</code>, <code class="literal">port</code>,
<code class="literal">user</code>, and <code class="literal">database</code>
connection arguments are given, in that order. If the
<code class="literal">pool_size</code> argument is not given, the default
size is 5 connections.
</p><p>
Subsequent calls to <code class="literal">connect()</code> that name the
same connection pool return connections from the existing pool.
Any <code class="literal">pool_size</code> or connection parameter arguments
are ignored, so the following <code class="literal">connect()</code> calls
are equivalent to the original <code class="literal">connect()</code> call
shown earlier:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(pool_name = "mypool", pool_size = 3)
cnx = mysql.connector.connect(pool_name = "mypool", **dbconfig)
cnx = mysql.connector.connect(pool_name = "mypool")
</pre><p>
Pooled connections obtained by calling
<code class="literal">connect()</code> with a pool-related argument have a
class of <code class="literal">PooledMySQLConnection</code> (see
<a class="xref" href="#connector-python-api-pooledmysqlconnection" title="10.4 pooling.PooledMySQLConnection Class">Section 10.4, “pooling.PooledMySQLConnection Class”</a>).
<code class="literal">PooledMySQLConnection</code> pooled connection objects
are similar to <code class="literal">MySQLConnection</code> unpooled
connection objects, with these differences:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
To release a pooled connection obtained from a connection
pool, invoke its <code class="literal">close()</code> method, just as
for any unpooled connection. However, for a pooled connection,
<code class="literal">close()</code> does not actually close the
connection but returns it to the pool and makes it available
for subsequent connection requests.
</p></li><li class="listitem"><p>
A pooled connection cannot be reconfigured using its
<code class="literal">config()</code> method. Connection changes must be
done through the pool object itself, as described shortly.
</p></li><li class="listitem"><p>
A pooled connection has a <code class="literal">pool_name</code>
property that returns the pool name.
</p></li></ul></div><p>
<span class="bold"><strong>To create a connection pool
explicitly:</strong></span> Create a
<code class="literal">MySQLConnectionPool</code> object (see
<a class="xref" href="#connector-python-api-mysqlconnectionpool" title="10.3 pooling.MySQLConnectionPool Class">Section 10.3, “pooling.MySQLConnectionPool Class”</a>):
</p><pre data-lang="python" class="programlisting">dbconfig = {
"database": "test",
"user": "joe"
}
cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",
pool_size = 3,
**dbconfig)
</pre><p>
To request a connection from the pool, use its
<code class="literal">get_connection()</code> method:
</p><pre data-lang="python" class="programlisting">cnx1 = cnxpool.get_connection()
cnx2 = cnxpool.get_connection()
</pre><p>
When you create a connection pool explicitly, it is possible to
use the pool object's <code class="literal">set_config()</code> method to
reconfigure the pool connection parameters:
</p><pre data-lang="python" class="programlisting">dbconfig = {
"database": "performance_schema",
"user": "admin",
"password": "<em class="replaceable"><code>password</code></em>"
}
cnxpool.set_config(**dbconfig)
</pre><p>
Connections requested from the pool after the configuration change
use the new parameters. Connections obtained before the change
remain unaffected, but when they are closed (returned to the pool)
are reopened with the new parameters before being returned by the
pool for subsequent connection requests.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-django-backend"></a>9.6 Connector/Python Django Back End</h2></div></div></div><p>
Connector/Python includes a <code class="literal">mysql.connector.django</code> module
that provides a Django back end for MySQL. This back end supports
new features found as of MySQL 5.6 such as fractional seconds
support for temporal data types.
</p><h3><a name="id3283"></a>Django Configuration</h3><p>
Django uses a configuration file named
<code class="filename">settings.py</code> that contains a variable called
<code class="literal">DATABASES</code> (see
<a class="ulink" href="https://docs.djangoproject.com/en/1.5/ref/settings/#std:setting-DATABASES" target="_top">https://docs.djangoproject.com/en/1.5/ref/settings/#std:setting-DATABASES</a>).
To configure Django to use Connector/Python as the MySQL back end, the
example found in the Django manual can be used as a basis:
</p><pre data-lang="python" class="programlisting">DATABASES = {
'default': {
'NAME': 'user_data',
'ENGINE': 'mysql.connector.django',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'mysql_user',
'PASSWORD': '<em class="replaceable"><code>password</code></em>',
'OPTIONS': {
'autocommit': True,
'use_oure': True,
'init_command': "SET foo='bar';"
},
}
}
</pre><p>
It is possible to add more connection arguments using
<code class="literal">OPTIONS</code>.
</p><h3><a name="id3292"></a>Support for MySQL Features</h3><p>
Django can launch the MySQL client application
<span class="command"><strong>mysql</strong></span>. When the Connector/Python back end does this, it
arranges for the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_sql_mode" target="_top"><code class="literal">sql_mode</code></a> system
variable to be set to <code class="literal">TRADITIONAL</code> at startup.
</p><p>
Some MySQL features are enabled depending on the server version.
For example, support for fractional seconds precision is enabled
when connecting to a server from MySQL 5.6.4 or higher. Django's
<code class="literal">DateTimeField</code> is stored in a MySQL column
defined as <code class="literal">DATETIME(6)</code>, and
<code class="literal">TimeField</code> is stored as
<code class="literal">TIME(6)</code>. For more information about fractional
seconds support, see <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html" target="_top">Fractional Seconds in Time Values</a>.
</p><p>
Using a custom class for data type conversation is supported as a
subclass of
<span class="emphasis"><em>mysql.connector.django.base.DjangoMySQLConverter</em></span>.
This support was added in Connector/Python 8.0.29.
</p></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-reference"></a>Chapter 10 Connector/Python API Reference</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysql-connector">10.1 mysql.connector Module</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysql-connector-connect">10.1.1 mysql.connector.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-apilevel">10.1.2 mysql.connector.apilevel Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-paramstyle">10.1.3 mysql.connector.paramstyle Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-threadsafety">10.1.4 mysql.connector.threadsafety Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version">10.1.5 mysql.connector.__version__ Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version-info">10.1.6 mysql.connector.__version_info__ Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnection">10.2 connection.MySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnection-constructor">10.2.1 connection.MySQLConnection() Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-close">10.2.2 MySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-commit">10.2.3 MySQLConnection.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-config">10.2.4 MySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connect">10.2.5 MySQLConnection.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cursor">10.2.6 MySQLConnection.cursor() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-change-user">10.2.7 MySQLConnection.cmd_change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-debug">10.2.8 MySQLConnection.cmd_debug() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-init-db">10.2.9 MySQLConnection.cmd_init_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-ping">10.2.10 MySQLConnection.cmd_ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-info">10.2.11 MySQLConnection.cmd_process_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-kill">10.2.12 MySQLConnection.cmd_process_kill() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query">10.2.13 MySQLConnection.cmd_query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query-iter">10.2.14 MySQLConnection.cmd_query_iter() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-quit">10.2.15 MySQLConnection.cmd_quit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-refresh">10.2.16 MySQLConnection.cmd_refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-reset-connection">10.2.17 MySQLConnection.cmd_reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-shutdown">10.2.18 MySQLConnection.cmd_shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-statistics">10.2.19 MySQLConnection.cmd_statistics() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-disconnect">10.2.20 MySQLConnection.disconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-row">10.2.21 MySQLConnection.get_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-rows">10.2.22 MySQLConnection.get_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-info">10.2.23 MySQLConnection.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-version">10.2.24 MySQLConnection.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-is-connected">10.2.25 MySQLConnection.is_connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-isset-client-flag">10.2.26 MySQLConnection.isset_client_flag() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-ping">10.2.27 MySQLConnection.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reconnect">10.2.28 MySQLConnection.reconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reset-session">10.2.29 MySQLConnection.reset_session() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-rollback">10.2.30 MySQLConnection.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-charset-collation">10.2.31 MySQLConnection.set_charset_collation() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-client-flags">10.2.32 MySQLConnection.set_client_flags() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-shutdown">10.2.33 MySQLConnection.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-start-transaction">10.2.34 MySQLConnection.start_transaction() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-autocommit">10.2.35 MySQLConnection.autocommit Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unread-results">10.2.36 MySQLConnection.unread_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-can-consume-results">10.2.37 MySQLConnection.can_consume_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-charset">10.2.38 MySQLConnection.charset Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-client-flags">10.2.39 MySQLConnection.client_flags Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-collation">10.2.40 MySQLConnection.collation Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connected">10.2.41 MySQLConnection.connected Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connection-id">10.2.42 MySQLConnection.connection_id Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-converter-class">10.2.43 MySQLConnection.converter-class Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-database">10.2.44 MySQLConnection.database Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-warnings">10.2.45 MySQLConnection.get_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-in-transaction">10.2.46 MySQLConnection.in_transaction Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-raise-on-warnings">10.2.47 MySQLConnection.raise_on_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-host">10.2.48 MySQLConnection.server_host Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-info">10.2.49 MySQLConnection.server_info Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-port">10.2.50 MySQLConnection.server_port Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-version">10.2.51 MySQLConnection.server_version Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-sql-mode">10.2.52 MySQLConnection.sql_mode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-time-zone">10.2.53 MySQLConnection.time_zone Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-use-unicode">10.2.54 MySQLConnection.use_unicode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unix-socket">10.2.55 MySQLConnection.unix_socket Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-user">10.2.56 MySQLConnection.user Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool">10.3 pooling.MySQLConnectionPool Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-constructor">10.3.1 pooling.MySQLConnectionPool Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-add-connection">10.3.2 MySQLConnectionPool.add_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-get-connection">10.3.3 MySQLConnectionPool.get_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-set-config">10.3.4 MySQLConnectionPool.set_config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-pool-name">10.3.5 MySQLConnectionPool.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection">10.4 pooling.PooledMySQLConnection Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-constructor">10.4.1 pooling.PooledMySQLConnection Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-close">10.4.2 PooledMySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-config">10.4.3 PooledMySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-pool-name">10.4.4 PooledMySQLConnection.pool_name Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-mysqlcursor">10.5 cursor.MySQLCursor Class</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursor-constructor">10.5.1 cursor.MySQLCursor Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-add-attribute">10.5.2 MySQLCursor.add_attribute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-clear-attributes">10.5.3 MySQLCursor.clear_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-get-attributes">10.5.4 MySQLCursor.get_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-callproc">10.5.5 MySQLCursor.callproc() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-close">10.5.6 MySQLCursor.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-execute">10.5.7 MySQLCursor.execute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-executemany">10.5.8 MySQLCursor.executemany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchall">10.5.9 MySQLCursor.fetchall() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchmany">10.5.10 MySQLCursor.fetchmany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchone">10.5.11 MySQLCursor.fetchone() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-nextset">10.5.12 MySQLCursor.nextset() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchsets">10.5.13 MySQLCursor.fetchsets() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchwarnings">10.5.14 MySQLCursor.fetchwarnings() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-stored-results">10.5.15 MySQLCursor.stored_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-column-names">10.5.16 MySQLCursor.column_names Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-description">10.5.17 MySQLCursor.description Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-warnings">10.5.18 MySQLCursor.warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-lastrowid">10.5.19 MySQLCursor.lastrowid Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-rowcount">10.5.20 MySQLCursor.rowcount Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-statement">10.5.21 MySQLCursor.statement Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-with-rows">10.5.22 MySQLCursor.with_rows Property</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-cursor-subclasses">10.6 Subclasses cursor.MySQLCursor</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffered">10.6.1 cursor.MySQLCursorBuffered Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorraw">10.6.2 cursor.MySQLCursorRaw Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursordict">10.6.3 cursor.MySQLCursorDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffereddict">10.6.4 cursor.MySQLCursorBufferedDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorprepared">10.6.5 cursor.MySQLCursorPrepared Class</a></span></dt></dl></dd><dt><span class="section"><a href="#connector-python-api-clientflag">10.7 constants.ClientFlag Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-fieldtype">10.8 constants.FieldType Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-sqlmode">10.9 constants.SQLMode Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-characterset">10.10 constants.CharacterSet Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-refreshoption">10.11 constants.RefreshOption Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors">10.12 Errors and Exceptions</a></span></dt><dd><dl><dt><span class="section"><a href="#connector-python-api-errorcode">10.12.1 errorcode Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-error">10.12.2 errors.Error Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-dataerror">10.12.3 errors.DataError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-databaseerror">10.12.4 errors.DatabaseError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-integrityerror">10.12.5 errors.IntegrityError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-interfaceerror">10.12.6 errors.InterfaceError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-internalerror">10.12.7 errors.InternalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-notsupportederror">10.12.8 errors.NotSupportedError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-operationalerror">10.12.9 errors.OperationalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-poolerror">10.12.10 errors.PoolError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-programmingerror">10.12.11 errors.ProgrammingError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-warning">10.12.12 errors.Warning Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-custom-error-exception">10.12.13 errors.custom_error_exception() Function</a></span></dt></dl></dd></dl></div><p>
This chapter contains the public API reference for Connector/Python. Examples
should be considered working for Python 2.7, and Python 3.1 and
greater. They might also work for older versions (such as Python
2.4) unless they use features introduced in newer Python versions.
For example, exception handling using the <code class="literal">as</code>
keyword was introduced in Python 2.6 and will not work in Python
2.4.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Python 2.7 support was removed in Connector/Python 8.0.24.
</p></div><p>
The following overview shows the <code class="literal">mysql.connector</code>
package with its modules. Currently, only the most useful modules,
classes, and methods for end users are documented.
</p><pre data-lang="simple" class="programlisting">mysql.connector
errorcode
errors
connection
constants
conversion
cursor
dbapi
locales
eng
client_error
protocol
utils
</pre><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysql-connector"></a>10.1 mysql.connector Module</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysql-connector-connect">10.1.1 mysql.connector.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-apilevel">10.1.2 mysql.connector.apilevel Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-paramstyle">10.1.3 mysql.connector.paramstyle Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-threadsafety">10.1.4 mysql.connector.threadsafety Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version">10.1.5 mysql.connector.__version__ Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysql-connector-version-info">10.1.6 mysql.connector.__version_info__ Property</a></span></dt></dl></div><a class="indexterm" name="id3316"></a><a class="indexterm" name="id3318"></a><p>
The <code class="literal">mysql.connector</code> module provides top-level
methods and properties.
</p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-connect"></a>10.1.1 mysql.connector.connect() Method</h3></div></div></div><a class="indexterm" name="id3324"></a><a class="indexterm" name="id3326"></a><p>
This method sets up a connection, establishing a session with
the MySQL server. If no arguments are given, it uses the already
configured or default values. For a complete list of possible
arguments, see <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p><p>
A connection with the MySQL server can be established using
either the <code class="literal">mysql.connector.connect()</code> method
or the <code class="literal">mysql.connector.MySQLConnection()</code>
class:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='joe', database='test')
cnx = MySQLConnection(user='joe', database='test')
</pre><p>
For descriptions of connection methods and properties, see
<a class="xref" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class">Section 10.2, “connection.MySQLConnection Class”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-apilevel"></a>10.1.2 mysql.connector.apilevel Property</h3></div></div></div><a class="indexterm" name="id3338"></a><a class="indexterm" name="id3340"></a><p>
This property is a string that indicates the supported DB API
level.
</p><pre data-lang="python" class="programlisting">
>>> mysql.connector.apilevel
'2.0'</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-paramstyle"></a>10.1.3 mysql.connector.paramstyle Property</h3></div></div></div><a class="indexterm" name="id3346"></a><a class="indexterm" name="id3348"></a><p>
This property is a string that indicates the Connector/Python default
parameter style.
</p><pre data-lang="python" class="programlisting">
>>> mysql.connector.paramstyle
'pyformat'</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-threadsafety"></a>10.1.4 mysql.connector.threadsafety Property</h3></div></div></div><a class="indexterm" name="id3354"></a><a class="indexterm" name="id3356"></a><p>
This property is an integer that indicates the supported level
of thread safety provided by Connector/Python.
</p><pre data-lang="python" class="programlisting">
>>> mysql.connector.threadsafety
1</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-version"></a>10.1.5 mysql.connector.__version__ Property</h3></div></div></div><a class="indexterm" name="id3362"></a><a class="indexterm" name="id3364"></a><p>
This property indicates the Connector/Python version as a string. It is
available as of Connector/Python 1.1.0.
</p><pre data-lang="python" class="programlisting">
>>> mysql.connector.__version__
'1.1.0'</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysql-connector-version-info"></a>10.1.6 mysql.connector.__version_info__ Property</h3></div></div></div><a class="indexterm" name="id3370"></a><a class="indexterm" name="id3372"></a><p>
This property indicates the Connector/Python version as an array of version
components. It is available as of Connector/Python 1.1.0.
</p><pre data-lang="python" class="programlisting">
>>> mysql.connector.__version_info__
(1, 1, 0, 'a', 0)</pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysqlconnection"></a>10.2 connection.MySQLConnection Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlconnection-constructor">10.2.1 connection.MySQLConnection() Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-close">10.2.2 MySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-commit">10.2.3 MySQLConnection.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-config">10.2.4 MySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connect">10.2.5 MySQLConnection.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cursor">10.2.6 MySQLConnection.cursor() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-change-user">10.2.7 MySQLConnection.cmd_change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-debug">10.2.8 MySQLConnection.cmd_debug() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-init-db">10.2.9 MySQLConnection.cmd_init_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-ping">10.2.10 MySQLConnection.cmd_ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-info">10.2.11 MySQLConnection.cmd_process_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-process-kill">10.2.12 MySQLConnection.cmd_process_kill() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query">10.2.13 MySQLConnection.cmd_query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-query-iter">10.2.14 MySQLConnection.cmd_query_iter() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-quit">10.2.15 MySQLConnection.cmd_quit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-refresh">10.2.16 MySQLConnection.cmd_refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-reset-connection">10.2.17 MySQLConnection.cmd_reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-shutdown">10.2.18 MySQLConnection.cmd_shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-cmd-statistics">10.2.19 MySQLConnection.cmd_statistics() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-disconnect">10.2.20 MySQLConnection.disconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-row">10.2.21 MySQLConnection.get_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-rows">10.2.22 MySQLConnection.get_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-info">10.2.23 MySQLConnection.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-server-version">10.2.24 MySQLConnection.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-is-connected">10.2.25 MySQLConnection.is_connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-isset-client-flag">10.2.26 MySQLConnection.isset_client_flag() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-ping">10.2.27 MySQLConnection.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reconnect">10.2.28 MySQLConnection.reconnect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-reset-session">10.2.29 MySQLConnection.reset_session() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-rollback">10.2.30 MySQLConnection.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-charset-collation">10.2.31 MySQLConnection.set_charset_collation() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-set-client-flags">10.2.32 MySQLConnection.set_client_flags() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-shutdown">10.2.33 MySQLConnection.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-start-transaction">10.2.34 MySQLConnection.start_transaction() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-autocommit">10.2.35 MySQLConnection.autocommit Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unread-results">10.2.36 MySQLConnection.unread_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-can-consume-results">10.2.37 MySQLConnection.can_consume_results Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-charset">10.2.38 MySQLConnection.charset Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-client-flags">10.2.39 MySQLConnection.client_flags Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-collation">10.2.40 MySQLConnection.collation Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connected">10.2.41 MySQLConnection.connected Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-connection-id">10.2.42 MySQLConnection.connection_id Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-converter-class">10.2.43 MySQLConnection.converter-class Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-database">10.2.44 MySQLConnection.database Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-get-warnings">10.2.45 MySQLConnection.get_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-in-transaction">10.2.46 MySQLConnection.in_transaction Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-raise-on-warnings">10.2.47 MySQLConnection.raise_on_warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-host">10.2.48 MySQLConnection.server_host Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-info">10.2.49 MySQLConnection.server_info Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-port">10.2.50 MySQLConnection.server_port Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-server-version">10.2.51 MySQLConnection.server_version Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-sql-mode">10.2.52 MySQLConnection.sql_mode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-time-zone">10.2.53 MySQLConnection.time_zone Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-use-unicode">10.2.54 MySQLConnection.use_unicode Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-unix-socket">10.2.55 MySQLConnection.unix_socket Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnection-user">10.2.56 MySQLConnection.user Property</a></span></dt></dl></div><a class="indexterm" name="id3378"></a><a class="indexterm" name="id3380"></a><p>
The <code class="literal">MySQLConnection</code> class is used to open and
manage a connection to a MySQL server. It also used to send
commands and SQL statements and read the results.
</p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-constructor"></a>10.2.1 connection.MySQLConnection() Constructor</h3></div></div></div><a class="indexterm" name="id3386"></a><a class="indexterm" name="id3388"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx = MySQLConnection(**kwargs)
</pre><p>
The <code class="literal">MySQLConnection</code> constructor initializes
the attributes and when at least one argument is passed, it
tries to connect to the MySQL server.
</p><p>
For a complete list of arguments, see
<a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-close"></a>10.2.2 MySQLConnection.close() Method</h3></div></div></div><a class="indexterm" name="id3398"></a><a class="indexterm" name="id3400"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.close()
</pre><p>
<code class="literal">close()</code> is a synonym for
<code class="literal">disconnect()</code>. See
<a class="xref" href="#connector-python-api-mysqlconnection-disconnect" title="10.2.20 MySQLConnection.disconnect() Method">Section 10.2.20, “MySQLConnection.disconnect() Method”</a>.
</p><p>
For a connection obtained from a connection pool,
<code class="literal">close()</code> does not actually close it but
returns it to the pool and makes it available for subsequent
connection requests. See
<a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-commit"></a>10.2.3 MySQLConnection.commit() Method</h3></div></div></div><a class="indexterm" name="id3413"></a><a class="indexterm" name="id3415"></a><p>
This method sends a <code class="literal">COMMIT</code> statement to the
MySQL server, committing the current transaction. Since by
default Connector/Python does not autocommit, it is important to call this
method after every transaction that modifies data for tables
that use transactional storage engines.
</p><pre data-lang="python" class="programlisting">
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s), (%s)", ('Jane', 'Mary'))
>>> cnx.commit()</pre><p>
To roll back instead and discard modifications, see the
<a class="link" href="#connector-python-api-mysqlconnection-rollback" title="10.2.30 MySQLConnection.rollback() Method">rollback()</a>
method.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-config"></a>10.2.4 MySQLConnection.config() Method</h3></div></div></div><a class="indexterm" name="id3424"></a><a class="indexterm" name="id3426"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.config(**kwargs)
</pre><p>
Configures a <code class="literal">MySQLConnection</code> instance after
it has been instantiated. For a complete list of possible
arguments, see <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p><p>
Arguments:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">kwargs</code>: Connection arguments.
</p></li></ul></div><p>
You could use the <code class="literal">config()</code> method to change
(for example) the user name, then call
<code class="literal">reconnect()</code>.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(user='joe', database='test')
# Connected as 'joe'
cnx.config(user='jane')
cnx.reconnect()
# Now connected as 'jane'
</pre><p>
For a connection obtained from a connection pool,
<code class="literal">config()</code> raises an exception. See
<a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-connect"></a>10.2.5 MySQLConnection.connect() Method</h3></div></div></div><a class="indexterm" name="id3448"></a><a class="indexterm" name="id3450"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">MySQLConnection.connect(**kwargs)
</pre><p>
This method sets up a connection, establishing a session with
the MySQL server. If no arguments are given, it uses the already
configured or default values. For a complete list of possible
arguments, see <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p><p>
Arguments:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">kwargs</code>: Connection arguments.
</p></li></ul></div><p>
Example:
</p><pre data-lang="python" class="programlisting">cnx = MySQLConnection(user='joe', database='test')
</pre><p>
For a connection obtained from a conection pool, the connection
object class is <code class="literal">PooledMySQLConnection</code>. A
pooled connection differs from an unpooled connection as
described in
<a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cursor"></a>10.2.6 MySQLConnection.cursor() Method</h3></div></div></div><a class="indexterm" name="id3468"></a><a class="indexterm" name="id3470"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor([arg=value[, arg=value]...])
</pre><p>
This method returns a <code class="literal">MySQLCursor()</code> object,
or a subclass of it depending on the passed arguments. The
returned object is a <code class="literal">cursor.CursorBase</code>
instance. For more information about cursor objects, see
<a class="xref" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">Section 10.5, “cursor.MySQLCursor Class”</a>, and
<a class="xref" href="#connector-python-api-cursor-subclasses" title="10.6 Subclasses cursor.MySQLCursor">Section 10.6, “Subclasses cursor.MySQLCursor”</a>.
</p><p>
Arguments may be passed to the <code class="literal">cursor()</code>
method to control what type of cursor to create:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
If <code class="literal">buffered</code> is <code class="literal">True</code>,
the cursor fetches all rows from the server after an
operation is executed. This is useful when queries return
small result sets. <code class="literal">buffered</code> can be used
alone, or in combination with the
<code class="literal">dictionary</code> argument.
</p><p>
<code class="literal">buffered</code> can also be passed to
<a class="link" href="#connector-python-api-mysql-connector-connect" title="10.1.1 mysql.connector.connect() Method"><code class="literal">connect()</code></a>
to set the default buffering mode for all cursors created
from the connection object. See
<a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p><p>
For information about the implications of buffering, see
<a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.
</p></li><li class="listitem"><p>
If <code class="literal">raw</code> is <code class="literal">True</code>, the
cursor skips the conversion from MySQL data types to Python
types when fetching rows. A raw cursor is usually used to
get better performance or when you want to do the conversion
yourself.
</p><p>
<code class="literal">raw</code> can also be passed to
<a class="link" href="#connector-python-api-mysql-connector-connect" title="10.1.1 mysql.connector.connect() Method"><code class="literal">connect()</code></a>
to set the default raw mode for all cursors created from the
connection object. See
<a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p></li><li class="listitem"><p>
If <code class="literal">dictionary</code> is <code class="literal">True</code>,
the cursor returns rows as dictionaries. This argument is
available as of Connector/Python 2.0.0.
</p></li><li class="listitem"><p>
If <code class="literal">prepared</code> is <code class="literal">True</code>,
the cursor is used for executing prepared statements. This
argument is available as of Connector/Python 1.1.2. The C extension
supports this as of Connector/Python 8.0.17.
</p></li><li class="listitem"><p>
The <code class="literal">cursor_class</code> argument can be used to
pass a class to use for instantiating a new cursor. It must
be a subclass of <code class="literal">cursor.CursorBase</code>.
</p></li></ul></div><p>
The returned object depends on the combination of the arguments.
Examples:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
If not buffered and not raw: <code class="literal">MySQLCursor</code>
</p></li><li class="listitem"><p>
If buffered and not raw:
<code class="literal">MySQLCursorBuffered</code>
</p></li><li class="listitem"><p>
If not buffered and raw: <code class="literal">MySQLCursorRaw</code>
</p></li><li class="listitem"><p>
If buffered and raw:
<code class="literal">MySQLCursorBufferedRaw</code>
</p></li></ul></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-change-user"></a>10.2.7 MySQLConnection.cmd_change_user() Method</h3></div></div></div><a class="indexterm" name="id3532"></a><a class="indexterm" name="id3534"></a><p>
Changes the user using <code class="literal">username</code> and
<code class="literal">password</code>. It also causes the specified
<code class="literal">database</code> to become the default (current)
database. It is also possible to change the character set using
the <code class="literal">charset</code> argument.
</p><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.cmd_change_user(username='', password='', database='', charset=33)
</pre><p>
Returns a dictionary containing the OK packet information.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-debug"></a>10.2.8 MySQLConnection.cmd_debug() Method</h3></div></div></div><a class="indexterm" name="id3546"></a><a class="indexterm" name="id3548"></a><p>
Instructs the server to write debugging information to the error
log. The connected user must have the
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_super" target="_top"><code class="literal">SUPER</code></a> privilege.
</p><p>
Returns a dictionary containing the OK packet information.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-init-db"></a>10.2.9 MySQLConnection.cmd_init_db() Method</h3></div></div></div><a class="indexterm" name="id3556"></a><a class="indexterm" name="id3558"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.cmd_init_db(db_name)
</pre><p>
This method makes specified database the default (current)
database. In subsequent queries, this database is the default
for table references that include no explicit database
qualifier.
</p><p>
Returns a dictionary containing the OK packet information.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-ping"></a>10.2.10 MySQLConnection.cmd_ping() Method</h3></div></div></div><a class="indexterm" name="id3566"></a><a class="indexterm" name="id3568"></a><p>
Checks whether the connection to the server is working.
</p><p>
This method is not to be used directly. Use
<a class="link" href="#connector-python-api-mysqlconnection-ping" title="10.2.27 MySQLConnection.ping() Method">ping()</a>
or
<a class="link" href="#connector-python-api-mysqlconnection-is-connected" title="10.2.25 MySQLConnection.is_connected() Method">is_connected()</a>
instead.
</p><p>
Returns a dictionary containing the OK packet information.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-process-info"></a>10.2.11 MySQLConnection.cmd_process_info() Method</h3></div></div></div><a class="indexterm" name="id3577"></a><a class="indexterm" name="id3579"></a><p>
This method raises the NotSupportedError exception. Instead, use
the <code class="literal">SHOW PROCESSLIST</code> statement or query the
tables found in the database
<code class="literal">INFORMATION_SCHEMA</code>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This MySQL Server functionality is deprecated.
</p></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-process-kill"></a>10.2.12 MySQLConnection.cmd_process_kill() Method</h3></div></div></div><a class="indexterm" name="id3589"></a><a class="indexterm" name="id3591"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.cmd_process_kill(mysql_pid)
</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This MySQL Server functionality is deprecated.
</p></div><p>
Asks the server to kill the thread specified by
<code class="literal">mysql_pid</code>. Although still available, it is
better to use the <code class="literal">KILL</code> SQL statement.
</p><p>
Returns a dictionary containing the OK packet information.
</p><p>
The following two lines have the same effect:
</p><pre data-lang="python" class="programlisting">
>>> cnx.cmd_process_kill(123)
>>> cnx.cmd_query('KILL 123')</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-query"></a>10.2.13 MySQLConnection.cmd_query() Method</h3></div></div></div><a class="indexterm" name="id3606"></a><a class="indexterm" name="id3608"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.cmd_query(statement)
</pre><p>
This method sends the given <code class="literal">statement</code> to the
MySQL server and returns a result. To send multiple statements,
use the
<a class="link" href="#connector-python-api-mysqlconnection-cmd-query-iter" title="10.2.14 MySQLConnection.cmd_query_iter() Method">cmd_query_iter()</a>
method instead.
</p><p>
The returned dictionary contains information depending on what
kind of query was executed. If the query is a
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statement, the result
contains information about columns. Other statements return a
dictionary containing OK or EOF packet information.
</p><p>
Errors received from the MySQL server are raised as exceptions.
An <code class="literal">InterfaceError</code> is raised when multiple
results are found.
</p><p>
Returns a dictionary.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-query-iter"></a>10.2.14 MySQLConnection.cmd_query_iter() Method</h3></div></div></div><a class="indexterm" name="id3623"></a><a class="indexterm" name="id3625"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.cmd_query_iter(statement)
</pre><p>
Similar to the
<a class="link" href="#connector-python-api-mysqlconnection-cmd-query" title="10.2.13 MySQLConnection.cmd_query() Method">cmd_query()</a>
method, but returns a generator object to iterate through
results. Use <code class="literal">cmd_query_iter()</code> when sending
multiple statements, and separate the statements with
semicolons.
</p><p>
The following example shows how to iterate through the results
after sending multiple statements:
</p><pre data-lang="python" class="programlisting">statement = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cnx.cmd_query_iter(statement):
if 'columns' in result:
columns = result['columns']
rows = cnx.get_rows()
else:
# do something useful with INSERT result
</pre><p>
Returns a generator object.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-quit"></a>10.2.15 MySQLConnection.cmd_quit() Method</h3></div></div></div><a class="indexterm" name="id3637"></a><a class="indexterm" name="id3639"></a><p>
This method sends a <code class="literal">QUIT</code> command to the MySQL
server, closing the current connection. Since there is no
response from the MySQL server, the packet that was sent is
returned.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-refresh"></a>10.2.16 MySQLConnection.cmd_refresh() Method</h3></div></div></div><a class="indexterm" name="id3645"></a><a class="indexterm" name="id3647"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.cmd_refresh(options)
</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This MySQL Server functionality is deprecated.
</p></div><p>
This method flushes tables or caches, or resets replication
server information. The connected user must have the
<code class="literal">RELOAD</code> privilege.
</p><p>
The <code class="literal">options</code> argument should be a bitmask
value constructed using constants from the
<code class="literal">constants.RefreshOption</code> class.
</p><p>
For a list of options, see
<a class="xref" href="#connector-python-api-refreshoption" title="10.11 constants.RefreshOption Class">Section 10.11, “constants.RefreshOption Class”</a>.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">
>>> from mysql.connector import RefreshOption
>>> refresh = RefreshOption.LOG | RefreshOption.THREADS
>>> cnx.cmd_refresh(refresh)</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-reset-connection"></a>10.2.17 MySQLConnection.cmd_reset_connection() Method</h3></div></div></div><a class="indexterm" name="id3665"></a><a class="indexterm" name="id3667"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.cmd_reset_connection()
</pre><p>
Resets the connection by sending a
<code class="literal">COM_RESET_CONNECTION</code> command to the server to
clear the session state.
</p><p>
This method permits the session state to be cleared without
reauthenticating. For MySQL servers older than 5.7.3 (when
<code class="literal">COM_RESET_CONNECTION</code> was introduced), the
<a class="link" href="#connector-python-api-mysqlconnection-reset-session" title="10.2.29 MySQLConnection.reset_session() Method"><code class="literal">reset_session()</code></a>
method can be used instead. That method resets the session state
by reauthenticating, which is more expensive.
</p><p>
This method was added in Connector/Python 1.2.1.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-shutdown"></a>10.2.18 MySQLConnection.cmd_shutdown() Method</h3></div></div></div><a class="indexterm" name="id3680"></a><a class="indexterm" name="id3682"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This MySQL Server functionality is deprecated.
</p></div><p>
Asks the database server to shut down. The connected user must
have the <code class="literal">SHUTDOWN</code> privilege.
</p><p>
Returns a dictionary containing the OK packet information.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-cmd-statistics"></a>10.2.19 MySQLConnection.cmd_statistics() Method</h3></div></div></div><a class="indexterm" name="id3692"></a><a class="indexterm" name="id3694"></a><p>
Returns a dictionary containing information about the MySQL
server including uptime in seconds and the number of running
threads, questions, reloads, and open tables.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-disconnect"></a>10.2.20 MySQLConnection.disconnect() Method</h3></div></div></div><a class="indexterm" name="id3699"></a><a class="indexterm" name="id3701"></a><p>
This method tries to send a <code class="literal">QUIT</code> command and
close the socket. It raises no exceptions.
</p><p>
<code class="literal">MySQLConnection.close()</code> is a synonymous
method name and more commonly used.
</p><p>
To shut down the connection without sending a
<code class="literal">QUIT</code> command first, use
<a class="link" href="#connector-python-api-mysqlconnection-shutdown" title="10.2.33 MySQLConnection.shutdown() Method"><code class="literal">shutdown()</code></a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-row"></a>10.2.21 MySQLConnection.get_row() Method</h3></div></div></div><a class="indexterm" name="id3713"></a><a class="indexterm" name="id3715"></a><p>
This method retrieves the next row of a query result set,
returning a tuple.
</p><p>
The tuple returned by <code class="literal">get_row()</code> consists of:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
The row as a tuple containing byte objects, or
<code class="literal">None</code> when no more rows are available.
</p></li><li class="listitem"><p>
EOF packet information as a dictionary containing
<code class="literal">status_flag</code> and
<code class="literal">warning_count</code>, or <code class="literal">None</code>
when the row returned is not the last row.
</p></li></ul></div><p>
The <code class="literal">get_row()</code> method is used by
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
to fetch rows.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-rows"></a>10.2.22 MySQLConnection.get_rows() Method</h3></div></div></div><a class="indexterm" name="id3734"></a><a class="indexterm" name="id3736"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.get_rows(count=None)
</pre><p>
This method retrieves all or remaining rows of a query result
set, returning a tuple containing the rows as sequences and the
EOF packet information. The count argument can be used to obtain
a given number of rows. If count is not specified or is
<code class="literal">None</code>, all rows are retrieved.
</p><p>
The tuple returned by <code class="literal">get_rows()</code> consists of:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
A list of tuples containing the row data as byte objects, or
an empty list when no rows are available.
</p></li><li class="listitem"><p>
EOF packet information as a dictionary containing
<code class="literal">status_flag</code> and
<code class="literal">warning_count</code>.
</p></li></ul></div><p>
An <code class="literal">InterfaceError</code> is raised when all rows
have been retrieved.
</p><p>
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">MySQLCursor</a>
uses the <code class="literal">get_rows()</code> method to fetch rows.
</p><p>
Returns a tuple.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-server-info"></a>10.2.23 MySQLConnection.get_server_info() Method</h3></div></div></div><a class="indexterm" name="id3759"></a><a class="indexterm" name="id3761"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This method has been deprecated as of 9.3.0. Use the property
method
<a class="xref" href="#connector-python-api-mysqlconnection-server-info" title="10.2.49 MySQLConnection.server_info Property">Section 10.2.49, “MySQLConnection.server_info Property”</a>
instead.
</p></div><p>
This method returns the MySQL server information verbatim as a
string, for example <code class="literal">'5.6.11-log'</code>, or
<code class="literal">None</code> when not connected.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-server-version"></a>10.2.24 MySQLConnection.get_server_version() Method</h3></div></div></div><a class="indexterm" name="id3772"></a><a class="indexterm" name="id3774"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This method has been deprecated as of 9.3.0. Use the property
method
<a class="xref" href="#connector-python-api-mysqlconnection-server-version" title="10.2.51 MySQLConnection.server_version Property">Section 10.2.51, “MySQLConnection.server_version Property”</a>
instead.
</p></div><p>
This method returns the MySQL server version as a tuple, or
<code class="literal">None</code> when not connected.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-is-connected"></a>10.2.25 MySQLConnection.is_connected() Method</h3></div></div></div><a class="indexterm" name="id3784"></a><a class="indexterm" name="id3786"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This method has been deprecated as of 9.3.0. Use the property
method
<a class="xref" href="#connector-python-api-mysqlconnection-connected" title="10.2.41 MySQLConnection.connected Property">Section 10.2.41, “MySQLConnection.connected Property”</a>
instead.
</p></div><p>
Reports whether the connection to MySQL Server is available.
</p><p>
This method checks whether the connection to MySQL is available
using the
<a class="link" href="#connector-python-api-mysqlconnection-ping" title="10.2.27 MySQLConnection.ping() Method">ping()</a>
method, but unlike <code class="literal">ping()</code>,
<code class="literal">is_connected()</code> returns
<code class="literal">True</code> when the connection is available,
<code class="literal">False</code> otherwise.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-isset-client-flag"></a>10.2.26 MySQLConnection.isset_client_flag() Method</h3></div></div></div><a class="indexterm" name="id3801"></a><a class="indexterm" name="id3803"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.isset_client_flag(flag)
</pre><p>
This method returns <code class="literal">True</code> if the client flag
was set, <code class="literal">False</code> otherwise.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-ping"></a>10.2.27 MySQLConnection.ping() Method</h3></div></div></div><a class="indexterm" name="id3812"></a><a class="indexterm" name="id3814"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.ping(reconnect=False, attempts=1, delay=0)
</pre><p>
Check whether the connection to the MySQL server is still
available.
</p><p>
When <code class="literal">reconnect</code> is set to
<code class="literal">True</code>, one or more <code class="literal">attempts</code>
are made to try to reconnect to the MySQL server, and these
options are forwarded to the
<a class="link" href="#connector-python-api-mysqlconnection-reconnect" title="10.2.28 MySQLConnection.reconnect() Method">reconnect()</a>>method.
Use the <code class="literal">delay</code> argument (seconds) if you want
to wait between each retry.
</p><p>
When the connection is not available, an
<code class="literal">InterfaceError</code> is raised. Use the
<a class="link" href="#connector-python-api-mysqlconnection-is-connected" title="10.2.25 MySQLConnection.is_connected() Method">is_connected()</a>
method to check the connection without raising an error.
</p><p>
Raises <code class="literal">InterfaceError</code> on errors.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-reconnect"></a>10.2.28 MySQLConnection.reconnect() Method</h3></div></div></div><a class="indexterm" name="id3832"></a><a class="indexterm" name="id3834"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.reconnect(attempts=1, delay=0)
</pre><p>
Attempt to reconnect to the MySQL server.
</p><p>
The argument <code class="literal">attempts</code> specifies the number of
times a reconnect is tried. The <code class="literal">delay</code>
argument is the number of seconds to wait between each retry.
</p><p>
You might set the number of attempts higher and use a longer
delay when you expect the MySQL server to be down for
maintenance, or when you expect the network to be temporarily
unavailable.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-reset-session"></a>10.2.29 MySQLConnection.reset_session() Method</h3></div></div></div><a class="indexterm" name="id3845"></a><a class="indexterm" name="id3847"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.reset_session(user_variables = None, session_variables = None)
</pre><p>
Resets the connection by reauthenticating to clear the session
state. <code class="literal">user_variables</code>, if given, is a
dictionary of user variable names and values.
<code class="literal">session_variables</code>, if given, is a dictionary
of system variable names and values. The method sets each
variable to the given value.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">user_variables = {'var1': '1', 'var2': '10'}
session_variables = {'wait_timeout': 100000, 'sql_mode': 'TRADITIONAL'}
self.cnx.reset_session(user_variables, session_variables)
</pre><p>
This method resets the session state by reauthenticating. For
MySQL servers 5.7 or higher, the
<a class="link" href="#connector-python-api-mysqlconnection-cmd-reset-connection" title="10.2.17 MySQLConnection.cmd_reset_connection() Method"><code class="literal">cmd_reset_connection()</code></a>
method is a more lightweight alternative.
</p><p>
This method was added in Connector/Python 1.2.1.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-rollback"></a>10.2.30 MySQLConnection.rollback() Method</h3></div></div></div><a class="indexterm" name="id3862"></a><a class="indexterm" name="id3864"></a><p>
This method sends a <code class="literal">ROLLBACK</code> statement to the
MySQL server, undoing all data changes from the current
transaction. By default, Connector/Python does not autocommit, so it is
possible to cancel transactions when using transactional storage
engines such as <code class="literal">InnoDB</code>.
</p><pre data-lang="python" class="programlisting">
>>> cursor.execute("INSERT INTO employees (first_name) VALUES (%s), (%s)", ('Jane', 'Mary'))
>>> cnx.rollback()</pre><p>
To <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_commit" target="_top">commit</a> modifications, see
the
<a class="link" href="#connector-python-api-mysqlconnection-commit" title="10.2.3 MySQLConnection.commit() Method">commit()</a>
method.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-set-charset-collation"></a>10.2.31 MySQLConnection.set_charset_collation() Method</h3></div></div></div><a class="indexterm" name="id3875"></a><a class="indexterm" name="id3877"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.set_charset_collation(charset=None, collation=None)
</pre><p>
This method sets the character set and collation to be used for
the current connection. The <code class="literal">charset</code> argument
can be either the name of a character set, or the numerical
equivalent as defined in
<code class="literal">constants.CharacterSet</code>.
</p><p>
When <code class="literal">collation</code> is <code class="literal">None</code>,
the default collation for the character set is used.
</p><p>
In the following example, we set the character set to
<code class="literal">latin1</code> and the collation to
<code class="literal">latin1_swedish_ci</code> (the default collation for:
<code class="literal">latin1</code>):
</p><pre data-lang="python" class="programlisting">
>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset_collation('latin1')</pre><p>
Specify a given collation as follows:
</p><pre data-lang="python" class="programlisting">
>>> cnx = mysql.connector.connect(user='scott')
>>> cnx.set_charset_collation('latin1', 'latin1_general_ci')</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-set-client-flags"></a>10.2.32 MySQLConnection.set_client_flags() Method</h3></div></div></div><a class="indexterm" name="id3896"></a><a class="indexterm" name="id3898"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This method has been deprecated as of 9.3.0. Use the property
method
<a class="xref" href="#connector-python-api-mysqlconnection-client-flags" title="10.2.39 MySQLConnection.client_flags Property">Section 10.2.39, “MySQLConnection.client_flags Property”</a>
instead.
</p></div><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.set_client_flags(flags)
</pre><p>
This method sets the client flags to use when connecting to the
MySQL server, and returns the new value as an integer. The
<code class="literal">flags</code> argument can be either an integer or a
sequence of valid client flag values (see
<a class="xref" href="#connector-python-api-clientflag" title="10.7 constants.ClientFlag Class">Section 10.7, “constants.ClientFlag Class”</a>).
</p><p>
If <code class="literal">flags</code> is a sequence, each item in the
sequence sets the flag when the value is positive or unsets it
when negative. For example, to unset
<code class="literal">LONG_FLAG</code> and set the
<code class="literal">FOUND_ROWS</code> flags:
</p><pre data-lang="python" class="programlisting">
>>> from mysql.connector.constants import ClientFlag
>>> cnx.set_client_flags([ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG])
>>> cnx.reconnect()</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Client flags are only set or used when connecting to the MySQL
server. It is therefore necessary to reconnect after making
changes.
</p></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-shutdown"></a>10.2.33 MySQLConnection.shutdown() Method</h3></div></div></div><a class="indexterm" name="id3918"></a><a class="indexterm" name="id3920"></a><p>
This method closes the socket. It raises no exceptions.
</p><p>
Unlike
<a class="link" href="#connector-python-api-mysqlconnection-disconnect" title="10.2.20 MySQLConnection.disconnect() Method"><code class="literal">disconnect()</code></a>,
<code class="literal">shutdown()</code> closes the client connection
without attempting to send a <code class="literal">QUIT</code> command to
the server first. Thus, it will not block if the connection is
disrupted for some reason such as network failure.
</p><p>
<code class="literal">shutdown()</code> was added in Connector/Python 2.0.1.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-start-transaction"></a>10.2.34 MySQLConnection.start_transaction() Method</h3></div></div></div><a class="indexterm" name="id3932"></a><a class="indexterm" name="id3934"></a><p>
This method starts a transaction. It accepts arguments
indicating whether to use a consistent snapshot, which
transaction isolation level to use, and the transaction access
mode:
</p><pre data-lang="python" class="programlisting">cnx.start_transaction(consistent_snapshot=<em class="replaceable"><code>bool</code></em>,
isolation_level=<em class="replaceable"><code>level</code></em>,
readonly=<em class="replaceable"><code>access_mode</code></em>)
</pre><p>
The default <code class="literal">consistent_snapshot</code> value is
<code class="literal">False</code>. If the value is
<code class="literal">True</code>, Connector/Python sends <code class="literal">WITH CONSISTENT
SNAPSHOT</code> with the statement. MySQL ignores this for
isolation levels for which that option does not apply.
</p><p>
The default <code class="literal">isolation_level</code> value is
<code class="literal">None</code>, and permitted values are <code class="literal">'READ
UNCOMMITTED'</code>, <code class="literal">'READ COMMITTED'</code>,
<code class="literal">'REPEATABLE READ'</code>, and
<code class="literal">'SERIALIZABLE'</code>. If the
<code class="literal">isolation_level</code> value is
<code class="literal">None</code>, no isolation level is sent, so the
default level applies.
</p><p>
The <code class="literal">readonly</code> argument can be
<code class="literal">True</code> to start the transaction in
<code class="literal">READ ONLY</code> mode or <code class="literal">False</code> to
start it in <code class="literal">READ WRITE</code> mode. If
<code class="literal">readonly</code> is omitted, the server's default
access mode is used. For details about transaction access mode,
see the description for the <code class="literal">START TRANSACTION</code>
statement at <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top">START TRANSACTION, COMMIT, and ROLLBACK Statements</a>. If the server is older
than MySQL 5.6.5, it does not support setting the access mode
and Connector/Python raises a <code class="literal">ValueError</code>.
</p><p>
Invoking <code class="literal">start_transaction()</code> raises a
<code class="literal">ProgrammingError</code> if invoked while a
transaction is currently in progress. This differs from
executing a <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top"><code class="literal">START
TRANSACTION</code></a> SQL statement while a transaction is in
progress; the statement implicitly commits the current
transaction.
</p><p>
To determine whether a transaction is active for the connection,
use the
<a class="link" href="#connector-python-api-mysqlconnection-in-transaction" title="10.2.46 MySQLConnection.in_transaction Property">in_transaction</a>
property.
</p><p>
<code class="literal">start_transaction()</code> was added in MySQL Connector/Python
1.1.0. The <code class="literal">readonly</code> argument was added in
Connector/Python 1.1.5.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-autocommit"></a>10.2.35 MySQLConnection.autocommit Property</h3></div></div></div><a class="indexterm" name="id3977"></a><a class="indexterm" name="id3979"></a><p>
This property can be assigned a value of <code class="literal">True</code>
or <code class="literal">False</code> to enable or disable the autocommit
feature of MySQL. The property can be invoked to retrieve the
current autocommit setting.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Autocommit is disabled by default when connecting through
Connector/Python. This can be enabled using the
<code class="literal">autocommit</code>
<a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
parameter</a>.
</p></div><p>
When the autocommit is turned off, you must
<a class="link" href="#connector-python-api-mysqlconnection-commit" title="10.2.3 MySQLConnection.commit() Method">commit</a>
transactions when using transactional storage engines such as
<code class="literal">InnoDB</code> or <code class="literal">NDBCluster</code>.
</p><pre data-lang="python" class="programlisting">
>>> cnx.autocommit
False
>>> cnx.autocommit = True
>>> cnx.autocommit
True</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-unread-results"></a>10.2.36 MySQLConnection.unread_results Property</h3></div></div></div><a class="indexterm" name="id3995"></a><a class="indexterm" name="id3997"></a><p>
Indicates whether there is an unread result. It is set to
<code class="literal">False</code> if there is not an unread result,
otherwise <code class="literal">True</code>. This is used by cursors to
check whether another cursor still needs to retrieve its result
set.
</p><p>
Do not set the value of this property, as only the connector
should change the value. In other words, treat this as a
read-only property.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-can-consume-results"></a>10.2.37 MySQLConnection.can_consume_results Property</h3></div></div></div><a class="indexterm" name="id4005"></a><a class="indexterm" name="id4007"></a><p>
This property indicates the value of the
<code class="literal">consume_results</code> connection parameter that
controls whether result sets produced by queries are
automatically read and discarded. See
<a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p><p>
This method was added in Connector/Python 2.1.1.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-charset"></a>10.2.38 MySQLConnection.charset Property</h3></div></div></div><a class="indexterm" name="id4015"></a><a class="indexterm" name="id4017"></a><p>
This property returns a string indicating which character set is
used for the connection, whether or not it is connected.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-client-flags"></a>10.2.39 MySQLConnection.client_flags Property</h3></div></div></div><a class="indexterm" name="id4022"></a><a class="indexterm" name="id4024"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">>>> cnx.client_flags=flags
>>> cnx.clieng_flags
</pre><p>
This property sets the client flags to use when connecting to
the MySQL server, and returns the set value as an integer. The
<code class="literal">flags</code> value can be either an integer or a
sequence of valid client flag values (see
<a class="xref" href="#connector-python-api-clientflag" title="10.7 constants.ClientFlag Class">Section 10.7, “constants.ClientFlag Class”</a>).
</p><p>
If <code class="literal">flags</code> is a sequence, each item in the
sequence sets the flag when the value is positive or unsets it
when negative. For example, to unset
<code class="literal">LONG_FLAG</code> and set the
<code class="literal">FOUND_ROWS</code> flags:
</p><pre data-lang="python" class="programlisting">
>>> from mysql.connector.constants import ClientFlag
>>> cnx.client_flags=[ClientFlag.FOUND_ROWS, -ClientFlag.LONG_FLAG]
>>> cnx.reconnect()</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Client flags are only set or used when connecting to the MySQL
server. It is therefore necessary to reconnect after making
changes.
</p></div></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-collation"></a>10.2.40 MySQLConnection.collation Property</h3></div></div></div><a class="indexterm" name="id4040"></a><a class="indexterm" name="id4042"></a><p>
This property returns a string indicating which collation is
used for the connection, whether or not it is connected.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-connected"></a>10.2.41 MySQLConnection.connected Property</h3></div></div></div><a class="indexterm" name="id4047"></a><a class="indexterm" name="id4049"></a><p>
Reports whether the connection to MySQL Server is available.
</p><p>
This read-only property checks whether the connection to MySQL
is available using the
<a class="link" href="#connector-python-api-mysqlconnection-ping" title="10.2.27 MySQLConnection.ping() Method">ping()</a>
method; but unlike <code class="literal">ping()</code>,
<code class="literal">connected</code> returns <code class="literal">True</code>
when the connection is available, and <code class="literal">False</code>
otherwise.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-connection-id"></a>10.2.42 MySQLConnection.connection_id Property</h3></div></div></div><a class="indexterm" name="id4060"></a><a class="indexterm" name="id4062"></a><p>
This property returns the integer connection ID (thread ID or
session ID) for the current connection or
<code class="literal">None</code> when not connected.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-converter-class"></a>10.2.43 MySQLConnection.converter-class Property</h3></div></div></div><a class="indexterm" name="id4068"></a><a class="indexterm" name="id4070"></a><p>
This property sets and returns the converter class to use when
configuring the connection.
</p><pre data-lang="python" class="programlisting"># get the current converter class being used
print(cnx.converter_class)
>> <class 'mysql.connector.conversion.MySQLConverter'>
class TestConverter(MySQLConverterBase): ...
# set the custom converter class
cnx.converter_class = TestConverter
print(cnx.converter_class)
>> <class '__main__.TestConverter'></pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-database"></a>10.2.44 MySQLConnection.database Property</h3></div></div></div><a class="indexterm" name="id4076"></a><a class="indexterm" name="id4078"></a><p>
This property sets the current (default) database by executing a
<code class="literal">USE</code> statement. The property can also be used
to retrieve the current database name.
</p><pre data-lang="python" class="programlisting">
>>> cnx.database = 'test'
>>> cnx.database = 'mysql'
>>> cnx.database
u'mysql'
</pre><p>
Returns a string.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-get-warnings"></a>10.2.45 MySQLConnection.get_warnings Property</h3></div></div></div><a class="indexterm" name="id4086"></a><a class="indexterm" name="id4088"></a><p>
This property can be assigned a value of <code class="literal">True</code>
or <code class="literal">False</code> to enable or disable whether
warnings should be fetched automatically. The default is
<code class="literal">False</code> (default). The property can be invoked
to retrieve the current warnings setting.
</p><p>
Fetching warnings automatically can be useful when debugging
queries. Cursors make warnings available through the method
<a class="link" href="#connector-python-api-mysqlcursor-fetchwarnings" title="10.5.14 MySQLCursor.fetchwarnings() Method">MySQLCursor.fetchwarnings()</a>.
</p><pre data-lang="python" class="programlisting">
>>> cnx.get_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
</pre><p>
Returns <code class="literal">True</code> or <code class="literal">False</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-in-transaction"></a>10.2.46 MySQLConnection.in_transaction Property</h3></div></div></div><a class="indexterm" name="id4102"></a><a class="indexterm" name="id4104"></a><p>
This property returns <code class="literal">True</code> or
<code class="literal">False</code> to indicate whether a transaction is
active for the connection. The value is <code class="literal">True</code>
regardless of whether you start a transaction using the
<a class="link" href="#connector-python-api-mysqlconnection-start-transaction" title="10.2.34 MySQLConnection.start_transaction() Method"><code class="literal">start_transaction()</code></a>
API call or by directly executing an SQL statement such as
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top"><code class="literal">START
TRANSACTION</code></a> or
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/commit.html" target="_top"><code class="literal">BEGIN</code></a>.
</p><pre data-lang="python" class="programlisting">
>>> cnx.start_transaction()
>>> cnx.in_transaction
True
>>> cnx.commit()
>>> cnx.in_transaction
False
</pre><p>
<code class="literal">in_transaction</code> was added in MySQL Connector/Python 1.1.0.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-raise-on-warnings"></a>10.2.47 MySQLConnection.raise_on_warnings Property</h3></div></div></div><a class="indexterm" name="id4121"></a><a class="indexterm" name="id4123"></a><p>
This property can be assigned a value of <code class="literal">True</code>
or <code class="literal">False</code> to enable or disable whether
warnings should raise exceptions. The default is
<code class="literal">False</code> (default). The property can be invoked
to retrieve the current exceptions setting.
</p><p>
Setting <code class="literal">raise_on_warnings</code> also sets
<code class="literal">get_warnings</code> because warnings need to be
fetched so they can be raised as exceptions.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
You might always want to set the SQL mode if you would like to
have the MySQL server directly report warnings as errors (see
<a class="xref" href="#connector-python-api-mysqlconnection-sql-mode" title="10.2.52 MySQLConnection.sql_mode Property">Section 10.2.52, “MySQLConnection.sql_mode Property”</a>).
It is also good to use transactional engines so transactions
can be rolled back when catching the exception.
</p></div><p>
Result sets needs to be fetched completely before any exception
can be raised. The following example shows the execution of a
query that produces a warning:
</p><pre data-lang="python" class="programlisting">
>>> cnx.raise_on_warnings = True
>>> cursor.execute('SELECT "a"+1')
>>> cursor.fetchall()
..
mysql.connector.errors.DataError: 1292: Truncated incorrect DOUBLE value: 'a'
</pre><p>
Returns <code class="literal">True</code> or <code class="literal">False</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-host"></a>10.2.48 MySQLConnection.server_host Property</h3></div></div></div><a class="indexterm" name="id4142"></a><a class="indexterm" name="id4144"></a><p>
This read-only property returns the host name or IP address used
for connecting to the MySQL server.
</p><p>
Returns a string.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-info"></a>10.2.49 MySQLConnection.server_info Property</h3></div></div></div><a class="indexterm" name="id4150"></a><a class="indexterm" name="id4152"></a><p>
This read-only property returns the MySQL server information
verbatim as a string: for example <code class="literal">8.4.0-log</code>,
or <code class="literal">None</code> when not connected.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-port"></a>10.2.50 MySQLConnection.server_port Property</h3></div></div></div><a class="indexterm" name="id4159"></a><a class="indexterm" name="id4161"></a><p>
This read-only property returns the TCP/IP port used for
connecting to the MySQL server.
</p><p>
Returns an integer.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-server-version"></a>10.2.51 MySQLConnection.server_version Property</h3></div></div></div><a class="indexterm" name="id4167"></a><a class="indexterm" name="id4169"></a><p>
This read-only property returns the MySQL server version as a
tuple, or <code class="literal">None</code> when not connected.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-sql-mode"></a>10.2.52 MySQLConnection.sql_mode Property</h3></div></div></div><a class="indexterm" name="id4175"></a><a class="indexterm" name="id4177"></a><p>
This property is used to retrieve and set the SQL Modes for the
current connection. The value should be a list of different
modes separated by comma (","), or a sequence of modes,
preferably using the <code class="literal">constants.SQLMode</code> class.
</p><p>
To unset all modes, pass an empty string or an empty sequence.
</p><pre data-lang="python" class="programlisting">
>>> cnx.sql_mode = 'TRADITIONAL,NO_ENGINE_SUBSTITUTION'
>>> cnx.sql_mode.split(',')
[u'STRICT_TRANS_TABLES', u'STRICT_ALL_TABLES', u'NO_ZERO_IN_DATE',
u'NO_ZERO_DATE', u'ERROR_FOR_DIVISION_BY_ZERO', u'TRADITIONAL',
u'NO_AUTO_CREATE_USER', u'NO_ENGINE_SUBSTITUTION']
>>> from mysql.connector.constants import SQLMode
>>> cnx.sql_mode = [ SQLMode.NO_ZERO_DATE, SQLMode.REAL_AS_FLOAT]
>>> cnx.sql_mode
u'REAL_AS_FLOAT,NO_ZERO_DATE'
</pre><p>
Returns a string.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-time-zone"></a>10.2.53 MySQLConnection.time_zone Property</h3></div></div></div><a class="indexterm" name="id4186"></a><a class="indexterm" name="id4188"></a><p>
This property is used to set or retrieve the time zone session
variable for the current connection.
</p><pre data-lang="python" class="programlisting">
>>> cnx.time_zone = '+00:00'
>>> cursor = cnx.cursor()
>>> cursor.execute('SELECT NOW()') ; cursor.fetchone()
(datetime.datetime(2012, 6, 15, 11, 24, 36),)
>>> cnx.time_zone = '-09:00'
>>> cursor.execute('SELECT NOW()') ; cursor.fetchone()
(datetime.datetime(2012, 6, 15, 2, 24, 44),)
>>> cnx.time_zone
u'-09:00'
</pre><p>
Returns a string.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-use-unicode"></a>10.2.54 MySQLConnection.use_unicode Property</h3></div></div></div><a class="indexterm" name="id4195"></a><a class="indexterm" name="id4197"></a><p>
This property sets and returns whether the connection uses
Unicode with the value <code class="literal">True</code> or
<code class="literal">False</code>.
</p><pre data-lang="python" class="programlisting"># gets whether the connector returns string fields as unicode or not
print(cnx.use_unicode)
>> True
# set or update use_unicode property
cnx.use_unicode = False
print(cnx.use_unicode)
>> False</pre><p>
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-unix-socket"></a>10.2.55 MySQLConnection.unix_socket Property</h3></div></div></div><a class="indexterm" name="id4205"></a><a class="indexterm" name="id4207"></a><p>
This read-only property returns the Unix socket file for
connecting to the MySQL server.
</p><p>
Returns a string.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnection-user"></a>10.2.56 MySQLConnection.user Property</h3></div></div></div><a class="indexterm" name="id4213"></a><a class="indexterm" name="id4215"></a><p>
This read-only property returns the user name used for
connecting to the MySQL server.
</p><p>
Returns a string.
</p></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysqlconnectionpool"></a>10.3 pooling.MySQLConnectionPool Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-constructor">10.3.1 pooling.MySQLConnectionPool Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-add-connection">10.3.2 MySQLConnectionPool.add_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-get-connection">10.3.3 MySQLConnectionPool.get_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-set-config">10.3.4 MySQLConnectionPool.set_config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlconnectionpool-pool-name">10.3.5 MySQLConnectionPool.pool_name Property</a></span></dt></dl></div><a class="indexterm" name="id4221"></a><a class="indexterm" name="id4223"></a><p>
This class provides for the instantiation and management of
connection pools.
</p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-constructor"></a>10.3.1 pooling.MySQLConnectionPool Constructor</h3></div></div></div><a class="indexterm" name="id4228"></a><a class="indexterm" name="id4230"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">MySQLConnectionPool(pool_name=None,
pool_size=5,
pool_reset_session=True,
**kwargs)
</pre><p>
This constructor instantiates an object that manages a
connection pool.
</p><p>
Arguments:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">pool_name</code>: The pool name. If this
argument is not given, Connector/Python automatically generates the
name, composed from whichever of the
<code class="literal">host</code>, <code class="literal">port</code>,
<code class="literal">user</code>, and <code class="literal">database</code>
connection arguments are given in <code class="literal">kwargs</code>,
in that order.
</p><p>
It is not an error for multiple pools to have the same name.
An application that must distinguish pools by their
<code class="literal">pool_name</code> property should create each
pool with a distinct name.
</p></li><li class="listitem"><p>
<code class="literal">pool_size</code>: The pool size. If this
argument is not given, the default is 5.
</p></li><li class="listitem"><p>
<code class="literal">pool_reset_session</code>: Whether to reset
session variables when the connection is returned to the
pool. This argument was added in Connector/Python 1.1.5. Before 1.1.5,
session variables are not reset.
</p></li><li class="listitem"><p>
<code class="literal">kwargs</code>: Optional additional connection
arguments, as described in
<a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p></li></ul></div><p>
Example:
</p><pre data-lang="python" class="programlisting">dbconfig = {
"database": "test",
"user": "joe",
}
cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",
pool_size = 3,
**dbconfig)
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-add-connection"></a>10.3.2 MySQLConnectionPool.add_connection() Method</h3></div></div></div><a class="indexterm" name="id4261"></a><a class="indexterm" name="id4263"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnxpool.add_connection(cnx = None)
</pre><p>
This method adds a new or existing
<code class="literal">MySQLConnection</code> to the pool, or raises a
<code class="literal">PoolError</code> if the pool is full.
</p><p>
Arguments:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">cnx</code>: The
<code class="literal">MySQLConnection</code> object to be added to the
pool. If this argument is missing, the pool creates a new
connection and adds it.
</p></li></ul></div><p>
Example:
</p><pre data-lang="python" class="programlisting">cnxpool.add_connection() # add new connection to pool
cnxpool.add_connection(cnx) # add existing connection to pool
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-get-connection"></a>10.3.3 MySQLConnectionPool.get_connection() Method</h3></div></div></div><a class="indexterm" name="id4280"></a><a class="indexterm" name="id4282"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnxpool.get_connection()
</pre><p>
This method returns a connection from the pool, or raises a
<code class="literal">PoolError</code> if no connections are available.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">cnx = cnxpool.get_connection()
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-set-config"></a>10.3.4 MySQLConnectionPool.set_config() Method</h3></div></div></div><a class="indexterm" name="id4292"></a><a class="indexterm" name="id4294"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnxpool.set_config(**kwargs)
</pre><p>
This method sets the configuration parameters for connections in
the pool. Connections requested from the pool after the
configuration change use the new parameters. Connections
obtained before the change remain unaffected, but when they are
closed (returned to the pool) are reopened with the new
parameters before being returned by the pool for subsequent
connection requests.
</p><p>
Arguments:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">kwargs</code>: Connection arguments.
</p></li></ul></div><p>
Example:
</p><pre data-lang="python" class="programlisting">dbconfig = {
"database": "performance_schema",
"user": "admin",
"password": "<em class="replaceable"><code>password</code></em>",
}
cnxpool.set_config(**dbconfig)
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlconnectionpool-pool-name"></a>10.3.5 MySQLConnectionPool.pool_name Property</h3></div></div></div><a class="indexterm" name="id4309"></a><a class="indexterm" name="id4311"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnxpool.pool_name
</pre><p>
This property returns the connection pool name.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">name = cnxpool.pool_name
</pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-pooledmysqlconnection"></a>10.4 pooling.PooledMySQLConnection Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-constructor">10.4.1 pooling.PooledMySQLConnection Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-close">10.4.2 PooledMySQLConnection.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-config">10.4.3 PooledMySQLConnection.config() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-pooledmysqlconnection-pool-name">10.4.4 PooledMySQLConnection.pool_name Property</a></span></dt></dl></div><a class="indexterm" name="id4320"></a><a class="indexterm" name="id4322"></a><p>
This class is used by <code class="literal">MySQLConnectionPool</code> to
return a pooled connection instance. It is also the class used for
connections obtained with calls to the
<code class="literal">connect()</code> method that name a connection pool
(see <a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>).
</p><p>
<code class="literal">PooledMySQLConnection</code> pooled connection objects
are similar to <code class="literal">MySQLConnection</code> unpooled
connection objects, with these differences:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
To release a pooled connection obtained from a connection
pool, invoke its <code class="literal">close()</code> method, just as
for any unpooled connection. However, for a pooled connection,
<code class="literal">close()</code> does not actually close the
connection but returns it to the pool and makes it available
for subsequent connection requests.
</p></li><li class="listitem"><p>
A pooled connection cannot be reconfigured using its
<code class="literal">config()</code> method. Connection changes must be
done through the pool object itself, as described by
<a class="xref" href="#connector-python-connection-pooling" title="9.5 Connector/Python Connection Pooling">Section 9.5, “Connector/Python Connection Pooling”</a>.
</p></li><li class="listitem"><p>
A pooled connection has a <code class="literal">pool_name</code>
property that returns the pool name.
</p></li></ul></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-constructor"></a>10.4.1 pooling.PooledMySQLConnection Constructor</h3></div></div></div><a class="indexterm" name="id4345"></a><a class="indexterm" name="id4347"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">PooledMySQLConnection(cnxpool, cnx)
</pre><p>
This constructor takes connection pool and connection arguments
and returns a pooled connection. It is used by the
<code class="literal">MySQLConnectionPool</code> class.
</p><p>
Arguments:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">cnxpool</code>: A
<code class="literal">MySQLConnectionPool</code> instance.
</p></li><li class="listitem"><p>
<code class="literal">cnx</code>: A <code class="literal">MySQLConnection</code>
instance.
</p></li></ul></div><p>
Example:
</p><pre data-lang="python" class="programlisting">pcnx = mysql.connector.pooling.PooledMySQLConnection(cnxpool, cnx)
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-close"></a>10.4.2 PooledMySQLConnection.close() Method</h3></div></div></div><a class="indexterm" name="id4367"></a><a class="indexterm" name="id4369"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.close()
</pre><p>
Returns a pooled connection to its connection pool.
</p><p>
For a pooled connection, <code class="literal">close()</code> does not
actually close it but returns it to the pool and makes it
available for subsequent connection requests.
</p><p>
If the pool configuration parameters are changed, a returned
connection is closed and reopened with the new configuration
before being returned from the pool again in response to a
connection request.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-config"></a>10.4.3 PooledMySQLConnection.config() Method</h3></div></div></div><a class="indexterm" name="id4379"></a><a class="indexterm" name="id4381"></a><p>
For pooled connections, the <code class="literal">config()</code> method
raises a <code class="literal">PoolError</code> exception. Configuration
for pooled connections should be done using the pool object.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-pooledmysqlconnection-pool-name"></a>10.4.4 PooledMySQLConnection.pool_name Property</h3></div></div></div><a class="indexterm" name="id4388"></a><a class="indexterm" name="id4390"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cnx.pool_name
</pre><p>
This property returns the name of the connection pool to which
the connection belongs.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">cnx = cnxpool.get_connection()
name = cnx.pool_name
</pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-mysqlcursor"></a>10.5 cursor.MySQLCursor Class</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlcursor-constructor">10.5.1 cursor.MySQLCursor Constructor</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-add-attribute">10.5.2 MySQLCursor.add_attribute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-clear-attributes">10.5.3 MySQLCursor.clear_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-get-attributes">10.5.4 MySQLCursor.get_attributes() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-callproc">10.5.5 MySQLCursor.callproc() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-close">10.5.6 MySQLCursor.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-execute">10.5.7 MySQLCursor.execute() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-executemany">10.5.8 MySQLCursor.executemany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchall">10.5.9 MySQLCursor.fetchall() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchmany">10.5.10 MySQLCursor.fetchmany() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchone">10.5.11 MySQLCursor.fetchone() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-nextset">10.5.12 MySQLCursor.nextset() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchsets">10.5.13 MySQLCursor.fetchsets() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-fetchwarnings">10.5.14 MySQLCursor.fetchwarnings() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-stored-results">10.5.15 MySQLCursor.stored_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-column-names">10.5.16 MySQLCursor.column_names Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-description">10.5.17 MySQLCursor.description Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-warnings">10.5.18 MySQLCursor.warnings Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-lastrowid">10.5.19 MySQLCursor.lastrowid Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-rowcount">10.5.20 MySQLCursor.rowcount Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-statement">10.5.21 MySQLCursor.statement Property</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursor-with-rows">10.5.22 MySQLCursor.with_rows Property</a></span></dt></dl></div><a class="indexterm" name="id4399"></a><a class="indexterm" name="id4401"></a><p>
The <code class="literal">MySQLCursor</code> class instantiates objects that
can execute operations such as SQL statements. Cursor objects
interact with the MySQL server using a
<code class="literal">MySQLConnection</code> object.
</p><p>
To create a cursor, use the
<a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
method of a connection object:
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor()
</pre><p>
Several related classes inherit from
<code class="literal">MySQLCursor</code>. To create a cursor of one of these
types, pass the appropriate arguments to
<code class="literal">cursor()</code>:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">MySQLCursorBuffered</code> creates a buffered
cursor. See
<a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(buffered=True)
</pre></li><li class="listitem"><p>
<code class="literal">MySQLCursorRaw</code> creates a raw cursor. See
<a class="xref" href="#connector-python-api-mysqlcursorraw" title="10.6.2 cursor.MySQLCursorRaw Class">Section 10.6.2, “cursor.MySQLCursorRaw Class”</a>.
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(raw=True)
</pre></li><li class="listitem"><p>
<code class="literal">MySQLCursorDict</code> creates a cursor that
returns rows as dictionaries. See
<a class="xref" href="#connector-python-api-mysqlcursordict" title="10.6.3 cursor.MySQLCursorDict Class">Section 10.6.3, “cursor.MySQLCursorDict Class”</a>.
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(dictionary=True)
</pre></li><li class="listitem"><p>
<code class="literal">MySQLCursorBufferedDict</code> creates a buffered
cursor that returns rows as dictionaries. See
<a class="xref" href="#connector-python-api-mysqlcursorbuffereddict" title="10.6.4 cursor.MySQLCursorBufferedDict Class">Section 10.6.4, “cursor.MySQLCursorBufferedDict Class”</a>.
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(dictionary=True, buffered=True)
</pre></li><li class="listitem"><p>
<code class="literal">MySQLCursorPrepared</code> creates a cursor for
executing prepared statements. See
<a class="xref" href="#connector-python-api-mysqlcursorprepared" title="10.6.5 cursor.MySQLCursorPrepared Class">Section 10.6.5, “cursor.MySQLCursorPrepared Class”</a>.
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(prepared=True)
</pre></li></ul></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-constructor"></a>10.5.1 cursor.MySQLCursor Constructor</h3></div></div></div><a class="indexterm" name="id4441"></a><a class="indexterm" name="id4443"></a><p>
In most cases, the <code class="literal">MySQLConnection</code>
<a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
method is used to instantiate a <code class="literal">MySQLCursor</code>
object:
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor()
</pre><p>
It is also possible to instantiate a cursor by passing a
<a class="link" href="#connector-python-api-mysqlconnection" title="10.2 connection.MySQLConnection Class"><code class="literal">MySQLConnection</code></a>
object to <code class="literal">MySQLCursor</code>:
</p><pre data-lang="python" class="programlisting">import mysql.connector
from mysql.connector.cursor import MySQLCursor
cnx = mysql.connector.connect(database='world')
cursor = MySQLCursor(cnx)
</pre><p>
The connection argument is optional. If omitted, the cursor is
created but its
<a class="link" href="#connector-python-api-mysqlcursor-execute" title="10.5.7 MySQLCursor.execute() Method"><code class="literal">execute()</code></a>
method raises an exception.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-add-attribute"></a>10.5.2 MySQLCursor.add_attribute() Method</h3></div></div></div><a class="indexterm" name="id4461"></a><a class="indexterm" name="id4463"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cursor.add_attribute(name, value)
</pre><p>
Adds a new named query attribute to the list, as part of MySQL
server's <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/query-attributes.html" target="_top">Query Attributes</a> functionality.
</p><p>
<code class="literal">name</code>: The name must be a string, but no other
validation checks are made; attributes are sent as is to the
server and errors, if any, will be detected and reported by the
server.
</p><p>
<code class="literal">value</code>: a value converted to the MySQL Binary
Protocol, similar to how prepared statement parameters are
converted. An error is reported if the conversion fails.
</p><p>
Query attributes must be enabled on the server, and are disabled
by default. A warning is logged when setting query attributes
server connection that does not support them. See also
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/query-attributes.html#query-attributes-prerequisites" target="_top">Prerequisites for Using Query Attributes</a> for enabling
the query_attributes MySQL server component.
</p><p>
Example query attribute usage:
</p><pre data-lang="python" class="programlisting"># Each invocation of `add_attribute` method will add a new query attribute:
cur.add_attribute("foo", 2)
cur.execute("SELECT first_name, last_name FROM clients")
# The query above sent attibute "foo" with value 2.
cur.add_attribute(*("bar", "3"))
cur.execute("SELECT * FROM products WHERE price < ?", 10)
# The query above sent attributes ("foo", 2) and ("bar", "3").
my_attributes = [("page_name", "root"), ("previous_page", "login")]
for attribute_tuple in my_attributes:
cur.add_attribute(*attribute_tuple)
cur.execute("SELECT * FROM offers WHERE publish = ?", 0)
# The query above sent 4 attributes.
# To check the current query attributes:
print(cur.get_attributes())
# prints:
[("foo", 2), ("bar", "3"), ("page_name", "root"), ("previous_page", "login")]
# Query attributes are not cleared until the cursor is closed or
# of the clear_attributes() method is invoked:
cur.clear_attributes()
print(cur.get_attributes())
# prints:
[]
cur.execute("SELECT first_name, last_name FROM clients")
# The query above did not send any attibute.
</pre><p>
This method was added in Connector/Python 8.0.26.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-clear-attributes"></a>10.5.3 MySQLCursor.clear_attributes() Method</h3></div></div></div><a class="indexterm" name="id4480"></a><a class="indexterm" name="id4482"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cursor.clear_attributes()
</pre><p>
Clear the list of query attributes on the connector's side, as
set by
<a class="xref" href="#connector-python-api-mysqlcursor-add-attribute" title="10.5.2 MySQLCursor.add_attribute() Method">Section 10.5.2, “MySQLCursor.add_attribute() Method”</a>.
</p><p>
This method was added in Connector/Python 8.0.26.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-get-attributes"></a>10.5.4 MySQLCursor.get_attributes() Method</h3></div></div></div><a class="indexterm" name="id4491"></a><a class="indexterm" name="id4493"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cursor.get_attributes()
</pre><p>
Return a list of existing query attributes, as set by
<a class="xref" href="#connector-python-api-mysqlcursor-add-attribute" title="10.5.2 MySQLCursor.add_attribute() Method">Section 10.5.2, “MySQLCursor.add_attribute() Method”</a>.
</p><p>
This method was added in Connector/Python 8.0.26.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-callproc"></a>10.5.5 MySQLCursor.callproc() Method</h3></div></div></div><a class="indexterm" name="id4502"></a><a class="indexterm" name="id4504"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">result_args = cursor.callproc(proc_name, args=())
</pre><p>
This method calls the stored procedure named by the
<code class="literal">proc_name</code> argument. The
<code class="literal">args</code> sequence of parameters must contain one
entry for each argument that the procedure expects.
<code class="literal">callproc()</code> returns a modified copy of the
input sequence. Input parameters are left untouched. Output and
input/output parameters may be replaced with new values.
</p><p>
Result sets produced by the stored procedure are automatically
fetched and stored as
<a class="link" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">MySQLCursorBuffered</a>
instances. For more information about using these result sets,
see
<a class="link" href="#connector-python-api-mysqlcursor-stored-results" title="10.5.15 MySQLCursor.stored_results() Method"><code class="literal">stored_results()</code></a>.
</p><p>
Suppose that a stored procedure takes two parameters, multiplies
the values, and returns the product:
</p><pre data-lang="sql" class="programlisting">CREATE PROCEDURE multiply(IN pFac1 INT, IN pFac2 INT, OUT pProd INT)
BEGIN
SET pProd := pFac1 * pFac2;
END;
</pre><p>
The following example shows how to execute the
<code class="literal">multiply()</code> procedure:
</p><pre data-lang="python" class="programlisting">>>> args = (5, 6, 0) # 0 is to hold value of the OUT parameter pProd
>>> cursor.callproc('multiply', args)
('5', '6', 30L)
</pre><p>
Connector/Python 1.2.1 and up permits parameter types to be specified. To
do this, specify a parameter as a two-item tuple consisting of
the parameter value and type. Suppose that a procedure
<code class="literal">sp1()</code> has this definition:
</p><pre data-lang="sql" class="programlisting">CREATE PROCEDURE sp1(IN pStr1 VARCHAR(20), IN pStr2 VARCHAR(20),
OUT pConCat VARCHAR(100))
BEGIN
SET pConCat := CONCAT(pStr1, pStr2);
END;
</pre><p>
To execute this procedure from Connector/Python, specifying a type for the
<code class="literal">OUT</code> parameter, do this:
</p><pre data-lang="python" class="programlisting">args = ('ham', 'eggs', (0, 'CHAR'))
result_args = cursor.callproc('sp1', args)
print(result_args[2])
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-close"></a>10.5.6 MySQLCursor.close() Method</h3></div></div></div><a class="indexterm" name="id4529"></a><a class="indexterm" name="id4531"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cursor.close()
</pre><p>
Use <code class="literal">close()</code> when you are done using a cursor.
This method closes the cursor, resets all results, and ensures
that the cursor object has no reference to its original
connection object.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-execute"></a>10.5.7 MySQLCursor.execute() Method</h3></div></div></div><a class="indexterm" name="id4539"></a><a class="indexterm" name="id4541"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cursor.execute(operation, params=None)
iterator = cursor.execute(operation, params=None)
# Allowed before 9.2.0
iterator = cursor.execute(operation, params=None, multi=True)
</pre><p>
This method executes the given database
<code class="literal">operation</code> (query or command). The parameters
found in the tuple or dictionary <code class="literal">params</code> are
bound to the variables in the operation. Specify variables using
<code class="literal">%s</code> or
<code class="literal">%(<em class="replaceable"><code>name</code></em>)s</code> parameter
style (that is, using <code class="literal">format</code> or
<code class="literal">pyformat</code> style).
</p><p>
Before Connector/Python 9.2.0, <code class="literal">execute()</code> accepted a
<code class="literal">multi</code> option and returned an iterator if set
to <code class="literal">True</code>. That option was removed in 9.2.0,
and <a class="xref" href="#connector-python-multi" title="9.3 Executing Multiple Statements">Section 9.3, “Executing Multiple Statements”</a> was added.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
In Python, a tuple containing a single value must include a
comma. For example, <span class="emphasis"><em>('abc')</em></span> is evaluated
as a scalar while <span class="emphasis"><em>('abc',)</em></span> is evaluated
as a tuple.
</p></div><p>
This example inserts information about a new employee, then
selects the data for that person. The statements are executed as
separate <code class="literal">execute()</code> operations:
</p><pre data-lang="python" class="programlisting">insert_stmt = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
"VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
select_stmt = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
cursor.execute(select_stmt, { 'emp_no': 2 })
</pre><p>
The data values are converted as necessary from Python objects
to something MySQL understands. In the preceding example, the
<code class="literal">datetime.date()</code> instance is converted to
<code class="literal">'2012-03-23'</code>.
</p><p>
If the connection is configured to fetch warnings, warnings
generated by the operation are available through the
<a class="link" href="#connector-python-api-mysqlcursor-fetchwarnings" title="10.5.14 MySQLCursor.fetchwarnings() Method">MySQLCursor.fetchwarnings()</a>
method.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-executemany"></a>10.5.8 MySQLCursor.executemany() Method</h3></div></div></div><a class="indexterm" name="id4572"></a><a class="indexterm" name="id4574"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">cursor.executemany(operation, seq_of_params)
</pre><p>
This method prepares a database <code class="literal">operation</code>
(query or command) and executes it against all parameter
sequences or mappings found in the sequence
<code class="literal">seq_of_params</code>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
In Python, a tuple containing a single value must include a
comma. For example, <span class="emphasis"><em>('abc')</em></span> is evaluated
as a scalar while <span class="emphasis"><em>('abc',)</em></span> is evaluated
as a tuple.
</p></div><p>
In most cases, the <code class="literal">executemany()</code> method
iterates through the sequence of parameters, each time passing
the current parameters to the <code class="literal">execute()</code>
method.
</p><p>
An optimization is applied for inserts: The data values given by
the parameter sequences are batched using multiple-row syntax.
The following example inserts three records:
</p><pre data-lang="python" class="programlisting">data = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)
</pre><p>
For the preceding example, the
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> statement sent to MySQL
is:
</p><pre data-lang="sql" class="programlisting">INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')
</pre><p>
With the <code class="literal">executemany()</code> method, it is not
possible to specify multiple statements to execute in the
<code class="literal">operation</code> argument. Doing so raises an
<code class="literal">InternalError</code> exception. Consider using
<a class="xref" href="#connector-python-multi" title="9.3 Executing Multiple Statements">Section 9.3, “Executing Multiple Statements”</a> instead.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchall"></a>10.5.9 MySQLCursor.fetchall() Method</h3></div></div></div><a class="indexterm" name="id4601"></a><a class="indexterm" name="id4603"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">rows = cursor.fetchall()
</pre><p>
The method fetches all (or all remaining) rows of a query result
set and returns a list of tuples. If no more rows are available,
it returns an empty list.
</p><p>
The following example shows how to retrieve the first two rows
of a result set, and then retrieve any remaining rows:
</p><pre data-lang="python" class="programlisting">>>> cursor.execute("SELECT * FROM employees ORDER BY emp_no")
>>> head_rows = cursor.fetchmany(size=2)
>>> remaining_rows = cursor.fetchall()
</pre><p>
You must fetch all rows for the current query before executing
new statements using the same connection.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchmany"></a>10.5.10 MySQLCursor.fetchmany() Method</h3></div></div></div><a class="indexterm" name="id4613"></a><a class="indexterm" name="id4615"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">rows = cursor.fetchmany(size=1)
</pre><p>
This method fetches the next set of rows of a query result and
returns a list of tuples. If no more rows are available, it
returns an empty list.
</p><p>
The number of rows returned can be specified using the
<code class="literal">size</code> argument, which defaults to one. Fewer
rows are returned if fewer rows are available than specified.
</p><p>
You must fetch all rows for the current query before executing
new statements using the same connection.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchone"></a>10.5.11 MySQLCursor.fetchone() Method</h3></div></div></div><a class="indexterm" name="id4625"></a><a class="indexterm" name="id4627"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">row = cursor.fetchone()
</pre><p>
This method retrieves the next row of a query result set and
returns a single sequence, or <code class="literal">None</code> if no more
rows are available. By default, the returned tuple consists of
data returned by the MySQL server, converted to Python objects.
If the cursor is a raw cursor, no such conversion occurs; see
<a class="xref" href="#connector-python-api-mysqlcursorraw" title="10.6.2 cursor.MySQLCursorRaw Class">Section 10.6.2, “cursor.MySQLCursorRaw Class”</a>.
</p><p>
The <code class="literal">fetchone()</code> method is used by
<a class="link" href="#connector-python-api-mysqlcursor-fetchall" title="10.5.9 MySQLCursor.fetchall() Method">fetchall()</a>
and
<a class="link" href="#connector-python-api-mysqlcursor-fetchmany" title="10.5.10 MySQLCursor.fetchmany() Method">fetchmany()</a>.
It is also used when a cursor is used as an iterator.
</p><p>
The following example shows two equivalent ways to process a
query result. The first uses <code class="literal">fetchone()</code> in a
<code class="literal">while</code> loop, the second uses the cursor as an
iterator:
</p><pre data-lang="python" class="programlisting"># Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
print(row)
row = cursor.fetchone()
# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
print(row)
</pre><p>
You must fetch all rows for the current query before executing
new statements using the same connection.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-nextset"></a>10.5.12 MySQLCursor.nextset() Method</h3></div></div></div><a class="indexterm" name="id4645"></a><a class="indexterm" name="id4647"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">row = cursor.nextset()
</pre><p>
This method makes the cursor skip to the next available set,
discarding any remaining rows from the current set. It returns
<code class="literal">None</code> if there are no more sets or returns
<code class="literal">True</code> and subsequent calls to the
cursor.fetch*() methods returns rows from the next result set.
</p><p>
This method can be used as part of the multi statement execution
workflow.
</p><pre data-lang="python" class="programlisting">sql_operation = '''
SET @a=1, @b='2025-01-01';
SELECT @a, LENGTH('hello'), @b;
SELECT @@version;
'''
with cnx.cursor() as cur:
cur.execute(sql_operation)
result_set = cur.fetchall()
# do something with result set
...
while cur.nextset():
result_set = cur.fetchall()
# do something with result set
</pre><p>
This method was added in Connector/Python 9.2.0.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchsets"></a>10.5.13 MySQLCursor.fetchsets() Method</h3></div></div></div><a class="indexterm" name="id4659"></a><a class="indexterm" name="id4661"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">for statement, result_set in cursor.fetchsets():
# do something with statement and/or result set
</pre><p>
This method generates a set of result sets caused by the last
cursor.execute*(). It returns a generator where each item is a
2-tuple; the first element is the statement that caused the
result set, and the second is the result set itself.
</p><p>
This method can be used as part of the multi statement execution
workflow.
</p><pre data-lang="python" class="programlisting"> sql_operation = '''
SET @a=1, @b='2025-01-01';
SELECT @a, LENGTH('hello'), @b;
SELECT @@version;
'''
with cnx.cursor() as cur:
cur.execute(sql_operation)
for statement, result_set in cur.fetchsets():
# do something with statement and/or result set
</pre><p>
This method was added in Connector/Python 9.2.0.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-fetchwarnings"></a>10.5.14 MySQLCursor.fetchwarnings() Method</h3></div></div></div><a class="indexterm" name="id4671"></a><a class="indexterm" name="id4673"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This method has been deprecated as of 9.3.0. Use the property
method
<a class="xref" href="#connector-python-api-mysqlcursor-warnings" title="10.5.18 MySQLCursor.warnings Property">Section 10.5.18, “MySQLCursor.warnings Property”</a>
instead.
</p></div><p>
Syntax:
</p><pre data-lang="python" class="programlisting">tuples = cursor.fetchwarnings()
</pre><p>
This method returns a list of tuples containing warnings
generated by the previously executed operation. To set whether
to fetch warnings, use the connection's
<a class="link" href="#connector-python-api-mysqlconnection-get-warnings" title="10.2.45 MySQLConnection.get_warnings Property"><code class="literal">get_warnings</code></a>
property.
</p><p>
The following example shows a
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statement that generates a
warning:
</p><pre data-lang="python" class="programlisting">>>> cnx.get_warnings = True
>>> cursor.execute("SELECT 'a'+1")
>>> cursor.fetchall()
[(1.0,)]
>>> cursor.fetchwarnings()
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
</pre><p>
When warnings are generated, it is possible to raise errors
instead, using the connection's
<a class="link" href="#connector-python-api-mysqlconnection-raise-on-warnings" title="10.2.47 MySQLConnection.raise_on_warnings Property"><code class="literal">raise_on_warnings</code></a>
property.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-stored-results"></a>10.5.15 MySQLCursor.stored_results() Method</h3></div></div></div><a class="indexterm" name="id4693"></a><a class="indexterm" name="id4695"></a><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Deprecation</div><p>
This method has been deprecated as of 9.3.0.
</p></div><p>
Syntax:
</p><pre data-lang="python" class="programlisting">iterator = cursor.stored_results()
</pre><p>
This method returns a list iterator object that can be used to
process result sets produced by a stored procedure executed
using the
<a class="link" href="#connector-python-api-mysqlcursor-callproc" title="10.5.5 MySQLCursor.callproc() Method">callproc()</a>
method. The result sets remain available until you use the
cursor to execute another operation or call another stored
procedure.
</p><p>
The following example executes a stored procedure that produces
two result sets, then uses <code class="literal">stored_results()</code>
to retrieve them:
</p><pre data-lang="python" class="programlisting">>>> cursor.callproc('myproc')
()
>>> for result in cursor.stored_results():
... print result.fetchall()
...
[(1,)]
[(2,)]
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-column-names"></a>10.5.16 MySQLCursor.column_names Property</h3></div></div></div><a class="indexterm" name="id4709"></a><a class="indexterm" name="id4711"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">sequence = cursor.column_names
</pre><p>
This read-only property returns the column names of a result set
as sequence of Unicode strings.
</p><p>
The following example shows how to create a dictionary from a
tuple containing data with keys using
<code class="literal">column_names</code>:
</p><pre data-lang="python" class="programlisting">cursor.execute("SELECT last_name, first_name, hire_date "
"FROM employees WHERE emp_no = %s", (123,))
row = dict(zip(cursor.column_names, cursor.fetchone()))
print("{last_name}, {first_name}: {hire_date}".format(row))
</pre><p>
Alternatively, as of Connector/Python 2.0.0, you can fetch rows as
dictionaries directly; see
<a class="xref" href="#connector-python-api-mysqlcursordict" title="10.6.3 cursor.MySQLCursorDict Class">Section 10.6.3, “cursor.MySQLCursorDict Class”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-description"></a>10.5.17 MySQLCursor.description Property</h3></div></div></div><a class="indexterm" name="id4723"></a><a class="indexterm" name="id4725"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">tuples = cursor.description
</pre><p>
This read-only property returns a list of tuples describing the
columns in a result set. Each tuple in the list contains values
as follows:
</p><pre data-lang="python" class="programlisting">(column_name,
type,
None,
None,
None,
None,
null_ok,
column_flags)
</pre><p>
The following example shows how to interpret
<code class="literal">description</code> tuples:
</p><pre data-lang="python" class="programlisting">import mysql.connector
from mysql.connector import FieldType
...
cursor.execute("SELECT emp_no, last_name, hire_date "
"FROM employees WHERE emp_no = %s", (123,))
for i in range(len(cursor.description)):
print("Column {}:".format(i+1))
desc = cursor.description[i]
print(" column_name = {}".format(desc[0]))
print(" type = {} ({})".format(desc[1], FieldType.get_info(desc[1])))
print(" null_ok = {}".format(desc[6]))
print(" column_flags = {}".format(desc[7]))
</pre><p>
The output looks like this:
</p><pre data-lang="python" class="programlisting">Column 1:
column_name = emp_no
type = 3 (LONG)
null_ok = 0
column_flags = 20483
Column 2:
column_name = last_name
type = 253 (VAR_STRING)
null_ok = 0
column_flags = 4097
Column 3:
column_name = hire_date
type = 10 (DATE)
null_ok = 0
column_flags = 4225
</pre><p>
The <code class="literal">column_flags</code> value is an instance of the
<code class="literal">constants.FieldFlag</code> class. To see how to
interpret it, do this:
</p><pre data-lang="python" class="programlisting">>>> from mysql.connector import FieldFlag
>>> FieldFlag.desc
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-warnings"></a>10.5.18 MySQLCursor.warnings Property</h3></div></div></div><a class="indexterm" name="id4742"></a><a class="indexterm" name="id4744"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">tuples = cursor.warnings
</pre><p>
This property returns a list of tuples containing warnings
generated by the previously executed operation. To set whether
to fetch warnings, use the connection's
<a class="link" href="#connector-python-api-mysqlconnection-get-warnings" title="10.2.45 MySQLConnection.get_warnings Property"><code class="literal">get_warnings</code></a>
property.
</p><p>
The following example shows a
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statement that generates a
warning:
</p><pre data-lang="python" class="programlisting">>>> cnx.get_warnings = True
>>> cursor.execute("SELECT 'a'+1")
>>> cursor.fetchall()
[(1.0,)]
>>> print(cursor.warnings)
[(u'Warning', 1292, u"Truncated incorrect DOUBLE value: 'a'")]
</pre><p>
When warnings are generated, it is possible to raise errors
instead, using the connection's
<a class="link" href="#connector-python-api-mysqlconnection-raise-on-warnings" title="10.2.47 MySQLConnection.raise_on_warnings Property"><code class="literal">raise_on_warnings</code></a>
property.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-lastrowid"></a>10.5.19 MySQLCursor.lastrowid Property</h3></div></div></div><a class="indexterm" name="id4760"></a><a class="indexterm" name="id4762"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">id = cursor.lastrowid
</pre><p>
This read-only property returns the value generated for an
<code class="literal">AUTO_INCREMENT</code> column by the previous
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> or
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a> statement or
<code class="literal">None</code> when there is no such value available.
For example, if you perform an
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> into a table that contains
an <code class="literal">AUTO_INCREMENT</code> column,
<code class="literal">lastrowid</code> returns the
<code class="literal">AUTO_INCREMENT</code> value for the new row. For an
example, see
<a class="xref" href="#connector-python-example-cursor-transaction" title="5.3 Inserting Data Using Connector/Python">Section 5.3, “Inserting Data Using Connector/Python”</a>.
</p><p>
The <code class="literal">lastrowid</code> property is like the
<a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-insert-id.html" target="_top"><code class="literal">mysql_insert_id()</code></a> C API
function; see <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-insert-id.html" target="_top">mysql_insert_id()</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-rowcount"></a>10.5.20 MySQLCursor.rowcount Property</h3></div></div></div><a class="indexterm" name="id4786"></a><a class="indexterm" name="id4788"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">count = cursor.rowcount
</pre><p>
This read-only property returns the number of rows returned for
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a> statements, or the number
of rows affected by DML statements such as
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a> or
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a>. For an example, see
<a class="xref" href="#connector-python-api-mysqlcursor-execute" title="10.5.7 MySQLCursor.execute() Method">Section 10.5.7, “MySQLCursor.execute() Method”</a>.
</p><p>
For nonbuffered cursors, the row count cannot be known before
the rows have been fetched. In this case, the number of rows is
-1 immediately after query execution and is incremented as rows
are fetched.
</p><p>
The <code class="literal">rowcount</code> property is like the
<a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-affected-rows.html" target="_top"><code class="literal">mysql_affected_rows()</code></a> C API
function; see <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-affected-rows.html" target="_top">mysql_affected_rows()</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-statement"></a>10.5.21 MySQLCursor.statement Property</h3></div></div></div><a class="indexterm" name="id4808"></a><a class="indexterm" name="id4810"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">str = cursor.statement
</pre><p>
This read-only property returns the last executed statement as a
string. The <code class="literal">statement</code> property can be useful
for debugging and displaying what was sent to the MySQL server.
</p><p>
The string can contain multiple statements if a
multiple-statement string was executed. This occurs for
<code class="literal">execute()</code> with <code class="literal">multi=True</code>.
In this case, the <code class="literal">statement</code> property contains
the entire statement string and the <code class="literal">execute()</code>
call returns an iterator that can be used to process results
from the individual statements. The <code class="literal">statement</code>
property for this iterator shows statement strings for the
individual statements.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursor-with-rows"></a>10.5.22 MySQLCursor.with_rows Property</h3></div></div></div><a class="indexterm" name="id4824"></a><a class="indexterm" name="id4826"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">boolean = cursor.with_rows
</pre><p>
This read-only property returns <code class="literal">True</code> or
<code class="literal">False</code> to indicate whether the most recently
executed operation could have produced rows.
</p><p>
The <code class="literal">with_rows</code> property is useful when it is
necessary to determine whether a statement produces a result set
and you need to fetch rows. The following example retrieves the
rows returned by the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/select.html" target="_top"><code class="literal">SELECT</code></a>
statements, but reports only the affected-rows value for the
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a> statement:
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect(user='scott', database='test')
cursor = cnx.cursor()
operation = 'SELECT 1; UPDATE t1 SET c1 = 2; SELECT 2'
for result in cursor.execute(operation):
if result.with_rows:
result.fetchall()
else:
print("Number of affected rows: {}".format(result.rowcount))
</pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cursor-subclasses"></a>10.6 Subclasses cursor.MySQLCursor</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffered">10.6.1 cursor.MySQLCursorBuffered Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorraw">10.6.2 cursor.MySQLCursorRaw Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursordict">10.6.3 cursor.MySQLCursorDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorbuffereddict">10.6.4 cursor.MySQLCursorBufferedDict Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-mysqlcursorprepared">10.6.5 cursor.MySQLCursorPrepared Class</a></span></dt></dl></div><a class="indexterm" name="id4842"></a><a class="indexterm" name="id4844"></a><p>
The cursor classes described in the following sections inherit
from the <code class="literal">MySQLCursor</code> class, which is described
in <a class="xref" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class">Section 10.5, “cursor.MySQLCursor Class”</a>.
</p><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorbuffered"></a>10.6.1 cursor.MySQLCursorBuffered Class</h3></div></div></div><a class="indexterm" name="id4851"></a><a class="indexterm" name="id4853"></a><p>
The <code class="literal">MySQLCursorBuffered</code> class inherits from
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
</p><p>
After executing a query, a
<code class="literal">MySQLCursorBuffered</code> cursor fetches the entire
result set from the server and buffers the rows.
</p><p>
For queries executed using a buffered cursor, row-fetching
methods such as
<a class="link" href="#connector-python-api-mysqlcursor-fetchone" title="10.5.11 MySQLCursor.fetchone() Method"><code class="literal">fetchone()</code></a>
return rows from the set of buffered rows. For nonbuffered
cursors, rows are not fetched from the server until a
row-fetching method is called. In this case, you must be sure to
fetch all rows of the result set before executing any other
statements on the same connection, or an
<code class="literal">InternalError</code> (Unread result found) exception
will be raised.
</p><p>
<code class="literal">MySQLCursorBuffered</code> can be useful in
situations where multiple queries, with small result sets, need
to be combined or computed with each other.
</p><p>
To create a buffered cursor, use the <code class="literal">buffered</code>
argument when calling a connection's
<a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
method. Alternatively, to make all cursors created from the
connection buffered by default, use the
<code class="literal">buffered</code>
<a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
argument</a>.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect()
# Only this particular cursor will buffer results
cursor = cnx.cursor(buffered=True)
# All cursors created from cnx2 will be buffered by default
cnx2 = mysql.connector.connect(buffered=True)
</pre><p>
For a practical use case, see
<a class="xref" href="#connector-python-tutorial-cursorbuffered" title="6.1 Tutorial: Raise Employee's Salary Using a Buffered Cursor">Section 6.1, “Tutorial: Raise Employee's Salary Using a Buffered Cursor”</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorraw"></a>10.6.2 cursor.MySQLCursorRaw Class</h3></div></div></div><a class="indexterm" name="id4879"></a><a class="indexterm" name="id4881"></a><p>
The <code class="literal">MySQLCursorRaw</code> class inherits from
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
</p><p>
A <code class="literal">MySQLCursorRaw</code> cursor skips the conversion
from MySQL data types to Python types when fetching rows. A raw
cursor is usually used to get better performance or when you
want to do the conversion yourself.
</p><p>
To create a raw cursor, use the <code class="literal">raw</code> argument
when calling a connection's
<a class="link" href="#connector-python-api-mysqlconnection-cursor" title="10.2.6 MySQLConnection.cursor() Method"><code class="literal">cursor()</code></a>
method. Alternatively, to make all cursors created from the
connection raw by default, use the <code class="literal">raw</code>
<a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
argument</a>.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect()
# Only this particular cursor will be raw
cursor = cnx.cursor(raw=True)
# All cursors created from cnx2 will be raw by default
cnx2 = mysql.connector.connect(raw=True)
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursordict"></a>10.6.3 cursor.MySQLCursorDict Class</h3></div></div></div><a class="indexterm" name="id4899"></a><a class="indexterm" name="id4901"></a><p>
The <code class="literal">MySQLCursorDict</code> class inherits from
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
This class is available as of Connector/Python 2.0.0.
</p><p>
A <code class="literal">MySQLCursorDict</code> cursor returns each row as
a dictionary. The keys for each dictionary object are the column
names of the MySQL result.
</p><p>
Example:
</p><pre data-lang="python" class="programlisting">cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")
print("Countries in Europe:")
for row in cursor:
print("* {Name}".format(Name=row['Name']
</pre><p>
The preceding code produces output like this:
</p><pre data-lang="none" class="programlisting">Countries in Europe:
* Albania
* Andorra
* Austria
* Belgium
* Bulgaria
...
</pre><p>
It may be convenient to pass the dictionary to
<code class="literal">format()</code> as follows:
</p><pre data-lang="python" class="programlisting">cursor.execute("SELECT Name, Population FROM country WHERE Continent = 'Europe'")
print("Countries in Europe with population:")
for row in cursor:
print("* {Name}: {Population}".format(**row))
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorbuffereddict"></a>10.6.4 cursor.MySQLCursorBufferedDict Class</h3></div></div></div><a class="indexterm" name="id4918"></a><a class="indexterm" name="id4920"></a><p>
The <code class="literal">MySQLCursorBufferedDict</code> class inherits
from
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
This class is available as of Connector/Python 2.0.0.
</p><p>
A <code class="literal">MySQLCursorBufferedDict</code> cursor is like a
<a class="link" href="#connector-python-api-mysqlcursordict" title="10.6.3 cursor.MySQLCursorDict Class"><code class="literal">MySQLCursorDict</code></a>
cursor, but is buffered: After executing a query, it fetches the
entire result set from the server and buffers the rows. For
information about the implications of buffering, see
<a class="xref" href="#connector-python-api-mysqlcursorbuffered" title="10.6.1 cursor.MySQLCursorBuffered Class">Section 10.6.1, “cursor.MySQLCursorBuffered Class”</a>.
</p><p>
To get a buffered cursor that returns dictionaries, add the
<code class="literal">buffered</code> argument when instantiating a new
dictionary cursor:
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(dictionary=True, buffered=True)
</pre></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-mysqlcursorprepared"></a>10.6.5 cursor.MySQLCursorPrepared Class</h3></div></div></div><a class="indexterm" name="id4936"></a><a class="indexterm" name="id4938"></a><a class="indexterm" name="id4941"></a><p>
The <code class="literal">MySQLCursorPrepared</code> class inherits from
<a class="link" href="#connector-python-api-mysqlcursor" title="10.5 cursor.MySQLCursor Class"><code class="literal">MySQLCursor</code></a>.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
This class is available as of Connector/Python 1.1.0. The C extension
supports it as of Connector/Python 8.0.17.
</p></div><p>
In MySQL, there are two ways to execute a prepared statement:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
Use the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/prepare.html" target="_top"><code class="literal">PREPARE</code></a> and
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/execute.html" target="_top"><code class="literal">EXECUTE</code></a> statements.
</p></li><li class="listitem"><p>
Use the binary client/server protocol to send and receive
data. To repeatedly execute the same statement with
different data for different executions, this is more
efficient than using <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/prepare.html" target="_top"><code class="literal">PREPARE</code></a>
and <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/execute.html" target="_top"><code class="literal">EXECUTE</code></a>. For information
about the binary protocol, see
<a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/c-api-prepared-statement-interface.html" target="_top">C API Prepared Statement Interface</a>.
</p></li></ul></div><p>
In Connector/Python, there are two ways to create a cursor that enables
execution of prepared statements using the binary protocol. In
both cases, the <code class="literal">cursor()</code> method of the
connection object returns a
<code class="literal">MySQLCursorPrepared</code> object:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
The simpler syntax uses a <code class="literal">prepared=True</code>
argument to the <code class="literal">cursor()</code> method. This
syntax is available as of Connector/Python 1.1.2.
</p><pre data-lang="python" class="programlisting">import mysql.connector
cnx = mysql.connector.connect(database='employees')
cursor = cnx.cursor(prepared=True)
</pre></li><li class="listitem"><p>
Alternatively, create an instance of the
<code class="literal">MySQLCursorPrepared</code> class using the
<code class="literal">cursor_class</code> argument to the
<code class="literal">cursor()</code> method. This syntax is available
as of Connector/Python 1.1.0.
</p><pre data-lang="python" class="programlisting">import mysql.connector
from mysql.connector.cursor import MySQLCursorPrepared
cnx = mysql.connector.connect(database='employees')
cursor = cnx.cursor(cursor_class=MySQLCursorPrepared)
</pre></li></ul></div><p>
A cursor instantiated from the
<code class="literal">MySQLCursorPrepared</code> class works like this:
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
The first time you pass a statement to the cursor's
<code class="literal">execute()</code> method, it prepares the
statement. For subsequent invocations of
<code class="literal">execute()</code>, the preparation phase is
skipped if the statement is the same.
</p></li><li class="listitem"><p>
The <code class="literal">execute()</code> method takes an optional
second argument containing a list of data values to
associate with parameter markers in the statement. If the
list argument is present, there must be one value per
parameter marker.
</p></li></ul></div><p>
Example:
</p><pre data-lang="python" class="programlisting">cursor = cnx.cursor(prepared=True)
stmt = "SELECT fullname FROM employees WHERE id = %s" # (1)
cursor.execute(stmt, (5,)) # (2)
# ... fetch data ...
cursor.execute(stmt, (10,)) # (3)
# ... fetch data ...
</pre><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>
The <code class="literal">%s</code> within the statement is a
parameter marker. Do not put quote marks around parameter
markers.
</p></li><li class="listitem"><p>
For the first call to the <code class="literal">execute()</code>
method, the cursor prepares the statement. If data is given
in the same call, it also executes the statement and you
should fetch the data.
</p></li><li class="listitem"><p>
For subsequent <code class="literal">execute()</code> calls that pass
the same SQL statement, the cursor skips the preparation
phase.
</p></li></ol></div><p>
Prepared statements executed with
<code class="literal">MySQLCursorPrepared</code> can use the
<code class="literal">format</code> (<code class="literal">%s</code>) or
<code class="literal">qmark</code> (<code class="literal">?</code>) parameterization
style. This differs from nonprepared statements executed with
<code class="literal">MySQLCursor</code>, which can use the
<code class="literal">format</code> or <code class="literal">pyformat</code>
parameterization style.
</p><p>
To use multiple prepared statements simultaneously, instantiate
multiple cursors from the <code class="literal">MySQLCursorPrepared</code>
class.
</p><a class="indexterm" name="id5012"></a><p>
The MySQL client/server protocol has an option to send prepared
statement parameters via the
<code class="literal">COM_STMT_SEND_LONG_DATA</code> command. To use this
from Connector/Python scripts, send the parameter in question using the
<code class="literal">IOBase</code> interface. Example:
</p><pre data-lang="python" class="programlisting">from io import IOBase
...
cur = cnx.cursor(prepared=True)
cur.execute("SELECT (%s)", (io.BytesIO(bytes("A", "latin1")), ))
</pre></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-clientflag"></a>10.7 constants.ClientFlag Class</h2></div></div></div><a class="indexterm" name="id5020"></a><a class="indexterm" name="id5022"></a><p>
This class provides constants defining MySQL client flags that can
be used when the connection is established to configure the
session. The <code class="literal">ClientFlag</code> class is available when
importing <code class="literal">mysql.connector</code>.
</p><pre data-lang="python" class="programlisting">
>>> import mysql.connector
>>> mysql.connector.ClientFlag.FOUND_ROWS
2</pre><p>
See
<a class="xref" href="#connector-python-api-mysqlconnection-set-client-flags" title="10.2.32 MySQLConnection.set_client_flags() Method">Section 10.2.32, “MySQLConnection.set_client_flags() Method”</a>
and the <a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">connection
argument</a> <code class="literal">client_flag</code>.
</p><p>
The <code class="literal">ClientFlag</code> class cannot be instantiated.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-fieldtype"></a>10.8 constants.FieldType Class</h2></div></div></div><a class="indexterm" name="id5036"></a><a class="indexterm" name="id5038"></a><p>
This class provides all supported MySQL field or data types. They
can be useful when dealing with raw data or defining your own
converters. The field type is stored with every cursor in the
description for each column.
</p><p>
The following example shows how to print the name of the data type
for each column in a result set.
</p><pre data-lang="python" class="programlisting">from __future__ import print_function
import mysql.connector
from mysql.connector import FieldType
cnx = mysql.connector.connect(user='scott', database='test')
cursor = cnx.cursor()
cursor.execute(
"SELECT DATE(NOW()) AS `c1`, TIME(NOW()) AS `c2`, "
"NOW() AS `c3`, 'a string' AS `c4`, 42 AS `c5`")
rows = cursor.fetchall()
for desc in cursor.description:
colname = desc[0]
coltype = desc[1]
print("Column {} has type {}".format(
colname, FieldType.get_info(coltype)))
cursor.close()
cnx.close()
</pre><p>
The <code class="literal">FieldType</code> class cannot be instantiated.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-sqlmode"></a>10.9 constants.SQLMode Class</h2></div></div></div><a class="indexterm" name="id5047"></a><a class="indexterm" name="id5049"></a><p>
This class provides all known MySQL
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">Server SQL Modes</a>. It is mostly
used when setting the SQL modes at connection time using the
connection's <code class="literal">sql_mode</code> property. See
<a class="xref" href="#connector-python-api-mysqlconnection-sql-mode" title="10.2.52 MySQLConnection.sql_mode Property">Section 10.2.52, “MySQLConnection.sql_mode Property”</a>.
</p><p>
The <code class="literal">SQLMode</code> class cannot be instantiated.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-characterset"></a>10.10 constants.CharacterSet Class</h2></div></div></div><a class="indexterm" name="id5059"></a><a class="indexterm" name="id5061"></a><p>
This class provides all known MySQL characters sets and their
default collations. For examples, see
<a class="xref" href="#connector-python-api-mysqlconnection-set-charset-collation" title="10.2.31 MySQLConnection.set_charset_collation() Method">Section 10.2.31, “MySQLConnection.set_charset_collation() Method”</a>.
</p><p>
The <code class="literal">CharacterSet</code> class cannot be instantiated.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-refreshoption"></a>10.11 constants.RefreshOption Class</h2></div></div></div><a class="indexterm" name="id5069"></a><a class="indexterm" name="id5071"></a><p>
This class performs various flush operations.
</p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
<code class="literal">RefreshOption.GRANT</code>
</p><p>
Refresh the grant tables, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-privileges" target="_top"><code class="literal">FLUSH
PRIVILEGES</code></a>.
</p></li><li class="listitem"><p>
<code class="literal">RefreshOption.LOG</code>
</p><p>
Flush the logs, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-logs" target="_top"><code class="literal">FLUSH
LOGS</code></a>.
</p></li><li class="listitem"><p>
<code class="literal">RefreshOption.TABLES</code>
</p><p>
Flush the table cache, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-tables" target="_top"><code class="literal">FLUSH
TABLES</code></a>.
</p></li><li class="listitem"><p>
<code class="literal">RefreshOption.HOSTS</code>
</p><p>
Flush the host cache, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-hosts" target="_top"><code class="literal">FLUSH
HOSTS</code></a>.
</p></li><li class="listitem"><p>
<code class="literal">RefreshOption.STATUS</code>
</p><p>
Reset status variables, like <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/flush.html#flush-status" target="_top"><code class="literal">FLUSH
STATUS</code></a>.
</p></li><li class="listitem"><p>
<code class="literal">RefreshOption.THREADS</code>
</p><p>
Flush the thread cache.
</p></li><li class="listitem"><p>
<code class="literal">RefreshOption.REPLICA</code>
</p><p>
On a replica replication server, reset the source server
information and restart the replica, like
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/reset-slave.html" target="_top"><code class="literal">RESET SLAVE</code></a>. This constant was
named "RefreshOption.SLAVE" before v8.0.23.
</p></li></ul></div></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-errors"></a>10.12 Errors and Exceptions</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="section"><a href="#connector-python-api-errorcode">10.12.1 errorcode Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-error">10.12.2 errors.Error Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-dataerror">10.12.3 errors.DataError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-databaseerror">10.12.4 errors.DatabaseError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-integrityerror">10.12.5 errors.IntegrityError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-interfaceerror">10.12.6 errors.InterfaceError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-internalerror">10.12.7 errors.InternalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-notsupportederror">10.12.8 errors.NotSupportedError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-operationalerror">10.12.9 errors.OperationalError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-poolerror">10.12.10 errors.PoolError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-programmingerror">10.12.11 errors.ProgrammingError Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-warning">10.12.12 errors.Warning Exception</a></span></dt><dt><span class="section"><a href="#connector-python-api-errors-custom-error-exception">10.12.13 errors.custom_error_exception() Function</a></span></dt></dl></div><p>
The <code class="literal">mysql.connector.errors</code> module defines
exception classes for errors and warnings raised by MySQL Connector/Python. Most
classes defined in this module are available when you import
<code class="literal">mysql.connector</code>.
</p><p>
The exception classes defined in this module mostly follow the
Python Database API Specification v2.0 (PEP 249). For some MySQL
client or server errors it is not always clear which exception to
raise. It is good to discuss whether an error should be
reclassified by opening a bug report.
</p><p>
MySQL Server errors are mapped with Python exception based on
their SQLSTATE value (see
<a class="ulink" href="https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html" target="_top">Server Error Message Reference</a>). The following table
shows the SQLSTATE classes and the exception Connector/Python raises. It is,
however, possible to redefine which exception is raised for each
server error. The default exception is
<code class="literal">DatabaseError</code>.
</p><div class="table"><a name="connector-python-api-errors-exceptions-map"></a><p class="title"><b>Table 10.1 Mapping of Server Errors to Python Exceptions</b></p><div class="table-contents"><table><col width="40%"><col width="60%"><thead><tr>
<th scope="col">SQLSTATE Class</th>
<th scope="col">Connector/Python Exception</th>
</tr></thead><tbody><tr>
<td><code class="literal">02</code></td>
<td><code class="literal">DataError</code></td>
</tr><tr>
<td><code class="literal">02</code></td>
<td><code class="literal">DataError</code></td>
</tr><tr>
<td><code class="literal">07</code></td>
<td><code class="literal">DatabaseError</code></td>
</tr><tr>
<td><code class="literal">08</code></td>
<td><code class="literal">OperationalError</code></td>
</tr><tr>
<td><code class="literal">0A</code></td>
<td><code class="literal">NotSupportedError</code></td>
</tr><tr>
<td><code class="literal">21</code></td>
<td><code class="literal">DataError</code></td>
</tr><tr>
<td><code class="literal">22</code></td>
<td><code class="literal">DataError</code></td>
</tr><tr>
<td><code class="literal">23</code></td>
<td><code class="literal">IntegrityError</code></td>
</tr><tr>
<td><code class="literal">24</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">25</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">26</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">27</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">28</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">2A</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">2B</code></td>
<td><code class="literal">DatabaseError</code></td>
</tr><tr>
<td><code class="literal">2C</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">2D</code></td>
<td><code class="literal">DatabaseError</code></td>
</tr><tr>
<td><code class="literal">2E</code></td>
<td><code class="literal">DatabaseError</code></td>
</tr><tr>
<td><code class="literal">33</code></td>
<td><code class="literal">DatabaseError</code></td>
</tr><tr>
<td><code class="literal">34</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">35</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">37</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">3C</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">3D</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">3F</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">40</code></td>
<td><code class="literal">InternalError</code></td>
</tr><tr>
<td><code class="literal">42</code></td>
<td><code class="literal">ProgrammingError</code></td>
</tr><tr>
<td><code class="literal">44</code></td>
<td><code class="literal">InternalError</code></td>
</tr><tr>
<td><code class="literal">HZ</code></td>
<td><code class="literal">OperationalError</code></td>
</tr><tr>
<td><code class="literal">XA</code></td>
<td><code class="literal">IntegrityError</code></td>
</tr><tr>
<td><code class="literal">0K</code></td>
<td><code class="literal">OperationalError</code></td>
</tr><tr>
<td><code class="literal">HY</code></td>
<td><code class="literal">DatabaseError</code></td>
</tr></tbody></table></div></div><br class="table-break"><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errorcode"></a>10.12.1 errorcode Module</h3></div></div></div><a class="indexterm" name="id5295"></a><a class="indexterm" name="id5297"></a><p>
This module contains both MySQL server and client error codes
defined as module attributes with the error number as value.
Using error codes instead of error numbers could make reading
the source code a bit easier.
</p><pre data-lang="python" class="programlisting">
>>> from mysql.connector import errorcode
>>> errorcode.ER_BAD_TABLE_ERROR
1051</pre><p>
For more information about MySQL errors, see
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/error-handling.html" target="_top">Error Messages and Common Problems</a>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-error"></a>10.12.2 errors.Error Exception</h3></div></div></div><a class="indexterm" name="id5305"></a><a class="indexterm" name="id5307"></a><p>
This exception is the base class for all other exceptions in the
<code class="literal">errors</code> module. It can be used to catch all
errors in a single <code class="literal">except</code> statement.
</p><p>
The following example shows how we could catch syntax errors:
</p><pre data-lang="python" class="programlisting">import mysql.connector
try:
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
cursor.execute("SELECT * FORM employees") # Syntax error in query
cnx.close()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
</pre><p>
Initializing the exception supports a few optional arguments,
namely <code class="literal">msg</code>, <code class="literal">errno</code>,
<code class="literal">values</code> and <code class="literal">sqlstate</code>. All
of them are optional and default to <code class="literal">None</code>.
<code class="literal">errors.Error</code> is internally used by Connector/Python to
raise MySQL client and server errors and should not be used by
your application to raise exceptions.
</p><p>
The following examples show the result when using no arguments
or a combination of the arguments:
</p><pre data-lang="python" class="programlisting">
>>> from mysql.connector.errors import Error
>>> str(Error())
'Unknown error'
>>> str(Error("Oops! There was an error."))
'Oops! There was an error.'
>>> str(Error(errno=2006))
'2006: MySQL server has gone away'
>>> str(Error(errno=2002, values=('/tmp/mysql.sock', 2)))
"2002: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)"
>>> str(Error(errno=1146, sqlstate='42S02', msg="Table 'test.spam' doesn't exist"))
"1146 (42S02): Table 'test.spam' doesn't exist"</pre><p>
The example which uses error number 1146 is used when Connector/Python
receives an error packet from the MySQL Server. The information
is parsed and passed to the <code class="literal">Error</code> exception
as shown.
</p><p>
Each exception subclassing from <code class="literal">Error</code> can be
initialized using the previously mentioned arguments.
Additionally, each instance has the attributes
<code class="literal">errno</code>, <code class="literal">msg</code> and
<code class="literal">sqlstate</code> which can be used in your code.
</p><p>
The following example shows how to handle errors when dropping a
table which does not exist (when the <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/drop-table.html" target="_top"><code class="literal">DROP
TABLE</code></a> statement does not include a <code class="literal">IF
EXISTS</code> clause):
</p><pre data-lang="python" class="programlisting">import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect(user='scott', database='test')
cursor = cnx.cursor()
try:
cursor.execute("DROP TABLE spam")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_TABLE_ERROR:
print("Creating table spam")
else:
raise
</pre><p>
Prior to Connector/Python 1.1.1, the original message passed to
<code class="literal">errors.Error()</code> is not saved in such a way
that it could be retrieved. Instead, the
<code class="literal">Error.msg</code> attribute was formatted with the
error number and SQLSTATE value. As of 1.1.1, only the original
message is saved in the <code class="literal">Error.msg</code> attribute.
The formatted value together with the error number and SQLSTATE
value can be obtained by printing or getting the string
representation of the error object. Example:
</p><pre data-lang="python" class="programlisting">try:
conn = mysql.connector.connect(database = "baddb")
except mysql.connector.Error as e:
print "Error code:", e.errno # error number
print "SQLSTATE value:", e.sqlstate # SQLSTATE value
print "Error message:", e.msg # error message
print "Error:", e # errno, sqlstate, msg values
s = str(e)
print "Error:", s # errno, sqlstate, msg values
</pre><p>
<code class="literal">errors.Error</code> is a subclass of the Python
<code class="literal">StandardError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-dataerror"></a>10.12.3 errors.DataError Exception</h3></div></div></div><a class="indexterm" name="id5345"></a><a class="indexterm" name="id5347"></a><p>
This exception is raised when there were problems with the data.
Examples are a column set to <code class="literal">NULL</code> that cannot
be <code class="literal">NULL</code>, out-of-range values for a column,
division by zero, column count does not match value count, and
so on.
</p><p>
<code class="literal">errors.DataError</code> is a subclass of
<code class="literal">errors.DatabaseError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-databaseerror"></a>10.12.4 errors.DatabaseError Exception</h3></div></div></div><a class="indexterm" name="id5357"></a><a class="indexterm" name="id5359"></a><p>
This exception is the default for any MySQL error which does not
fit the other exceptions.
</p><p>
<code class="literal">errors.DatabaseError</code> is a subclass of
<code class="literal">errors.Error</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-integrityerror"></a>10.12.5 errors.IntegrityError Exception</h3></div></div></div><a class="indexterm" name="id5367"></a><a class="indexterm" name="id5369"></a><p>
This exception is raised when the relational integrity of the
data is affected. For example, a duplicate key was inserted or a
foreign key constraint would fail.
</p><p>
The following example shows a duplicate key error raised as
IntegrityError:
</p><pre data-lang="python" class="programlisting">cursor.execute("CREATE TABLE t1 (id int, PRIMARY KEY (id))")
try:
cursor.execute("INSERT INTO t1 (id) VALUES (1)")
cursor.execute("INSERT INTO t1 (id) VALUES (1)")
except mysql.connector.IntegrityError as err:
print("Error: {}".format(err))
</pre><p>
<code class="literal">errors.IntegrityError</code> is a subclass of
<code class="literal">errors.DatabaseError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-interfaceerror"></a>10.12.6 errors.InterfaceError Exception</h3></div></div></div><a class="indexterm" name="id5379"></a><a class="indexterm" name="id5381"></a><p>
This exception is raised for errors originating from Connector/Python
itself, not related to the MySQL server.
</p><p>
<code class="literal">errors.InterfaceError</code> is a subclass of
<code class="literal">errors.Error</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-internalerror"></a>10.12.7 errors.InternalError Exception</h3></div></div></div><a class="indexterm" name="id5389"></a><a class="indexterm" name="id5391"></a><p>
This exception is raised when the MySQL server encounters an
internal error, for example, when a deadlock occurred.
</p><p>
<code class="literal">errors.InternalError</code> is a subclass of
<code class="literal">errors.DatabaseError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-notsupportederror"></a>10.12.8 errors.NotSupportedError Exception</h3></div></div></div><a class="indexterm" name="id5399"></a><a class="indexterm" name="id5401"></a><p>
This exception is raised when some feature was used that is not
supported by the version of MySQL that returned the error. It is
also raised when using functions or statements that are not
supported by stored routines.
</p><p>
<code class="literal">errors.NotSupportedError</code> is a subclass of
<code class="literal">errors.DatabaseError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-operationalerror"></a>10.12.9 errors.OperationalError Exception</h3></div></div></div><a class="indexterm" name="id5409"></a><a class="indexterm" name="id5411"></a><p>
This exception is raised for errors which are related to MySQL's
operations. For example: too many connections; a host name could
not be resolved; bad handshake; server is shutting down,
communication errors.
</p><p>
<code class="literal">errors.OperationalError</code> is a subclass of
<code class="literal">errors.DatabaseError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-poolerror"></a>10.12.10 errors.PoolError Exception</h3></div></div></div><a class="indexterm" name="id5419"></a><a class="indexterm" name="id5421"></a><p>
This exception is raised for connection pool errors.
<code class="literal">errors.PoolError</code> is a subclass of
<code class="literal">errors.Error</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-programmingerror"></a>10.12.11 errors.ProgrammingError Exception</h3></div></div></div><a class="indexterm" name="id5428"></a><a class="indexterm" name="id5430"></a><p>
This exception is raised on programming errors, for example when
you have a syntax error in your SQL or a table was not found.
</p><p>
The following example shows how to handle syntax errors:
</p><pre data-lang="python" class="programlisting">try:
cursor.execute("CREATE DESK t1 (id int, PRIMARY KEY (id))")
except mysql.connector.ProgrammingError as err:
if err.errno == errorcode.ER_SYNTAX_ERROR:
print("Check your syntax!")
else:
print("Error: {}".format(err))
</pre><p>
<code class="literal">errors.ProgrammingError</code> is a subclass of
<code class="literal">errors.DatabaseError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-warning"></a>10.12.12 errors.Warning Exception</h3></div></div></div><a class="indexterm" name="id5440"></a><a class="indexterm" name="id5442"></a><p>
This exception is used for reporting important warnings,
however, Connector/Python does not use it. It is included to be compliant
with the Python Database Specification v2.0 (PEP-249).
</p><p>
Consider using either more strict
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html" target="_top">Server SQL Modes</a> or the
<a class="link" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">raise_on_warnings</a>
connection argument to make Connector/Python raise errors when your queries
produce warnings.
</p><p>
<code class="literal">errors.Warning</code> is a subclass of the Python
<code class="literal">StandardError</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h3 class="title"><a name="connector-python-api-errors-custom-error-exception"></a>10.12.13 errors.custom_error_exception() Function</h3></div></div></div><a class="indexterm" name="id5453"></a><a class="indexterm" name="id5455"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">errors.custom_error_exception(error=None, exception=None)
</pre><p>
This method defines custom exceptions for MySQL server errors
and returns current customizations.
</p><p>
If <code class="literal">error</code> is a MySQL Server error number, you
must also pass the <code class="literal">exception</code> class. The
<code class="literal">error</code> argument can be a dictionary, in which
case the key is the server error number, and value the class of
the exception to be raised.
</p><p>
To reset the customizations, supply an empty dictionary.
</p><pre data-lang="python" class="programlisting">import mysql.connector
from mysql.connector import errorcode
# Server error 1028 should raise a DatabaseError
mysql.connector.custom_error_exception(1028, mysql.connector.DatabaseError)
# Or using a dictionary:
mysql.connector.custom_error_exception({
1028: mysql.connector.DatabaseError,
1029: mysql.connector.OperationalError,
})
# To reset, pass an empty dictionary:
mysql.connector.custom_error_exception({})
</pre></div></div></div><div class="chapter"><div class="titlepage"><div><div><h1 class="title"><a name="connector-python-cext-reference"></a>Chapter 11 Connector/Python C Extension API Reference</h1></div></div></div><div class="toc"><p><b>Table of Contents</b></p><dl class="toc"><dt><span class="section"><a href="#connector-python-api-cext-mysql-connector">11.1 _mysql_connector Module</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-mysql">11.2 _mysql_connector.MySQL() Class</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-affected-rows">11.3 _mysql_connector.MySQL.affected_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-autocommit">11.4 _mysql_connector.MySQL.autocommit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-buffered">11.5 _mysql_connector.MySQL.buffered() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-change-user">11.6 _mysql_connector.MySQL.change_user() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-character-set-name">11.7 _mysql_connector.MySQL.character_set_name() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-close">11.8 _mysql_connector.MySQL.close() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-commit">11.9 _mysql_connector.MySQL.commit() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connect">11.10 _mysql_connector.MySQL.connect() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-connected">11.11 _mysql_connector.MySQL.connected() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-consume-result">11.12 _mysql_connector.MySQL.consume_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-convert-to-mysql">11.13 _mysql_connector.MySQL.convert_to_mysql() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-escape-string">11.14 _mysql_connector.MySQL.escape_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-fields">11.15 _mysql_connector.MySQL.fetch_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-fetch-row">11.16 _mysql_connector.MySQL.fetch_row() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-field-count">11.17 _mysql_connector.MySQL.field_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-free-result">11.18 _mysql_connector.MySQL.free_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-character-set-info">11.19 _mysql_connector.MySQL.get_character_set_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-info">11.20 _mysql_connector.MySQL.get_client_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-client-version">11.21 _mysql_connector.MySQL.get_client_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-host-info">11.22 _mysql_connector.MySQL.get_host_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-proto-info">11.23 _mysql_connector.MySQL.get_proto_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-info">11.24 _mysql_connector.MySQL.get_server_info() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-server-version">11.25 _mysql_connector.MySQL.get_server_version() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-get-ssl-cipher">11.26 _mysql_connector.MySQL.get_ssl_cipher() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-hex-string">11.27 _mysql_connector.MySQL.hex_string() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-insert-id">11.28 _mysql_connector.MySQL.insert_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-more-results">11.29 _mysql_connector.MySQL.more_results() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-next-result">11.30 _mysql_connector.MySQL.next_result() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-fields">11.31 _mysql_connector.MySQL.num_fields() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-num-rows">11.32 _mysql_connector.MySQL.num_rows() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-ping">11.33 _mysql_connector.MySQL.ping() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-query">11.34 _mysql_connector.MySQL.query() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-raw">11.35 _mysql_connector.MySQL.raw() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-refresh">11.36 _mysql_connector.MySQL.refresh() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-reset-connection">11.37 _mysql_connector.MySQL.reset_connection() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-rollback">11.38 _mysql_connector.MySQL.rollback() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-select-db">11.39 _mysql_connector.MySQL.select_db() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-set-character-set">11.40 _mysql_connector.MySQL.set_character_set() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-shutdown">11.41 _mysql_connector.MySQL.shutdown() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-stat">11.42 _mysql_connector.MySQL.stat() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-thread-id">11.43 _mysql_connector.MySQL.thread_id() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-use-unicode">11.44 _mysql_connector.MySQL.use_unicode() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-warning-count">11.45 _mysql_connector.MySQL.warning_count() Method</a></span></dt><dt><span class="section"><a href="#connector-python-api-cext-have-result-set">11.46 _mysql_connector.MySQL.have_result_set Property</a></span></dt></dl></div><p>
This chapter contains the public API reference for the Connector/Python C
Extension, also known as the <code class="literal">_mysql_connector</code>
Python module.
</p><p>
The <code class="literal">_mysql_connector</code> C Extension module can be
used directly without any other code of Connector/Python. One reason to use
this module directly is for performance reasons.
</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
Examples in this reference use <code class="literal">ccnx</code> to
represent a connector object as used with the
<code class="literal">_mysql_connector</code> C Extension module.
<code class="literal">ccnx</code> is an instance of the
<code class="literal">_mysql_connector.MySQL()</code> class. It is distinct
from the <code class="literal">cnx</code> object used in examples for the
<code class="literal">mysql.connector</code> Connector/Python module described in
<a class="xref" href="#connector-python-reference" title="Chapter 10 Connector/Python API Reference">Chapter 10, <i>Connector/Python API Reference</i></a>.
<code class="literal">cnx</code> is an instance of the object returned by
the <code class="literal">connect()</code> method of the
<code class="literal">MySQLConnection</code> class.
</p></div><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><div class="admon-title">Note</div><p>
The C Extension is not part of the pure Python installation. It is
an optional module that must be installed using a binary
distribution of Connector/Python that includes it, or compiled using a source
distribution. See <a class="xref" href="#connector-python-installation" title="Chapter 4 Connector/Python Installation">Chapter 4, <i>Connector/Python Installation</i></a>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-mysql-connector"></a>11.1 _mysql_connector Module</h2></div></div></div><a class="indexterm" name="id5489"></a><a class="indexterm" name="id5491"></a><p>
The <code class="literal">_mysql_connector</code> module provides classes.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-mysql"></a>11.2 _mysql_connector.MySQL() Class</h2></div></div></div><a class="indexterm" name="id5497"></a><a class="indexterm" name="id5499"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx = _mysql_connector.MySQL(<em class="replaceable"><code>args</code></em>)
</pre><p>
The <code class="literal">MySQL</code> class is used to open and manage a
connection to a MySQL server (referred to elsewhere in this
reference as <span class="quote">“<span class="quote">the <code class="literal">MySQL</code>
instance</span>”</span>). It is also used to send commands and SQL
statements and read results.
</p><p>
The <code class="literal">MySQL</code> class wraps most functions found in
the MySQL C Client API and adds some additional convenient
functionality.
</p><pre data-lang="python" class="programlisting">import _mysql_connector
ccnx = _mysql_connector.MySQL()
ccnx.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
host='127.0.0.1', database='employees')
ccnx.close()
</pre><p>
Permitted arguments for the <code class="literal">MySQL</code> class are
<code class="literal">auth_plugin</code>, <code class="literal">buffered</code>,
<code class="literal">charset_name</code>,
<code class="literal">connection_timeout</code>, <code class="literal">raw</code>,
<code class="literal">use_unicode</code>. Those arguments correspond to the
arguments of the same names for
<code class="literal">MySQLConnection.connect()</code> as described at
<a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>, except that
<code class="literal">charset_name</code> corresponds to
<code class="literal">charset</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-affected-rows"></a>11.3 _mysql_connector.MySQL.affected_rows() Method</h2></div></div></div><a class="indexterm" name="id5526"></a><a class="indexterm" name="id5528"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">count = ccnx.affected_rows()
</pre><p>
Returns the number of rows changed, inserted, or deleted by the
most recent <a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/update.html" target="_top"><code class="literal">UPDATE</code></a>,
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/insert.html" target="_top"><code class="literal">INSERT</code></a>, or
<a class="ulink" href="https://dev.mysql.com/doc/refman/8.0/en/delete.html" target="_top"><code class="literal">DELETE</code></a> statement.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-autocommit"></a>11.4 _mysql_connector.MySQL.autocommit() Method</h2></div></div></div><a class="indexterm" name="id5541"></a><a class="indexterm" name="id5543"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.autocommit(<em class="replaceable"><code>bool</code></em>)
</pre><p>
Sets the autocommit mode.
</p><p>
Raises a <code class="literal">ValueError</code> exception if
<code class="literal">mode</code> is not <code class="literal">True</code> or
<code class="literal">False</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-buffered"></a>11.5 _mysql_connector.MySQL.buffered() Method</h2></div></div></div><a class="indexterm" name="id5556"></a><a class="indexterm" name="id5558"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">is_buffered = ccnx.buffered() # getter
ccnx.buffered(<em class="replaceable"><code>bool</code></em>) # setter
</pre><p>
With no argument, returns <code class="literal">True</code> or
<code class="literal">False</code> to indicate whether the
<code class="literal">MySQL</code> instance buffers (stores) the results.
</p><p>
With a boolean argument, sets the <code class="literal">MySQL</code>
instance buffering mode.
</p><p>
For the setter syntax, raises a <code class="literal">TypeError</code>
exception if the value is not <code class="literal">True</code> or
<code class="literal">False</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-change-user"></a>11.6 _mysql_connector.MySQL.change_user() Method</h2></div></div></div><a class="indexterm" name="id5575"></a><a class="indexterm" name="id5577"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.change_user(user='<em class="replaceable"><code>user_name</code></em>,
password='<em class="replaceable"><code>password_val</code></em>',
database='<code class="literal">db_name</code>')
</pre><p>
Changes the user and sets a new default database. Permitted
arguments are <code class="literal">user</code>,
<code class="literal">password</code>, and <code class="literal">database</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-character-set-name"></a>11.7 _mysql_connector.MySQL.character_set_name() Method</h2></div></div></div><a class="indexterm" name="id5590"></a><a class="indexterm" name="id5592"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">charset = ccnx.character_set_name()
</pre><p>
Returns the name of the default character set for the current
MySQL session.
</p><p>
Some MySQL character sets have no equivalent names in Python. When
this is the case, a name usable by Python is returned. For
example, the <code class="literal">'utf8mb4'</code> MySQL character set name
is returned as <code class="literal">'utf8'</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-close"></a>11.8 _mysql_connector.MySQL.close() Method</h2></div></div></div><a class="indexterm" name="id5602"></a><a class="indexterm" name="id5604"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.close()
</pre><p>
Closes the MySQL connection.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-commit"></a>11.9 _mysql_connector.MySQL.commit() Method</h2></div></div></div><a class="indexterm" name="id5611"></a><a class="indexterm" name="id5613"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.commit()
</pre><p>
Commits the current transaction.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-connect"></a>11.10 _mysql_connector.MySQL.connect() Method</h2></div></div></div><a class="indexterm" name="id5620"></a><a class="indexterm" name="id5622"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.connect(<em class="replaceable"><code>args</code></em>)
</pre><p>
Connects to a MySQL server.
</p><pre data-lang="python" class="programlisting">import _mysql_connector
ccnx = _mysql_connector.MySQL()
ccnx.connect(user='scott', password='<em class="replaceable"><code>password</code></em>',
host='127.0.0.1', database='employees')
ccnx.close()
</pre><p>
<code class="literal">connect()</code> supports the following arguments:
<code class="literal">host</code>, <code class="literal">user</code>,
<code class="literal">password</code>, <code class="literal">database</code>,
<code class="literal">port</code>, <code class="literal">unix_socket</code>,
<code class="literal">client_flags</code>, <code class="literal">ssl_ca</code>,
<code class="literal">ssl_cert</code>, <code class="literal">ssl_key</code>,
<code class="literal">ssl_verify_cert</code>, <code class="literal">compress</code>.
See <a class="xref" href="#connector-python-connectargs" title="7.1 Connector/Python Connection Arguments">Section 7.1, “Connector/Python Connection Arguments”</a>.
</p><p>
If <code class="literal">ccnx</code> is already connected,
<code class="literal">connect()</code> discards any pending result set and
closes the connection before reopening it.
</p><p>
Raises a <code class="literal">TypeError</code> exception if any argument is
of an invalid type.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-connected"></a>11.11 _mysql_connector.MySQL.connected() Method</h2></div></div></div><a class="indexterm" name="id5652"></a><a class="indexterm" name="id5654"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">is_connected = ccnx.connected()
</pre><p>
Returns <code class="literal">True</code> or <code class="literal">False</code> to
indicate whether the <code class="literal">MySQL</code> instance is
connected.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-consume-result"></a>11.12 _mysql_connector.MySQL.consume_result() Method</h2></div></div></div><a class="indexterm" name="id5664"></a><a class="indexterm" name="id5666"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.consume_result()
</pre><p>
Consumes the stored result set, if there is one, for this
<code class="literal">MySQL</code> instance, by fetching all rows. If the
statement that was executed returned multiple result sets, this
method loops over and consumes all of them.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-convert-to-mysql"></a>11.13 _mysql_connector.MySQL.convert_to_mysql() Method</h2></div></div></div><a class="indexterm" name="id5674"></a><a class="indexterm" name="id5676"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">converted_obj = ccnx.convert_to_mysql(<em class="replaceable"><code>obj</code></em>))
</pre><p>
Converts a Python object to a MySQL value based on the Python type
of the object. The converted object is escaped and quoted.
</p><pre data-lang="python" class="programlisting">ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
row = ccnx.fetch_row()
for col in row:
print(ccnx.convert_to_mysql(col))
ccnx.consume_result()
</pre><p>
Raises a <code class="literal">MySQLInterfaceError</code> exception if the
Python object cannot be converted.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-escape-string"></a>11.14 _mysql_connector.MySQL.escape_string() Method</h2></div></div></div><a class="indexterm" name="id5687"></a><a class="indexterm" name="id5689"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">str = ccnx.escape_string(<em class="replaceable"><code>str_to_escape</code></em>)
</pre><p>
Uses the <a class="ulink" href="https://dev.mysql.com/doc/c-api/8.0/en/mysql-escape-string.html" target="_top"><code class="literal">mysql_escape_string()</code></a> C
API function to create an SQL string that you can use in an SQL
statement.
</p><p>
Raises a <code class="literal">TypeError</code> exception if the value does
not have a <code class="literal">Unicode</code>, <code class="literal">bytes</code>,
or (for Python 2) <code class="literal">string</code> type. Raises a
<code class="literal">MySQLError</code> exception if the string could not be
escaped.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-fetch-fields"></a>11.15 _mysql_connector.MySQL.fetch_fields() Method</h2></div></div></div><a class="indexterm" name="id5705"></a><a class="indexterm" name="id5707"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">field_info = ccnx.fetch_fields()
</pre><p>
Fetches column information for the active result set. Returns a
list of tuples, one tuple per column
</p><p>
Raises a <code class="literal">MySQLInterfaceError</code> exception for any
MySQL error returned by the MySQL server.
</p><pre data-lang="python" class="programlisting">ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
field_info = ccnx.fetch_fields()
for fi in field_info:
print(fi)
ccnx.consume_result()
</pre></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-fetch-row"></a>11.16 _mysql_connector.MySQL.fetch_row() Method</h2></div></div></div><a class="indexterm" name="id5717"></a><a class="indexterm" name="id5719"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">row = ccnx.fetch_row()
</pre><p>
Fetches the next row from the active result set. The row is
returned as a tuple that contains the values converted to Python
objects, unless <code class="literal">raw</code> was set.
</p><pre data-lang="python" class="programlisting">ccnx.query('SELECT CURRENT_USER(), 1 + 3, NOW()')
row = ccnx.fetch_row()
print(row)
ccnx.free_result()
</pre><p>
Raises a <code class="literal">MySQLInterfaceError</code> exception for any
MySQL error returned by the MySQL server.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-field-count"></a>11.17 _mysql_connector.MySQL.field_count() Method</h2></div></div></div><a class="indexterm" name="id5730"></a><a class="indexterm" name="id5732"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">count = ccnx.field_count()
</pre><p>
Returns the number of columns in the active result set.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-free-result"></a>11.18 _mysql_connector.MySQL.free_result() Method</h2></div></div></div><a class="indexterm" name="id5739"></a><a class="indexterm" name="id5741"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.free_result()
</pre><p>
Frees the stored result set, if there is one, for this
<code class="literal">MySQL</code> instance. If the statement that was
executed returned multiple result sets, this method loops over and
consumes all of them.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-character-set-info"></a>11.19 _mysql_connector.MySQL.get_character_set_info() Method</h2></div></div></div><a class="indexterm" name="id5749"></a><a class="indexterm" name="id5751"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_character_set_info()
</pre><p>
Returns information about the default character set for the
current MySQL session. The returned dictionary has the keys
<code class="literal">number</code>, <code class="literal">name</code>,
<code class="literal">csname</code>, <code class="literal">comment</code>,
<code class="literal">dir</code>, <code class="literal">mbminlen</code>, and
<code class="literal">mbmaxlen</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-client-info"></a>11.20 _mysql_connector.MySQL.get_client_info() Method</h2></div></div></div><a class="indexterm" name="id5765"></a><a class="indexterm" name="id5767"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_client_info()
</pre><p>
Returns the MySQL client library version as a string.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-client-version"></a>11.21 _mysql_connector.MySQL.get_client_version() Method</h2></div></div></div><a class="indexterm" name="id5774"></a><a class="indexterm" name="id5776"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_client_version()
</pre><p>
Returns the MySQL client library version as a tuple.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-host-info"></a>11.22 _mysql_connector.MySQL.get_host_info() Method</h2></div></div></div><a class="indexterm" name="id5783"></a><a class="indexterm" name="id5785"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_host_info()
</pre><p>
Returns a description of the type of connection in use as a
string.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-proto-info"></a>11.23 _mysql_connector.MySQL.get_proto_info() Method</h2></div></div></div><a class="indexterm" name="id5792"></a><a class="indexterm" name="id5794"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_proto_info()
</pre><p>
Returns the protocol version used by the current session.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-server-info"></a>11.24 _mysql_connector.MySQL.get_server_info() Method</h2></div></div></div><a class="indexterm" name="id5801"></a><a class="indexterm" name="id5803"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_server_info()
</pre><p>
Returns the MySQL server version as a string.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-server-version"></a>11.25 _mysql_connector.MySQL.get_server_version() Method</h2></div></div></div><a class="indexterm" name="id5810"></a><a class="indexterm" name="id5812"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_server_version()
</pre><p>
Returns the MySQL server version as a tuple.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-get-ssl-cipher"></a>11.26 _mysql_connector.MySQL.get_ssl_cipher() Method</h2></div></div></div><a class="indexterm" name="id5819"></a><a class="indexterm" name="id5821"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.get_ssl_cipher()
</pre><p>
Returns the SSL cipher used for the current session, or
<code class="literal">None</code> if SSL is not in use.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-hex-string"></a>11.27 _mysql_connector.MySQL.hex_string() Method</h2></div></div></div><a class="indexterm" name="id5829"></a><a class="indexterm" name="id5831"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">str = ccnx.hex_string(<em class="replaceable"><code>string_to_hexify</code></em>)
</pre><p>
Encodes a value in hexadecimal format and wraps it within
<code class="literal">X''</code>. For example, <code class="literal">"ham"</code>
becomes <code class="literal">X'68616D'</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-insert-id"></a>11.28 _mysql_connector.MySQL.insert_id() Method</h2></div></div></div><a class="indexterm" name="id5842"></a><a class="indexterm" name="id5844"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">insert_id = ccnx.insert_id()
</pre><p>
Returns the <code class="literal">AUTO_INCREMENT</code> value generated by
the most recent executed statement, or 0 if there is no such
value.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-more-results"></a>11.29 _mysql_connector.MySQL.more_results() Method</h2></div></div></div><a class="indexterm" name="id5852"></a><a class="indexterm" name="id5854"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">more = ccnx.more_results()
</pre><p>
Returns <code class="literal">True</code> or <code class="literal">False</code> to
indicate whether any more result sets exist.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-next-result"></a>11.30 _mysql_connector.MySQL.next_result() Method</h2></div></div></div><a class="indexterm" name="id5863"></a><a class="indexterm" name="id5865"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.next_result()
</pre><p>
Initiates the next result set for a statement string that produced
multiple result sets.
</p><p>
Raises a <code class="literal">MySQLInterfaceError</code> exception for any
MySQL error returned by the MySQL server.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-num-fields"></a>11.31 _mysql_connector.MySQL.num_fields() Method</h2></div></div></div><a class="indexterm" name="id5874"></a><a class="indexterm" name="id5876"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">count = ccnx.num_fields()
</pre><p>
Returns the number of columns in the active result set.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-num-rows"></a>11.32 _mysql_connector.MySQL.num_rows() Method</h2></div></div></div><a class="indexterm" name="id5883"></a><a class="indexterm" name="id5885"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">count = ccnx.num_rows()
</pre><p>
Returns the number of rows in the active result set.
</p><p>
Raises a <code class="literal">MySQLError</code> exception if there is no
result set.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-ping"></a>11.33 _mysql_connector.MySQL.ping() Method</h2></div></div></div><a class="indexterm" name="id5894"></a><a class="indexterm" name="id5896"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">alive = ccnx.ping()
</pre><p>
Returns <code class="literal">True</code> or <code class="literal">False</code> to
indicate whether the connection to the MySQL server is working.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-query"></a>11.34 _mysql_connector.MySQL.query() Method</h2></div></div></div><a class="indexterm" name="id5905"></a><a class="indexterm" name="id5907"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.query(<em class="replaceable"><code>args</code></em>)
</pre><p>
Executes an SQL statement. The permitted arguments are
<code class="literal">statement</code>, <code class="literal">buffered</code>,
<code class="literal">raw</code>, and <code class="literal">raw_as_string</code>.
</p><pre data-lang="python" class="programlisting">ccnx.query('DROP TABLE IF EXISTS t')
ccnx.query('CREATE TABLE t (i INT NOT NULL AUTO_INCREMENT PRIMARY KEY)')
ccnx.query('INSERT INTO t (i) VALUES (NULL),(NULL),(NULL)')
ccnx.query('SELECT LAST_INSERT_ID()')
row = ccnx.fetch_row()
print('LAST_INSERT_ID(): ', row)
ccnx.consume_result()
</pre><p>
<code class="literal">buffered</code> and <code class="literal">raw</code>, if not
provided, take their values from the <code class="literal">MySQL</code>
instance. <code class="literal">raw_as_string</code> is a special argument
for Python v2 and returns <code class="literal">str</code> instead of
<code class="literal">bytearray</code> (compatible with Connector/Python
v1.x).
</p><p>
To check whether the query returns rows, check the
<code class="literal">have_result_set</code> property of the
<code class="literal">MySQL</code> instance.
</p><p>
<code class="literal">query()</code> returns <code class="literal">True</code> if the
query executes, and raises an exception otherwise. It raises a
<code class="literal">TypeError</code> exception if any argument has an
invalid type, and a <code class="literal">MySQLInterfaceError</code>
exception for any MySQL error returned by the MySQL server.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-raw"></a>11.35 _mysql_connector.MySQL.raw() Method</h2></div></div></div><a class="indexterm" name="id5935"></a><a class="indexterm" name="id5937"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">is_raw = ccnx.raw() # getter
ccnx.raw(<em class="replaceable"><code>bool</code></em>) # setter
</pre><p>
With no argument, returns <code class="literal">True</code> or
<code class="literal">False</code> to indicate whether the
<code class="literal">MySQL</code> instance return the rows as is (without
conversion to Python objects).
</p><p>
With a boolean argument, sets the <code class="literal">MySQL</code>
instance raw mode.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-refresh"></a>11.36 _mysql_connector.MySQL.refresh() Method</h2></div></div></div><a class="indexterm" name="id5950"></a><a class="indexterm" name="id5952"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.refresh(<em class="replaceable"><code>flags</code></em>)
</pre><p>
Flushes or resets the tables and caches indicated by the argument.
The only argument currently permitted is an integer.
</p><p>
Raises a <code class="literal">TypeError</code> exception if the first
argument is not an integer.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-reset-connection"></a>11.37 _mysql_connector.MySQL.reset_connection() Method</h2></div></div></div><a class="indexterm" name="id5962"></a><a class="indexterm" name="id5964"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.reset_connection()
</pre><p>
Resets the user variables and session variables for a connection
session.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-rollback"></a>11.38 _mysql_connector.MySQL.rollback() Method</h2></div></div></div><a class="indexterm" name="id5971"></a><a class="indexterm" name="id5973"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.rollback()
</pre><p>
Rolls back the current transaction.
</p><p>
Raises a <code class="literal">MySQLInterfaceError</code> exception on
errors.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-select-db"></a>11.39 _mysql_connector.MySQL.select_db() Method</h2></div></div></div><a class="indexterm" name="id5982"></a><a class="indexterm" name="id5984"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.select_db(<em class="replaceable"><code>db_name</code></em>)
</pre><p>
Sets the default (current) database for the current session.
</p><p>
Raises a <code class="literal">MySQLInterfaceError</code> exception for any
MySQL error returned by the MySQL server.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-set-character-set"></a>11.40 _mysql_connector.MySQL.set_character_set() Method</h2></div></div></div><a class="indexterm" name="id5994"></a><a class="indexterm" name="id5996"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.set_character_set(<em class="replaceable"><code>charset_name</code></em>)
</pre><p>
Sets the default character set for the current session. The only
argument permitted is a string that contains the character set
name.
</p><p>
Raises a <code class="literal">TypeError</code> exception if the argument is
not a <code class="literal">PyString_type</code>.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-shutdown"></a>11.41 _mysql_connector.MySQL.shutdown() Method</h2></div></div></div><a class="indexterm" name="id6007"></a><a class="indexterm" name="id6009"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">ccnx.shutdown(<em class="replaceable"><code>flags</code></em>)
</pre><p>
Shuts down the MySQL server. The only argument currently permitted
is an integer that describes the shutdown type.
</p><p>
Raises a <code class="literal">TypeError</code> exception if the first
argument is not an integer. Raises a
<code class="literal">MySQLErrorInterface</code> exception if an error is
retured by the MySQL server.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-stat"></a>11.42 _mysql_connector.MySQL.stat() Method</h2></div></div></div><a class="indexterm" name="id6020"></a><a class="indexterm" name="id6022"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">info = ccnx.stat()
</pre><p>
Returns the server status as a string.
</p><p>
Raises a <code class="literal">MySQLErrorInterface</code> exception if an
error is retured by the MySQL server.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-thread-id"></a>11.43 _mysql_connector.MySQL.thread_id() Method</h2></div></div></div><a class="indexterm" name="id6031"></a><a class="indexterm" name="id6033"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">thread_id = ccnx.thread_id()
</pre><p>
Returns the current thread or connection ID.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-use-unicode"></a>11.44 _mysql_connector.MySQL.use_unicode() Method</h2></div></div></div><a class="indexterm" name="id6040"></a><a class="indexterm" name="id6042"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">is_unicode = ccnx.use_unicode() # getter
ccnx.use_unicode(<em class="replaceable"><code>bool</code></em>) # setter
</pre><p>
With no argument, returns <code class="literal">True</code> or
<code class="literal">False</code> to indicate whether the
<code class="literal">MySQL</code> instance returns nonbinary strings as
Unicode.
</p><p>
With a boolean argument, sets whether the <code class="literal">MySQL</code>
instance returns nonbinary strings as Unicode.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-warning-count"></a>11.45 _mysql_connector.MySQL.warning_count() Method</h2></div></div></div><a class="indexterm" name="id6055"></a><a class="indexterm" name="id6057"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">count = ccnx.warning_count()
</pre><p>
Returns the number of errors, warnings, and notes produced by the
previous SQL statement.
</p></div><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="connector-python-api-cext-have-result-set"></a>11.46 _mysql_connector.MySQL.have_result_set Property</h2></div></div></div><a class="indexterm" name="id6064"></a><a class="indexterm" name="id6066"></a><p>
Syntax:
</p><pre data-lang="python" class="programlisting">has_rows = ccnx.have_result_set
</pre><p>
After execution of the <code class="literal">query()</code> method, this
property indicates whether the query returns rows.
</p></div></div><div class="index"><div class="titlepage"><div><div><h1 class="title"><a name="ix01"></a>Index</h1></div></div></div><div xmlns:xlink="http://www.w3.org/1999/xlink" class="index"><p><a href="#connector-python_index0_Symbols">Symbols</a>
| <a href="#connector-python_index0_C">C</a>
| <a href="#connector-python_index0_D">D</a>
| <a href="#connector-python_index0_E">E</a>
| <a href="#connector-python_index0_F">F</a>
| <a href="#connector-python_index0_M">M</a>
| <a href="#connector-python_index0_P">P</a>
| <a href="#connector-python_index0_S">S</a>
</p><div class="indexdiv"><h3><a name="connector-python_index0_Symbols"></a>Symbols</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id5489">_mysql_connector module, <a class="indexterm" href="#connector-python-api-cext-mysql-connector">_mysql_connector Module</a></dt><dt id="ientry-id5497">_mysql_connector.MySQL() class, <a class="indexterm" href="#connector-python-api-cext-mysql">_mysql_connector.MySQL() Class</a></dt><dt id="ientry-id5526">_mysql_connector.MySQL.affected_rows() method, <a class="indexterm" href="#connector-python-api-cext-affected-rows">_mysql_connector.MySQL.affected_rows() Method</a></dt><dt id="ientry-id5541">_mysql_connector.MySQL.autocommit() method, <a class="indexterm" href="#connector-python-api-cext-autocommit">_mysql_connector.MySQL.autocommit() Method</a></dt><dt id="ientry-id5556">_mysql_connector.MySQL.buffered() method, <a class="indexterm" href="#connector-python-api-cext-buffered">_mysql_connector.MySQL.buffered() Method</a></dt><dt id="ientry-id5575">_mysql_connector.MySQL.change_user() method, <a class="indexterm" href="#connector-python-api-cext-change-user">_mysql_connector.MySQL.change_user() Method</a></dt><dt id="ientry-id5590">_mysql_connector.MySQL.character_set_name() method, <a class="indexterm" href="#connector-python-api-cext-character-set-name">_mysql_connector.MySQL.character_set_name() Method</a></dt><dt id="ientry-id5602">_mysql_connector.MySQL.close() method, <a class="indexterm" href="#connector-python-api-cext-close">_mysql_connector.MySQL.close() Method</a></dt><dt id="ientry-id5611">_mysql_connector.MySQL.commit() method, <a class="indexterm" href="#connector-python-api-cext-commit">_mysql_connector.MySQL.commit() Method</a></dt><dt id="ientry-id5620">_mysql_connector.MySQL.connect() method, <a class="indexterm" href="#connector-python-api-cext-connect">_mysql_connector.MySQL.connect() Method</a></dt><dt id="ientry-id5652">_mysql_connector.MySQL.connected() method, <a class="indexterm" href="#connector-python-api-cext-connected">_mysql_connector.MySQL.connected() Method</a></dt><dt id="ientry-id5664">_mysql_connector.MySQL.consume_result() method, <a class="indexterm" href="#connector-python-api-cext-consume-result">_mysql_connector.MySQL.consume_result() Method</a></dt><dt id="ientry-id5674">_mysql_connector.MySQL.convert_to_mysql() method, <a class="indexterm" href="#connector-python-api-cext-convert-to-mysql">_mysql_connector.MySQL.convert_to_mysql() Method</a></dt><dt id="ientry-id5687">_mysql_connector.MySQL.escape_string() method, <a class="indexterm" href="#connector-python-api-cext-escape-string">_mysql_connector.MySQL.escape_string() Method</a></dt><dt id="ientry-id5705">_mysql_connector.MySQL.fetch_fields() method, <a class="indexterm" href="#connector-python-api-cext-fetch-fields">_mysql_connector.MySQL.fetch_fields() Method</a></dt><dt id="ientry-id5717">_mysql_connector.MySQL.fetch_row() method, <a class="indexterm" href="#connector-python-api-cext-fetch-row">_mysql_connector.MySQL.fetch_row() Method</a></dt><dt id="ientry-id5730">_mysql_connector.MySQL.field_count() method, <a class="indexterm" href="#connector-python-api-cext-field-count">_mysql_connector.MySQL.field_count() Method</a></dt><dt id="ientry-id5739">_mysql_connector.MySQL.free_result() method, <a class="indexterm" href="#connector-python-api-cext-free-result">_mysql_connector.MySQL.free_result() Method</a></dt><dt id="ientry-id5749">_mysql_connector.MySQL.get_character_set_info() method, <a class="indexterm" href="#connector-python-api-cext-get-character-set-info">_mysql_connector.MySQL.get_character_set_info() Method</a></dt><dt id="ientry-id5765">_mysql_connector.MySQL.get_client_info() method, <a class="indexterm" href="#connector-python-api-cext-get-client-info">_mysql_connector.MySQL.get_client_info() Method</a></dt><dt id="ientry-id5774">_mysql_connector.MySQL.get_client_version() method, <a class="indexterm" href="#connector-python-api-cext-get-client-version">_mysql_connector.MySQL.get_client_version() Method</a></dt><dt id="ientry-id5783">_mysql_connector.MySQL.get_host_info() method, <a class="indexterm" href="#connector-python-api-cext-get-host-info">_mysql_connector.MySQL.get_host_info() Method</a></dt><dt id="ientry-id5792">_mysql_connector.MySQL.get_proto_info() method, <a class="indexterm" href="#connector-python-api-cext-get-proto-info">_mysql_connector.MySQL.get_proto_info() Method</a></dt><dt id="ientry-id5801">_mysql_connector.MySQL.get_server_info() method, <a class="indexterm" href="#connector-python-api-cext-get-server-info">_mysql_connector.MySQL.get_server_info() Method</a></dt><dt id="ientry-id5810">_mysql_connector.MySQL.get_server_version() method, <a class="indexterm" href="#connector-python-api-cext-get-server-version">_mysql_connector.MySQL.get_server_version() Method</a></dt><dt id="ientry-id5819">_mysql_connector.MySQL.get_ssl_cipher() method, <a class="indexterm" href="#connector-python-api-cext-get-ssl-cipher">_mysql_connector.MySQL.get_ssl_cipher() Method</a></dt><dt id="ientry-id6064">_mysql_connector.MySQL.have_result_set property, <a class="indexterm" href="#connector-python-api-cext-have-result-set">_mysql_connector.MySQL.have_result_set Property</a></dt><dt id="ientry-id5829">_mysql_connector.MySQL.hex_string() method, <a class="indexterm" href="#connector-python-api-cext-hex-string">_mysql_connector.MySQL.hex_string() Method</a></dt><dt id="ientry-id5842">_mysql_connector.MySQL.insert_id() method, <a class="indexterm" href="#connector-python-api-cext-insert-id">_mysql_connector.MySQL.insert_id() Method</a></dt><dt id="ientry-id5852">_mysql_connector.MySQL.more_results() method, <a class="indexterm" href="#connector-python-api-cext-more-results">_mysql_connector.MySQL.more_results() Method</a></dt><dt id="ientry-id5863">_mysql_connector.MySQL.next_result() method, <a class="indexterm" href="#connector-python-api-cext-next-result">_mysql_connector.MySQL.next_result() Method</a></dt><dt id="ientry-id5874">_mysql_connector.MySQL.num_fields() method, <a class="indexterm" href="#connector-python-api-cext-num-fields">_mysql_connector.MySQL.num_fields() Method</a></dt><dt id="ientry-id5883">_mysql_connector.MySQL.num_rows() method, <a class="indexterm" href="#connector-python-api-cext-num-rows">_mysql_connector.MySQL.num_rows() Method</a></dt><dt id="ientry-id5894">_mysql_connector.MySQL.ping() method, <a class="indexterm" href="#connector-python-api-cext-ping">_mysql_connector.MySQL.ping() Method</a></dt><dt id="ientry-id5905">_mysql_connector.MySQL.query() method, <a class="indexterm" href="#connector-python-api-cext-query">_mysql_connector.MySQL.query() Method</a></dt><dt id="ientry-id5935">_mysql_connector.MySQL.raw() method, <a class="indexterm" href="#connector-python-api-cext-raw">_mysql_connector.MySQL.raw() Method</a></dt><dt id="ientry-id5950">_mysql_connector.MySQL.refresh() method, <a class="indexterm" href="#connector-python-api-cext-refresh">_mysql_connector.MySQL.refresh() Method</a></dt><dt id="ientry-id5962">_mysql_connector.MySQL.reset_connection() method, <a class="indexterm" href="#connector-python-api-cext-reset-connection">_mysql_connector.MySQL.reset_connection() Method</a></dt><dt id="ientry-id5971">_mysql_connector.MySQL.rollback() method, <a class="indexterm" href="#connector-python-api-cext-rollback">_mysql_connector.MySQL.rollback() Method</a></dt><dt id="ientry-id5982">_mysql_connector.MySQL.select_db() method, <a class="indexterm" href="#connector-python-api-cext-select-db">_mysql_connector.MySQL.select_db() Method</a></dt><dt id="ientry-id5994">_mysql_connector.MySQL.set_character_set() method, <a class="indexterm" href="#connector-python-api-cext-set-character-set">_mysql_connector.MySQL.set_character_set() Method</a></dt><dt id="ientry-id6007">_mysql_connector.MySQL.shutdown() method, <a class="indexterm" href="#connector-python-api-cext-shutdown">_mysql_connector.MySQL.shutdown() Method</a></dt><dt id="ientry-id6020">_mysql_connector.MySQL.stat() method, <a class="indexterm" href="#connector-python-api-cext-stat">_mysql_connector.MySQL.stat() Method</a></dt><dt id="ientry-id6031">_mysql_connector.MySQL.thread_id() method, <a class="indexterm" href="#connector-python-api-cext-thread-id">_mysql_connector.MySQL.thread_id() Method</a></dt><dt id="ientry-id6040">_mysql_connector.MySQL.use_unicode() method, <a class="indexterm" href="#connector-python-api-cext-use-unicode">_mysql_connector.MySQL.use_unicode() Method</a></dt><dt id="ientry-id6055">_mysql_connector.MySQL.warning_count() method, <a class="indexterm" href="#connector-python-api-cext-warning-count">_mysql_connector.MySQL.warning_count() Method</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_C"></a>C</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id3380">class</dt><dd><dl><dt>connection.MySQLConnection, <a class="indexterm" href="#connector-python-api-mysqlconnection">connection.MySQLConnection Class</a></dt><dt>constants.CharacterSet, <a class="indexterm" href="#connector-python-api-characterset">constants.CharacterSet Class</a></dt><dt>constants.ClientFlag, <a class="indexterm" href="#connector-python-api-clientflag">constants.ClientFlag Class</a></dt><dt>constants.FieldType, <a class="indexterm" href="#connector-python-api-fieldtype">constants.FieldType Class</a></dt><dt>constants.RefreshOption, <a class="indexterm" href="#connector-python-api-refreshoption">constants.RefreshOption Class</a></dt><dt>constants.SQLMode, <a class="indexterm" href="#connector-python-api-sqlmode">constants.SQLMode Class</a></dt><dt>cursor.MySQLCursor, <a class="indexterm" href="#connector-python-api-mysqlcursor">cursor.MySQLCursor Class</a></dt><dt>cursor.MySQLCursorBuffered, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffered">cursor.MySQLCursorBuffered Class</a></dt><dt>cursor.MySQLCursorBufferedDict, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffereddict">cursor.MySQLCursorBufferedDict Class</a></dt><dt>cursor.MySQLCursorDict, <a class="indexterm" href="#connector-python-api-mysqlcursordict">cursor.MySQLCursorDict Class</a></dt><dt>cursor.MySQLCursorPrepared, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt><dt>cursor.MySQLCursorRaw, <a class="indexterm" href="#connector-python-api-mysqlcursorraw">cursor.MySQLCursorRaw Class</a></dt><dt>pooling.MySQLConnectionPool, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool">pooling.MySQLConnectionPool Class</a></dt><dt>pooling.PooledMySQLConnection, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection">pooling.PooledMySQLConnection Class</a></dt><dt>_mysql_connector.MySQL(), <a class="indexterm" href="#connector-python-api-cext-mysql">_mysql_connector.MySQL() Class</a></dt></dl></dd><dt id="ientry-id5012">COM_STMT_SEND_LONG_DATA</dt><dd><dl><dt>prepared statements, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt></dl></dd><dt id="ientry-id3378">connection.MySQLConnection class, <a class="indexterm" href="#connector-python-api-mysqlconnection">connection.MySQLConnection Class</a></dt><dt id="ientry-id3386">connection.MySQLConnection() constructor, <a class="indexterm" href="#connector-python-api-mysqlconnection-constructor">connection.MySQLConnection() Constructor</a></dt><dt id="ientry-id1571">Connector/Python, <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt><dt id="ientry-id5059">constants.CharacterSet class, <a class="indexterm" href="#connector-python-api-characterset">constants.CharacterSet Class</a></dt><dt id="ientry-id5020">constants.ClientFlag class, <a class="indexterm" href="#connector-python-api-clientflag">constants.ClientFlag Class</a></dt><dt id="ientry-id5036">constants.FieldType class, <a class="indexterm" href="#connector-python-api-fieldtype">constants.FieldType Class</a></dt><dt id="ientry-id5069">constants.RefreshOption class, <a class="indexterm" href="#connector-python-api-refreshoption">constants.RefreshOption Class</a></dt><dt id="ientry-id5047">constants.SQLMode class, <a class="indexterm" href="#connector-python-api-sqlmode">constants.SQLMode Class</a></dt><dt id="ientry-id3388">constructor</dt><dd><dl><dt>connection.MySQLConnection(), <a class="indexterm" href="#connector-python-api-mysqlconnection-constructor">connection.MySQLConnection() Constructor</a></dt><dt>cursor.MySQLCursor, <a class="indexterm" href="#connector-python-api-mysqlcursor-constructor">cursor.MySQLCursor Constructor</a></dt><dt>pooling.MySQLConnectionPool, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-constructor">pooling.MySQLConnectionPool Constructor</a></dt><dt>pooling.PooledMySQLConnection, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-constructor">pooling.PooledMySQLConnection Constructor</a></dt></dl></dd><dt id="ientry-id4844">cursor.mysqlcursor</dt><dd><dl><dt>Subclasses, <a class="indexterm" href="#connector-python-api-cursor-subclasses">Subclasses cursor.MySQLCursor</a></dt></dl></dd><dt id="ientry-id4399">cursor.MySQLCursor class, <a class="indexterm" href="#connector-python-api-mysqlcursor">cursor.MySQLCursor Class</a></dt><dt id="ientry-id4441">cursor.MySQLCursor constructor, <a class="indexterm" href="#connector-python-api-mysqlcursor-constructor">cursor.MySQLCursor Constructor</a></dt><dt id="ientry-id4851">cursor.MySQLCursorBuffered class, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffered">cursor.MySQLCursorBuffered Class</a></dt><dt id="ientry-id4918">cursor.MySQLCursorBufferedDict class, <a class="indexterm" href="#connector-python-api-mysqlcursorbuffereddict">cursor.MySQLCursorBufferedDict Class</a></dt><dt id="ientry-id4899">cursor.MySQLCursorDict class, <a class="indexterm" href="#connector-python-api-mysqlcursordict">cursor.MySQLCursorDict Class</a></dt><dt id="ientry-id4936">cursor.MySQLCursorPrepared class, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt><dt id="ientry-id4879">cursor.MySQLCursorRaw class, <a class="indexterm" href="#connector-python-api-mysqlcursorraw">cursor.MySQLCursorRaw Class</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_D"></a>D</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id2948">DYLD_LIBRARY_PATH environment variable, <a class="indexterm" href="#connector-python-cext-development">Application Development with the Connector/Python C Extension</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_E"></a>E</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id2950">environment variable</dt><dd><dl><dt>DYLD_LIBRARY_PATH, <a class="indexterm" href="#connector-python-cext-development">Application Development with the Connector/Python C Extension</a></dt></dl></dd><dt id="ientry-id5295">errorcode module, <a class="indexterm" href="#connector-python-api-errorcode">errorcode Module</a></dt><dt id="ientry-id5453">errors.custom_error_exception() function, <a class="indexterm" href="#connector-python-api-errors-custom-error-exception">errors.custom_error_exception() Function</a></dt><dt id="ientry-id5357">errors.DatabaseError exception, <a class="indexterm" href="#connector-python-api-errors-databaseerror">errors.DatabaseError Exception</a></dt><dt id="ientry-id5345">errors.DataError exception, <a class="indexterm" href="#connector-python-api-errors-dataerror">errors.DataError Exception</a></dt><dt id="ientry-id5305">errors.Error exception, <a class="indexterm" href="#connector-python-api-errors-error">errors.Error Exception</a></dt><dt id="ientry-id5367">errors.IntegrityError exception, <a class="indexterm" href="#connector-python-api-errors-integrityerror">errors.IntegrityError Exception</a></dt><dt id="ientry-id5379">errors.InterfaceError exception, <a class="indexterm" href="#connector-python-api-errors-interfaceerror">errors.InterfaceError Exception</a></dt><dt id="ientry-id5389">errors.InternalError exception, <a class="indexterm" href="#connector-python-api-errors-internalerror">errors.InternalError Exception</a></dt><dt id="ientry-id5399">errors.NotSupportedError exception, <a class="indexterm" href="#connector-python-api-errors-notsupportederror">errors.NotSupportedError Exception</a></dt><dt id="ientry-id5409">errors.OperationalError exception, <a class="indexterm" href="#connector-python-api-errors-operationalerror">errors.OperationalError Exception</a></dt><dt id="ientry-id5419">errors.PoolError exception, <a class="indexterm" href="#connector-python-api-errors-poolerror">errors.PoolError Exception</a></dt><dt id="ientry-id5428">errors.ProgrammingError exception, <a class="indexterm" href="#connector-python-api-errors-programmingerror">errors.ProgrammingError Exception</a></dt><dt id="ientry-id5440">errors.Warning exception, <a class="indexterm" href="#connector-python-api-errors-warning">errors.Warning Exception</a></dt><dt id="ientry-id5307">exception</dt><dd><dl><dt>errors.DatabaseError, <a class="indexterm" href="#connector-python-api-errors-databaseerror">errors.DatabaseError Exception</a></dt><dt>errors.DataError, <a class="indexterm" href="#connector-python-api-errors-dataerror">errors.DataError Exception</a></dt><dt>errors.Error, <a class="indexterm" href="#connector-python-api-errors-error">errors.Error Exception</a></dt><dt>errors.IntegrityError, <a class="indexterm" href="#connector-python-api-errors-integrityerror">errors.IntegrityError Exception</a></dt><dt>errors.InterfaceError, <a class="indexterm" href="#connector-python-api-errors-interfaceerror">errors.InterfaceError Exception</a></dt><dt>errors.InternalError, <a class="indexterm" href="#connector-python-api-errors-internalerror">errors.InternalError Exception</a></dt><dt>errors.NotSupportedError, <a class="indexterm" href="#connector-python-api-errors-notsupportederror">errors.NotSupportedError Exception</a></dt><dt>errors.OperationalError, <a class="indexterm" href="#connector-python-api-errors-operationalerror">errors.OperationalError Exception</a></dt><dt>errors.PoolError, <a class="indexterm" href="#connector-python-api-errors-poolerror">errors.PoolError Exception</a></dt><dt>errors.ProgrammingError, <a class="indexterm" href="#connector-python-api-errors-programmingerror">errors.ProgrammingError Exception</a></dt><dt>errors.Warning, <a class="indexterm" href="#connector-python-api-errors-warning">errors.Warning Exception</a></dt></dl></dd></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_F"></a>F</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id5455">function</dt><dd><dl><dt>errors.custom_error_exception(), <a class="indexterm" href="#connector-python-api-errors-custom-error-exception">errors.custom_error_exception() Function</a></dt></dl></dd></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_M"></a>M</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id3326">method</dt><dd><dl><dt>mysql.connector.connect(), <a class="indexterm" href="#connector-python-api-mysql-connector-connect">mysql.connector.connect() Method</a></dt><dt>MySQLConnection.close(), <a class="indexterm" href="#connector-python-api-mysqlconnection-close">MySQLConnection.close() Method</a></dt><dt>MySQLConnection.cmd_change_user(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-change-user">MySQLConnection.cmd_change_user() Method</a></dt><dt>MySQLConnection.cmd_debug(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-debug">MySQLConnection.cmd_debug() Method</a></dt><dt>MySQLConnection.cmd_init_db(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-init-db">MySQLConnection.cmd_init_db() Method</a></dt><dt>MySQLConnection.cmd_ping(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-ping">MySQLConnection.cmd_ping() Method</a></dt><dt>MySQLConnection.cmd_process_info(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-info">MySQLConnection.cmd_process_info() Method</a></dt><dt>MySQLConnection.cmd_process_kill(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-kill">MySQLConnection.cmd_process_kill() Method</a></dt><dt>MySQLConnection.cmd_query(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query">MySQLConnection.cmd_query() Method</a></dt><dt>MySQLConnection.cmd_query_iter(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query-iter">MySQLConnection.cmd_query_iter() Method</a></dt><dt>MySQLConnection.cmd_quit(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-quit">MySQLConnection.cmd_quit() Method</a></dt><dt>MySQLConnection.cmd_refresh(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-refresh">MySQLConnection.cmd_refresh() Method</a></dt><dt>MySQLConnection.cmd_reset_connection(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-reset-connection">MySQLConnection.cmd_reset_connection() Method</a></dt><dt>MySQLConnection.cmd_shutdown(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-shutdown">MySQLConnection.cmd_shutdown() Method</a></dt><dt>MySQLConnection.cmd_statistics(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-statistics">MySQLConnection.cmd_statistics() Method</a></dt><dt>MySQLConnection.commit(), <a class="indexterm" href="#connector-python-api-mysqlconnection-commit">MySQLConnection.commit() Method</a></dt><dt>MySQLConnection.config(), <a class="indexterm" href="#connector-python-api-mysqlconnection-config">MySQLConnection.config() Method</a></dt><dt>MySQLConnection.connect(), <a class="indexterm" href="#connector-python-api-mysqlconnection-connect">MySQLConnection.connect() Method</a></dt><dt>MySQLConnection.cursor(), <a class="indexterm" href="#connector-python-api-mysqlconnection-cursor">MySQLConnection.cursor() Method</a></dt><dt>MySQLConnection.disconnect(), <a class="indexterm" href="#connector-python-api-mysqlconnection-disconnect">MySQLConnection.disconnect() Method</a></dt><dt>MySQLConnection.get_row(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-row">MySQLConnection.get_row() Method</a></dt><dt>MySQLConnection.get_rows(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-rows">MySQLConnection.get_rows() Method</a></dt><dt>MySQLConnection.get_server_info(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-info">MySQLConnection.get_server_info() Method</a></dt><dt>MySQLConnection.get_server_version(), <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-version">MySQLConnection.get_server_version() Method</a></dt><dt>MySQLConnection.isset_client_flag(), <a class="indexterm" href="#connector-python-api-mysqlconnection-isset-client-flag">MySQLConnection.isset_client_flag() Method</a></dt><dt>MySQLConnection.is_connected(), <a class="indexterm" href="#connector-python-api-mysqlconnection-is-connected">MySQLConnection.is_connected() Method</a></dt><dt>MySQLConnection.ping(), <a class="indexterm" href="#connector-python-api-mysqlconnection-ping">MySQLConnection.ping() Method</a></dt><dt>MySQLConnection.reconnect(), <a class="indexterm" href="#connector-python-api-mysqlconnection-reconnect">MySQLConnection.reconnect() Method</a></dt><dt>MySQLConnection.reset_session(), <a class="indexterm" href="#connector-python-api-mysqlconnection-reset-session">MySQLConnection.reset_session() Method</a></dt><dt>MySQLConnection.rollback(), <a class="indexterm" href="#connector-python-api-mysqlconnection-rollback">MySQLConnection.rollback() Method</a></dt><dt>MySQLConnection.set_charset_collation(), <a class="indexterm" href="#connector-python-api-mysqlconnection-set-charset-collation">MySQLConnection.set_charset_collation() Method</a></dt><dt>MySQLConnection.set_client_flags(), <a class="indexterm" href="#connector-python-api-mysqlconnection-set-client-flags">MySQLConnection.set_client_flags() Method</a></dt><dt>MySQLConnection.shutdown(), <a class="indexterm" href="#connector-python-api-mysqlconnection-shutdown">MySQLConnection.shutdown() Method</a></dt><dt>MySQLConnection.start_transaction(), <a class="indexterm" href="#connector-python-api-mysqlconnection-start-transaction">MySQLConnection.start_transaction() Method</a></dt><dt>MySQLConnectionPool.add_connection(), <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-add-connection">MySQLConnectionPool.add_connection() Method</a></dt><dt>MySQLConnectionPool.get_connection(), <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-get-connection">MySQLConnectionPool.get_connection() Method</a></dt><dt>MySQLConnectionPool.set_config(), <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-set-config">MySQLConnectionPool.set_config() Method</a></dt><dt>MySQLCursor.add_attribute(), <a class="indexterm" href="#connector-python-api-mysqlcursor-add-attribute">MySQLCursor.add_attribute() Method</a></dt><dt>MySQLCursor.callproc(), <a class="indexterm" href="#connector-python-api-mysqlcursor-callproc">MySQLCursor.callproc() Method</a></dt><dt>MySQLCursor.clear_attributes(), <a class="indexterm" href="#connector-python-api-mysqlcursor-clear-attributes">MySQLCursor.clear_attributes() Method</a></dt><dt>MySQLCursor.close(), <a class="indexterm" href="#connector-python-api-mysqlcursor-close">MySQLCursor.close() Method</a></dt><dt>MySQLCursor.execute(), <a class="indexterm" href="#connector-python-api-mysqlcursor-execute">MySQLCursor.execute() Method</a></dt><dt>MySQLCursor.executemany(), <a class="indexterm" href="#connector-python-api-mysqlcursor-executemany">MySQLCursor.executemany() Method</a></dt><dt>MySQLCursor.fetchall(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchall">MySQLCursor.fetchall() Method</a></dt><dt>MySQLCursor.fetchmany(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchmany">MySQLCursor.fetchmany() Method</a></dt><dt>MySQLCursor.fetchone(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchone">MySQLCursor.fetchone() Method</a></dt><dt>MySQLCursor.fetchsets(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchsets">MySQLCursor.fetchsets() Method</a></dt><dt>MySQLCursor.fetchwarnings(), <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchwarnings">MySQLCursor.fetchwarnings() Method</a></dt><dt>MySQLCursor.get_attributes(), <a class="indexterm" href="#connector-python-api-mysqlcursor-get-attributes">MySQLCursor.get_attributes() Method</a></dt><dt>MySQLCursor.nextset(), <a class="indexterm" href="#connector-python-api-mysqlcursor-nextset">MySQLCursor.nextset() Method</a></dt><dt>MySQLCursor.stored_results(), <a class="indexterm" href="#connector-python-api-mysqlcursor-stored-results">MySQLCursor.stored_results() Method</a></dt><dt>PooledMySQLConnection.close(), <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-close">PooledMySQLConnection.close() Method</a></dt><dt>PooledMySQLConnection.config(), <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-config">PooledMySQLConnection.config() Method</a></dt><dt>_mysql_connector.MySQL.affected_rows(), <a class="indexterm" href="#connector-python-api-cext-affected-rows">_mysql_connector.MySQL.affected_rows() Method</a></dt><dt>_mysql_connector.MySQL.autocommit(), <a class="indexterm" href="#connector-python-api-cext-autocommit">_mysql_connector.MySQL.autocommit() Method</a></dt><dt>_mysql_connector.MySQL.buffered(), <a class="indexterm" href="#connector-python-api-cext-buffered">_mysql_connector.MySQL.buffered() Method</a></dt><dt>_mysql_connector.MySQL.change_user(), <a class="indexterm" href="#connector-python-api-cext-change-user">_mysql_connector.MySQL.change_user() Method</a></dt><dt>_mysql_connector.MySQL.character_set_name(), <a class="indexterm" href="#connector-python-api-cext-character-set-name">_mysql_connector.MySQL.character_set_name() Method</a></dt><dt>_mysql_connector.MySQL.close(), <a class="indexterm" href="#connector-python-api-cext-close">_mysql_connector.MySQL.close() Method</a></dt><dt>_mysql_connector.MySQL.commit(), <a class="indexterm" href="#connector-python-api-cext-commit">_mysql_connector.MySQL.commit() Method</a></dt><dt>_mysql_connector.MySQL.connect(), <a class="indexterm" href="#connector-python-api-cext-connect">_mysql_connector.MySQL.connect() Method</a></dt><dt>_mysql_connector.MySQL.connected(), <a class="indexterm" href="#connector-python-api-cext-connected">_mysql_connector.MySQL.connected() Method</a></dt><dt>_mysql_connector.MySQL.consume_result(), <a class="indexterm" href="#connector-python-api-cext-consume-result">_mysql_connector.MySQL.consume_result() Method</a></dt><dt>_mysql_connector.MySQL.convert_to_mysql(), <a class="indexterm" href="#connector-python-api-cext-convert-to-mysql">_mysql_connector.MySQL.convert_to_mysql() Method</a></dt><dt>_mysql_connector.MySQL.escape_string(), <a class="indexterm" href="#connector-python-api-cext-escape-string">_mysql_connector.MySQL.escape_string() Method</a></dt><dt>_mysql_connector.MySQL.fetch_fields(), <a class="indexterm" href="#connector-python-api-cext-fetch-fields">_mysql_connector.MySQL.fetch_fields() Method</a></dt><dt>_mysql_connector.MySQL.fetch_row(), <a class="indexterm" href="#connector-python-api-cext-fetch-row">_mysql_connector.MySQL.fetch_row() Method</a></dt><dt>_mysql_connector.MySQL.field_count(), <a class="indexterm" href="#connector-python-api-cext-field-count">_mysql_connector.MySQL.field_count() Method</a></dt><dt>_mysql_connector.MySQL.free_result(), <a class="indexterm" href="#connector-python-api-cext-free-result">_mysql_connector.MySQL.free_result() Method</a></dt><dt>_mysql_connector.MySQL.get_character_set_info(), <a class="indexterm" href="#connector-python-api-cext-get-character-set-info">_mysql_connector.MySQL.get_character_set_info() Method</a></dt><dt>_mysql_connector.MySQL.get_client_info(), <a class="indexterm" href="#connector-python-api-cext-get-client-info">_mysql_connector.MySQL.get_client_info() Method</a></dt><dt>_mysql_connector.MySQL.get_client_version(), <a class="indexterm" href="#connector-python-api-cext-get-client-version">_mysql_connector.MySQL.get_client_version() Method</a></dt><dt>_mysql_connector.MySQL.get_host_info(), <a class="indexterm" href="#connector-python-api-cext-get-host-info">_mysql_connector.MySQL.get_host_info() Method</a></dt><dt>_mysql_connector.MySQL.get_proto_info(), <a class="indexterm" href="#connector-python-api-cext-get-proto-info">_mysql_connector.MySQL.get_proto_info() Method</a></dt><dt>_mysql_connector.MySQL.get_server_info(), <a class="indexterm" href="#connector-python-api-cext-get-server-info">_mysql_connector.MySQL.get_server_info() Method</a></dt><dt>_mysql_connector.MySQL.get_server_version(), <a class="indexterm" href="#connector-python-api-cext-get-server-version">_mysql_connector.MySQL.get_server_version() Method</a></dt><dt>_mysql_connector.MySQL.get_ssl_cipher(), <a class="indexterm" href="#connector-python-api-cext-get-ssl-cipher">_mysql_connector.MySQL.get_ssl_cipher() Method</a></dt><dt>_mysql_connector.MySQL.hex_string(), <a class="indexterm" href="#connector-python-api-cext-hex-string">_mysql_connector.MySQL.hex_string() Method</a></dt><dt>_mysql_connector.MySQL.insert_id(), <a class="indexterm" href="#connector-python-api-cext-insert-id">_mysql_connector.MySQL.insert_id() Method</a></dt><dt>_mysql_connector.MySQL.more_results(), <a class="indexterm" href="#connector-python-api-cext-more-results">_mysql_connector.MySQL.more_results() Method</a></dt><dt>_mysql_connector.MySQL.next_result(), <a class="indexterm" href="#connector-python-api-cext-next-result">_mysql_connector.MySQL.next_result() Method</a></dt><dt>_mysql_connector.MySQL.num_fields(), <a class="indexterm" href="#connector-python-api-cext-num-fields">_mysql_connector.MySQL.num_fields() Method</a></dt><dt>_mysql_connector.MySQL.num_rows(), <a class="indexterm" href="#connector-python-api-cext-num-rows">_mysql_connector.MySQL.num_rows() Method</a></dt><dt>_mysql_connector.MySQL.ping(), <a class="indexterm" href="#connector-python-api-cext-ping">_mysql_connector.MySQL.ping() Method</a></dt><dt>_mysql_connector.MySQL.query(), <a class="indexterm" href="#connector-python-api-cext-query">_mysql_connector.MySQL.query() Method</a></dt><dt>_mysql_connector.MySQL.raw(), <a class="indexterm" href="#connector-python-api-cext-raw">_mysql_connector.MySQL.raw() Method</a></dt><dt>_mysql_connector.MySQL.refresh(), <a class="indexterm" href="#connector-python-api-cext-refresh">_mysql_connector.MySQL.refresh() Method</a></dt><dt>_mysql_connector.MySQL.reset_connection(), <a class="indexterm" href="#connector-python-api-cext-reset-connection">_mysql_connector.MySQL.reset_connection() Method</a></dt><dt>_mysql_connector.MySQL.rollback(), <a class="indexterm" href="#connector-python-api-cext-rollback">_mysql_connector.MySQL.rollback() Method</a></dt><dt>_mysql_connector.MySQL.select_db(), <a class="indexterm" href="#connector-python-api-cext-select-db">_mysql_connector.MySQL.select_db() Method</a></dt><dt>_mysql_connector.MySQL.set_character_set(), <a class="indexterm" href="#connector-python-api-cext-set-character-set">_mysql_connector.MySQL.set_character_set() Method</a></dt><dt>_mysql_connector.MySQL.shutdown(), <a class="indexterm" href="#connector-python-api-cext-shutdown">_mysql_connector.MySQL.shutdown() Method</a></dt><dt>_mysql_connector.MySQL.stat(), <a class="indexterm" href="#connector-python-api-cext-stat">_mysql_connector.MySQL.stat() Method</a></dt><dt>_mysql_connector.MySQL.thread_id(), <a class="indexterm" href="#connector-python-api-cext-thread-id">_mysql_connector.MySQL.thread_id() Method</a></dt><dt>_mysql_connector.MySQL.use_unicode(), <a class="indexterm" href="#connector-python-api-cext-use-unicode">_mysql_connector.MySQL.use_unicode() Method</a></dt><dt>_mysql_connector.MySQL.warning_count(), <a class="indexterm" href="#connector-python-api-cext-warning-count">_mysql_connector.MySQL.warning_count() Method</a></dt></dl></dd><dt id="ientry-id3318">module</dt><dd><dl><dt>errorcode, <a class="indexterm" href="#connector-python-api-errorcode">errorcode Module</a></dt><dt>mysql.connector, <a class="indexterm" href="#connector-python-api-mysql-connector">mysql.connector Module</a></dt><dt>_mysql_connector, <a class="indexterm" href="#connector-python-api-cext-mysql-connector">_mysql_connector Module</a></dt></dl></dd><dt id="ientry-id3316">mysql.connector module, <a class="indexterm" href="#connector-python-api-mysql-connector">mysql.connector Module</a></dt><dt id="ientry-id3338">mysql.connector.apilevel property, <a class="indexterm" href="#connector-python-api-mysql-connector-apilevel">mysql.connector.apilevel Property</a></dt><dt id="ientry-id3324">mysql.connector.connect() method, <a class="indexterm" href="#connector-python-api-mysql-connector-connect">mysql.connector.connect() Method</a></dt><dt id="ientry-id3346">mysql.connector.paramstyle property, <a class="indexterm" href="#connector-python-api-mysql-connector-paramstyle">mysql.connector.paramstyle Property</a></dt><dt id="ientry-id3354">mysql.connector.threadsafety property, <a class="indexterm" href="#connector-python-api-mysql-connector-threadsafety">mysql.connector.threadsafety Property</a></dt><dt id="ientry-id3370">mysql.connector.__version_info__ property, <a class="indexterm" href="#connector-python-api-mysql-connector-version-info">mysql.connector.__version_info__ Property</a></dt><dt id="ientry-id3362">mysql.connector.__version__ property, <a class="indexterm" href="#connector-python-api-mysql-connector-version">mysql.connector.__version__ Property</a></dt><dt id="ientry-id3977">MySQLConnection.autocommit property, <a class="indexterm" href="#connector-python-api-mysqlconnection-autocommit">MySQLConnection.autocommit Property</a></dt><dt id="ientry-id4005">MySQLConnection.can_consume_results property, <a class="indexterm" href="#connector-python-api-mysqlconnection-can-consume-results">MySQLConnection.can_consume_results Property</a></dt><dt id="ientry-id4015">MySQLConnection.charset property, <a class="indexterm" href="#connector-python-api-mysqlconnection-charset">MySQLConnection.charset Property</a></dt><dt id="ientry-id4022">MySQLConnection.client_flags property, <a class="indexterm" href="#connector-python-api-mysqlconnection-client-flags">MySQLConnection.client_flags Property</a></dt><dt id="ientry-id3398">MySQLConnection.close() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-close">MySQLConnection.close() Method</a></dt><dt id="ientry-id3532">MySQLConnection.cmd_change_user() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-change-user">MySQLConnection.cmd_change_user() Method</a></dt><dt id="ientry-id3546">MySQLConnection.cmd_debug() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-debug">MySQLConnection.cmd_debug() Method</a></dt><dt id="ientry-id3556">MySQLConnection.cmd_init_db() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-init-db">MySQLConnection.cmd_init_db() Method</a></dt><dt id="ientry-id3566">MySQLConnection.cmd_ping() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-ping">MySQLConnection.cmd_ping() Method</a></dt><dt id="ientry-id3577">MySQLConnection.cmd_process_info() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-info">MySQLConnection.cmd_process_info() Method</a></dt><dt id="ientry-id3589">MySQLConnection.cmd_process_kill() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-process-kill">MySQLConnection.cmd_process_kill() Method</a></dt><dt id="ientry-id3606">MySQLConnection.cmd_query() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query">MySQLConnection.cmd_query() Method</a></dt><dt id="ientry-id3623">MySQLConnection.cmd_query_iter() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-query-iter">MySQLConnection.cmd_query_iter() Method</a></dt><dt id="ientry-id3637">MySQLConnection.cmd_quit() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-quit">MySQLConnection.cmd_quit() Method</a></dt><dt id="ientry-id3645">MySQLConnection.cmd_refresh() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-refresh">MySQLConnection.cmd_refresh() Method</a></dt><dt id="ientry-id3665">MySQLConnection.cmd_reset_connection() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-reset-connection">MySQLConnection.cmd_reset_connection() Method</a></dt><dt id="ientry-id3680">MySQLConnection.cmd_shutdown() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-shutdown">MySQLConnection.cmd_shutdown() Method</a></dt><dt id="ientry-id3692">MySQLConnection.cmd_statistics() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cmd-statistics">MySQLConnection.cmd_statistics() Method</a></dt><dt id="ientry-id4040">MySQLConnection.collation property, <a class="indexterm" href="#connector-python-api-mysqlconnection-collation">MySQLConnection.collation Property</a></dt><dt id="ientry-id3413">MySQLConnection.commit() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-commit">MySQLConnection.commit() Method</a></dt><dt id="ientry-id3424">MySQLConnection.config() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-config">MySQLConnection.config() Method</a></dt><dt id="ientry-id3448">MySQLConnection.connect() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-connect">MySQLConnection.connect() Method</a></dt><dt id="ientry-id4047">MySQLConnection.connected property, <a class="indexterm" href="#connector-python-api-mysqlconnection-connected">MySQLConnection.connected Property</a></dt><dt id="ientry-id4060">MySQLConnection.connection_id property, <a class="indexterm" href="#connector-python-api-mysqlconnection-connection-id">MySQLConnection.connection_id Property</a></dt><dt id="ientry-id4068">MySQLConnection.converter-class property, <a class="indexterm" href="#connector-python-api-mysqlconnection-converter-class">MySQLConnection.converter-class Property</a></dt><dt id="ientry-id3468">MySQLConnection.cursor() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-cursor">MySQLConnection.cursor() Method</a></dt><dt id="ientry-id4076">MySQLConnection.database property, <a class="indexterm" href="#connector-python-api-mysqlconnection-database">MySQLConnection.database Property</a></dt><dt id="ientry-id3699">MySQLConnection.disconnect() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-disconnect">MySQLConnection.disconnect() Method</a></dt><dt id="ientry-id3713">MySQLConnection.get_row() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-row">MySQLConnection.get_row() Method</a></dt><dt id="ientry-id3734">MySQLConnection.get_rows() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-rows">MySQLConnection.get_rows() Method</a></dt><dt id="ientry-id3759">MySQLConnection.get_server_info() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-info">MySQLConnection.get_server_info() Method</a></dt><dt id="ientry-id3772">MySQLConnection.get_server_version() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-server-version">MySQLConnection.get_server_version() Method</a></dt><dt id="ientry-id4086">MySQLConnection.get_warnings property, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-warnings">MySQLConnection.get_warnings Property</a></dt><dt id="ientry-id4102">MySQLConnection.in_transaction property, <a class="indexterm" href="#connector-python-api-mysqlconnection-in-transaction">MySQLConnection.in_transaction Property</a></dt><dt id="ientry-id3801">MySQLConnection.isset_client_flag() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-isset-client-flag">MySQLConnection.isset_client_flag() Method</a></dt><dt id="ientry-id3784">MySQLConnection.is_connected() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-is-connected">MySQLConnection.is_connected() Method</a></dt><dt id="ientry-id3812">MySQLConnection.ping() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-ping">MySQLConnection.ping() Method</a></dt><dt id="ientry-id4121">MySQLConnection.raise_on_warnings property, <a class="indexterm" href="#connector-python-api-mysqlconnection-raise-on-warnings">MySQLConnection.raise_on_warnings Property</a></dt><dt id="ientry-id3832">MySQLConnection.reconnect() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-reconnect">MySQLConnection.reconnect() Method</a></dt><dt id="ientry-id3845">MySQLConnection.reset_session() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-reset-session">MySQLConnection.reset_session() Method</a></dt><dt id="ientry-id3862">MySQLConnection.rollback() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-rollback">MySQLConnection.rollback() Method</a></dt><dt id="ientry-id4142">MySQLConnection.server_host property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-host">MySQLConnection.server_host Property</a></dt><dt id="ientry-id4150">MySQLConnection.server_info property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-info">MySQLConnection.server_info Property</a></dt><dt id="ientry-id4159">MySQLConnection.server_port property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-port">MySQLConnection.server_port Property</a></dt><dt id="ientry-id4167">MySQLConnection.server_version property, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-version">MySQLConnection.server_version Property</a></dt><dt id="ientry-id3875">MySQLConnection.set_charset_collation() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-set-charset-collation">MySQLConnection.set_charset_collation() Method</a></dt><dt id="ientry-id3896">MySQLConnection.set_client_flags() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-set-client-flags">MySQLConnection.set_client_flags() Method</a></dt><dt id="ientry-id3918">MySQLConnection.shutdown() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-shutdown">MySQLConnection.shutdown() Method</a></dt><dt id="ientry-id4175">MySQLConnection.sql_mode property, <a class="indexterm" href="#connector-python-api-mysqlconnection-sql-mode">MySQLConnection.sql_mode Property</a></dt><dt id="ientry-id3932">MySQLConnection.start_transaction() method, <a class="indexterm" href="#connector-python-api-mysqlconnection-start-transaction">MySQLConnection.start_transaction() Method</a></dt><dt id="ientry-id4186">MySQLConnection.time_zone property, <a class="indexterm" href="#connector-python-api-mysqlconnection-time-zone">MySQLConnection.time_zone Property</a></dt><dt id="ientry-id4205">MySQLConnection.unix_socket property, <a class="indexterm" href="#connector-python-api-mysqlconnection-unix-socket">MySQLConnection.unix_socket Property</a></dt><dt id="ientry-id3995">MySQLConnection.unread_results property, <a class="indexterm" href="#connector-python-api-mysqlconnection-unread-results">MySQLConnection.unread_results Property</a></dt><dt id="ientry-id4213">MySQLConnection.user property, <a class="indexterm" href="#connector-python-api-mysqlconnection-user">MySQLConnection.user Property</a></dt><dt id="ientry-id4195">MySQLConnection.use_unicode property, <a class="indexterm" href="#connector-python-api-mysqlconnection-use-unicode">MySQLConnection.use_unicode Property</a></dt><dt id="ientry-id4261">MySQLConnectionPool.add_connection() method, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-add-connection">MySQLConnectionPool.add_connection() Method</a></dt><dt id="ientry-id4280">MySQLConnectionPool.get_connection() method, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-get-connection">MySQLConnectionPool.get_connection() Method</a></dt><dt id="ientry-id4309">MySQLConnectionPool.pool_name property, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-pool-name">MySQLConnectionPool.pool_name Property</a></dt><dt id="ientry-id4292">MySQLConnectionPool.set_config() method, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-set-config">MySQLConnectionPool.set_config() Method</a></dt><dt id="ientry-id4461">MySQLCursor.add_attribute() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-add-attribute">MySQLCursor.add_attribute() Method</a></dt><dt id="ientry-id4502">MySQLCursor.callproc() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-callproc">MySQLCursor.callproc() Method</a></dt><dt id="ientry-id4480">MySQLCursor.clear_attributes() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-clear-attributes">MySQLCursor.clear_attributes() Method</a></dt><dt id="ientry-id4529">MySQLCursor.close() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-close">MySQLCursor.close() Method</a></dt><dt id="ientry-id4709">MySQLCursor.column_names property, <a class="indexterm" href="#connector-python-api-mysqlcursor-column-names">MySQLCursor.column_names Property</a></dt><dt id="ientry-id4723">MySQLCursor.description property, <a class="indexterm" href="#connector-python-api-mysqlcursor-description">MySQLCursor.description Property</a></dt><dt id="ientry-id4539">MySQLCursor.execute() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-execute">MySQLCursor.execute() Method</a></dt><dt id="ientry-id4572">MySQLCursor.executemany() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-executemany">MySQLCursor.executemany() Method</a></dt><dt id="ientry-id4601">MySQLCursor.fetchall() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchall">MySQLCursor.fetchall() Method</a></dt><dt id="ientry-id4613">MySQLCursor.fetchmany() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchmany">MySQLCursor.fetchmany() Method</a></dt><dt id="ientry-id4625">MySQLCursor.fetchone() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchone">MySQLCursor.fetchone() Method</a></dt><dt id="ientry-id4659">MySQLCursor.fetchsets() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchsets">MySQLCursor.fetchsets() Method</a></dt><dt id="ientry-id4671">MySQLCursor.fetchwarnings() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-fetchwarnings">MySQLCursor.fetchwarnings() Method</a></dt><dt id="ientry-id4491">MySQLCursor.get_attributes() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-get-attributes">MySQLCursor.get_attributes() Method</a></dt><dt id="ientry-id4760">MySQLCursor.lastrowid property, <a class="indexterm" href="#connector-python-api-mysqlcursor-lastrowid">MySQLCursor.lastrowid Property</a></dt><dt id="ientry-id4645">MySQLCursor.nextset() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-nextset">MySQLCursor.nextset() Method</a></dt><dt id="ientry-id4786">MySQLCursor.rowcount property, <a class="indexterm" href="#connector-python-api-mysqlcursor-rowcount">MySQLCursor.rowcount Property</a></dt><dt id="ientry-id4808">MySQLCursor.statement property, <a class="indexterm" href="#connector-python-api-mysqlcursor-statement">MySQLCursor.statement Property</a></dt><dt id="ientry-id4693">MySQLCursor.stored_results() method, <a class="indexterm" href="#connector-python-api-mysqlcursor-stored-results">MySQLCursor.stored_results() Method</a></dt><dt id="ientry-id4742">MySQLCursor.warnings property, <a class="indexterm" href="#connector-python-api-mysqlcursor-warnings">MySQLCursor.warnings Property</a></dt><dt id="ientry-id4824">MySQLCursor.with_rows property, <a class="indexterm" href="#connector-python-api-mysqlcursor-with-rows">MySQLCursor.with_rows Property</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_P"></a>P</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id1569">PEP 249, <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt><dt id="ientry-id4367">PooledMySQLConnection.close() method, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-close">PooledMySQLConnection.close() Method</a></dt><dt id="ientry-id4379">PooledMySQLConnection.config() method, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-config">PooledMySQLConnection.config() Method</a></dt><dt id="ientry-id4388">PooledMySQLConnection.pool_name property, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-pool-name">PooledMySQLConnection.pool_name Property</a></dt><dt id="ientry-id4221">pooling.MySQLConnectionPool class, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool">pooling.MySQLConnectionPool Class</a></dt><dt id="ientry-id4228">pooling.MySQLConnectionPool constructor, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-constructor">pooling.MySQLConnectionPool Constructor</a></dt><dt id="ientry-id4320">pooling.PooledMySQLConnection class, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection">pooling.PooledMySQLConnection Class</a></dt><dt id="ientry-id4345">pooling.PooledMySQLConnection constructor, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-constructor">pooling.PooledMySQLConnection Constructor</a></dt><dt id="ientry-id4941">prepared statements, <a class="indexterm" href="#connector-python-api-mysqlcursorprepared">cursor.MySQLCursorPrepared Class</a></dt><dt id="ientry-id3340">property</dt><dd><dl><dt>mysql.connector.apilevel, <a class="indexterm" href="#connector-python-api-mysql-connector-apilevel">mysql.connector.apilevel Property</a></dt><dt>mysql.connector.paramstyle, <a class="indexterm" href="#connector-python-api-mysql-connector-paramstyle">mysql.connector.paramstyle Property</a></dt><dt>mysql.connector.threadsafety, <a class="indexterm" href="#connector-python-api-mysql-connector-threadsafety">mysql.connector.threadsafety Property</a></dt><dt>mysql.connector.__version_info__, <a class="indexterm" href="#connector-python-api-mysql-connector-version-info">mysql.connector.__version_info__ Property</a></dt><dt>mysql.connector.__version__, <a class="indexterm" href="#connector-python-api-mysql-connector-version">mysql.connector.__version__ Property</a></dt><dt>MySQLConnection.autocommit, <a class="indexterm" href="#connector-python-api-mysqlconnection-autocommit">MySQLConnection.autocommit Property</a></dt><dt>MySQLConnection.can_consume_results, <a class="indexterm" href="#connector-python-api-mysqlconnection-can-consume-results">MySQLConnection.can_consume_results Property</a></dt><dt>MySQLConnection.charset, <a class="indexterm" href="#connector-python-api-mysqlconnection-charset">MySQLConnection.charset Property</a></dt><dt>MySQLConnection.client_flags, <a class="indexterm" href="#connector-python-api-mysqlconnection-client-flags">MySQLConnection.client_flags Property</a></dt><dt>MySQLConnection.collation, <a class="indexterm" href="#connector-python-api-mysqlconnection-collation">MySQLConnection.collation Property</a></dt><dt>MySQLConnection.connected, <a class="indexterm" href="#connector-python-api-mysqlconnection-connected">MySQLConnection.connected Property</a></dt><dt>MySQLConnection.connection_id, <a class="indexterm" href="#connector-python-api-mysqlconnection-connection-id">MySQLConnection.connection_id Property</a></dt><dt>MySQLConnection.converter-class, <a class="indexterm" href="#connector-python-api-mysqlconnection-converter-class">MySQLConnection.converter-class Property</a></dt><dt>MySQLConnection.database, <a class="indexterm" href="#connector-python-api-mysqlconnection-database">MySQLConnection.database Property</a></dt><dt>MySQLConnection.get_warnings, <a class="indexterm" href="#connector-python-api-mysqlconnection-get-warnings">MySQLConnection.get_warnings Property</a></dt><dt>MySQLConnection.in_transaction, <a class="indexterm" href="#connector-python-api-mysqlconnection-in-transaction">MySQLConnection.in_transaction Property</a></dt><dt>MySQLConnection.raise_on_warnings, <a class="indexterm" href="#connector-python-api-mysqlconnection-raise-on-warnings">MySQLConnection.raise_on_warnings Property</a></dt><dt>MySQLConnection.server_host, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-host">MySQLConnection.server_host Property</a></dt><dt>MySQLConnection.server_info, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-info">MySQLConnection.server_info Property</a></dt><dt>MySQLConnection.server_port, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-port">MySQLConnection.server_port Property</a></dt><dt>MySQLConnection.server_version, <a class="indexterm" href="#connector-python-api-mysqlconnection-server-version">MySQLConnection.server_version Property</a></dt><dt>MySQLConnection.sql_mode, <a class="indexterm" href="#connector-python-api-mysqlconnection-sql-mode">MySQLConnection.sql_mode Property</a></dt><dt>MySQLConnection.time_zone, <a class="indexterm" href="#connector-python-api-mysqlconnection-time-zone">MySQLConnection.time_zone Property</a></dt><dt>MySQLConnection.unix_socket, <a class="indexterm" href="#connector-python-api-mysqlconnection-unix-socket">MySQLConnection.unix_socket Property</a></dt><dt>MySQLConnection.unread_results, <a class="indexterm" href="#connector-python-api-mysqlconnection-unread-results">MySQLConnection.unread_results Property</a></dt><dt>MySQLConnection.user, <a class="indexterm" href="#connector-python-api-mysqlconnection-user">MySQLConnection.user Property</a></dt><dt>MySQLConnection.use_unicode, <a class="indexterm" href="#connector-python-api-mysqlconnection-use-unicode">MySQLConnection.use_unicode Property</a></dt><dt>MySQLConnectionPool.pool_name, <a class="indexterm" href="#connector-python-api-mysqlconnectionpool-pool-name">MySQLConnectionPool.pool_name Property</a></dt><dt>MySQLCursor.column_names, <a class="indexterm" href="#connector-python-api-mysqlcursor-column-names">MySQLCursor.column_names Property</a></dt><dt>MySQLCursor.description, <a class="indexterm" href="#connector-python-api-mysqlcursor-description">MySQLCursor.description Property</a></dt><dt>MySQLCursor.lastrowid, <a class="indexterm" href="#connector-python-api-mysqlcursor-lastrowid">MySQLCursor.lastrowid Property</a></dt><dt>MySQLCursor.rowcount, <a class="indexterm" href="#connector-python-api-mysqlcursor-rowcount">MySQLCursor.rowcount Property</a></dt><dt>MySQLCursor.statement, <a class="indexterm" href="#connector-python-api-mysqlcursor-statement">MySQLCursor.statement Property</a></dt><dt>MySQLCursor.warnings, <a class="indexterm" href="#connector-python-api-mysqlcursor-warnings">MySQLCursor.warnings Property</a></dt><dt>MySQLCursor.with_rows, <a class="indexterm" href="#connector-python-api-mysqlcursor-with-rows">MySQLCursor.with_rows Property</a></dt><dt>PooledMySQLConnection.pool_name, <a class="indexterm" href="#connector-python-api-pooledmysqlconnection-pool-name">PooledMySQLConnection.pool_name Property</a></dt><dt>_mysql_connector.MySQL.have_result_set, <a class="indexterm" href="#connector-python-api-cext-have-result-set">_mysql_connector.MySQL.have_result_set Property</a></dt></dl></dd><dt id="ientry-id1573">Python, <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt><dt id="ientry-id1567">Python Database API Specification v2.0 (PEP 249), <a class="indexterm" href="#connector-python-introduction">Introduction to MySQL Connector/Python</a></dt></dl></div><div class="indexdiv"><h3><a name="connector-python_index0_S"></a>S</h3> [<a href="#ix01">index top</a>]<dl><dt id="ientry-id4842">Subclasses cursor.mysqlcursor, <a class="indexterm" href="#connector-python-api-cursor-subclasses">Subclasses cursor.MySQLCursor</a></dt></dl></div></div></div></div><div class="copyright-footer"></div></body></html>
|