StatementImpl.java 96.2 KB
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
/*
  Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.

  The MySQL Connector/J is licensed under the terms of the GPLv2
  <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
  There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
  this software, see the FOSS License Exception
  <http://www.mysql.com/about/legal/licensing/foss-exception.html>.

  This program is free software; you can redistribute it and/or modify it under the terms
  of the GNU General Public License as published by the Free Software Foundation; version 2
  of the License.

  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along with this
  program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
  Floor, Boston, MA 02110-1301  USA

 */

package com.mysql.jdbc;

import java.io.InputStream;
import java.math.BigInteger;
import java.sql.BatchUpdateException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

import com.mysql.jdbc.exceptions.MySQLStatementCancelledException;
import com.mysql.jdbc.exceptions.MySQLTimeoutException;
import com.mysql.jdbc.log.LogUtils;
import com.mysql.jdbc.profiler.ProfilerEvent;
import com.mysql.jdbc.profiler.ProfilerEventHandler;

/**
 * A Statement object is used for executing a static SQL statement and obtaining
 * the results produced by it.
 * 
 * Only one ResultSet per Statement can be open at any point in time. Therefore, if the reading of one ResultSet is interleaved with the reading of another,
 * each must have been generated by different Statements. All statement execute methods implicitly close a statement's current ResultSet if an open one exists.
 */
public class StatementImpl implements Statement {
    protected static final String PING_MARKER = "/* ping */";

    protected static final String[] ON_DUPLICATE_KEY_UPDATE_CLAUSE = new String[] { "ON", "DUPLICATE", "KEY", "UPDATE" };

    /**
     * Thread used to implement query timeouts...Eventually we could be more
     * efficient and have one thread with timers, but this is a straightforward
     * and simple way to implement a feature that isn't used all that often.
     */
    class CancelTask extends TimerTask {

        long connectionId = 0;
        SQLException caughtWhileCancelling = null;
        StatementImpl toCancel;
        Properties origConnProps = null;
        String origConnURL = "";

        CancelTask(StatementImpl cancellee) throws SQLException {
            this.connectionId = cancellee.connectionId;
            this.toCancel = cancellee;
            this.origConnProps = new Properties();

            Properties props = StatementImpl.this.connection.getProperties();

            Enumeration<?> keys = props.propertyNames();

            while (keys.hasMoreElements()) {
                String key = keys.nextElement().toString();
                this.origConnProps.setProperty(key, props.getProperty(key));
            }

            this.origConnURL = StatementImpl.this.connection.getURL();
        }

        @Override
        public void run() {

            Thread cancelThread = new Thread() {

                @Override
                public void run() {

                    Connection cancelConn = null;
                    java.sql.Statement cancelStmt = null;

                    try {
                        if (StatementImpl.this.connection.getQueryTimeoutKillsConnection()) {
                            CancelTask.this.toCancel.wasCancelled = true;
                            CancelTask.this.toCancel.wasCancelledByTimeout = true;
                            StatementImpl.this.connection.realClose(false, false, true,
                                    new MySQLStatementCancelledException(Messages.getString("Statement.ConnectionKilledDueToTimeout")));
                        } else {
                            synchronized (StatementImpl.this.cancelTimeoutMutex) {
                                if (CancelTask.this.origConnURL.equals(StatementImpl.this.connection.getURL())) {
                                    //All's fine
                                    cancelConn = StatementImpl.this.connection.duplicate();
                                    cancelStmt = cancelConn.createStatement();
                                    cancelStmt.execute("KILL QUERY " + CancelTask.this.connectionId);
                                } else {
                                    try {
                                        cancelConn = (Connection) DriverManager.getConnection(CancelTask.this.origConnURL, CancelTask.this.origConnProps);
                                        cancelStmt = cancelConn.createStatement();
                                        cancelStmt.execute("KILL QUERY " + CancelTask.this.connectionId);
                                    } catch (NullPointerException npe) {
                                        //Log this? "Failed to connect to " + origConnURL + " and KILL query"
                                    }
                                }
                                CancelTask.this.toCancel.wasCancelled = true;
                                CancelTask.this.toCancel.wasCancelledByTimeout = true;
                            }
                        }
                    } catch (SQLException sqlEx) {
                        CancelTask.this.caughtWhileCancelling = sqlEx;
                    } catch (NullPointerException npe) {
                        // Case when connection closed while starting to cancel
                        // We can't easily synchronize this, because then one thread can't cancel() a running query

                        // ignore, we shouldn't re-throw this, because the connection's already closed, so the statement has been timed out.
                    } finally {
                        if (cancelStmt != null) {
                            try {
                                cancelStmt.close();
                            } catch (SQLException sqlEx) {
                                throw new RuntimeException(sqlEx.toString());
                            }
                        }

                        if (cancelConn != null) {
                            try {
                                cancelConn.close();
                            } catch (SQLException sqlEx) {
                                throw new RuntimeException(sqlEx.toString());
                            }
                        }

                        CancelTask.this.toCancel = null;
                        CancelTask.this.origConnProps = null;
                        CancelTask.this.origConnURL = null;
                    }
                }
            };

            cancelThread.start();
        }
    }

    /**
     * Mutex to prevent race between returning query results and noticing
     * that we're timed-out or cancelled.
     */

    protected Object cancelTimeoutMutex = new Object();

    /** Used to generate IDs when profiling. */
    static int statementCounter = 1;

    public final static byte USES_VARIABLES_FALSE = 0;

    public final static byte USES_VARIABLES_TRUE = 1;

    public final static byte USES_VARIABLES_UNKNOWN = -1;

    protected boolean wasCancelled = false;
    protected boolean wasCancelledByTimeout = false;

    /** Holds batched commands */
    protected List<Object> batchedArgs;

    /** The character converter to use (if available) */
    protected SingleByteCharsetConverter charConverter = null;

    /** The character encoding to use (if available) */
    protected String charEncoding = null;

    /** The connection that created us */
    protected volatile MySQLConnection connection = null;

    protected long connectionId = 0;

    /** The catalog in use */
    protected String currentCatalog = null;

    /** Should we process escape codes? */
    protected boolean doEscapeProcessing = true;

    /** If we're profiling, where should events go to? */
    protected ProfilerEventHandler eventSink = null;

    /** The number of rows to fetch at a time (currently ignored) */
    private int fetchSize = 0;

    /** Has this statement been closed? */
    protected boolean isClosed = false;

    /** The auto_increment value for the last insert */
    protected long lastInsertId = -1;

    /** The max field size for this statement */
    protected int maxFieldSize = MysqlIO.getMaxBuf();

    /**
     * The maximum number of rows to return for this statement (-1 means _all_
     * rows)
     */
    protected int maxRows = -1;

    /** Set of currently-open ResultSets */
    protected Set<ResultSetInternalMethods> openResults = new HashSet<ResultSetInternalMethods>();

    /** Are we in pedantic mode? */
    protected boolean pedantic = false;

    /**
     * Where this statement was created, only used if profileSql or
     * useUsageAdvisor set to true.
     */
    protected String pointOfOrigin;

    /** Should we profile? */
    protected boolean profileSQL = false;

    /** The current results */
    protected ResultSetInternalMethods results = null;

    protected ResultSetInternalMethods generatedKeysResults = null;

    /** The concurrency for this result set (updatable or not) */
    protected int resultSetConcurrency = 0;

    /** The type of this result set (scroll sensitive or in-sensitive) */
    protected int resultSetType = 0;

    /** Used to identify this statement when profiling. */
    protected int statementId;

    /** The timeout for a query */
    protected int timeoutInMillis = 0;

    /** The update count for this statement */
    protected long updateCount = -1;

    /** Should we use the usage advisor? */
    protected boolean useUsageAdvisor = false;

    /** The warnings chain. */
    protected SQLWarning warningChain = null;

    /** Has clearWarnings() been called? */
    protected boolean clearWarningsCalled = false;

    /**
     * Should this statement hold results open over .close() irregardless of
     * connection's setting?
     */
    protected boolean holdResultsOpenOverClose = false;

    protected ArrayList<ResultSetRow> batchedGeneratedKeys = null;

    protected boolean retrieveGeneratedKeys = false;

    protected boolean continueBatchOnError = false;

    protected PingTarget pingTarget = null;

    protected boolean useLegacyDatetimeCode;

    protected boolean sendFractionalSeconds;

    private ExceptionInterceptor exceptionInterceptor;

    /** Whether or not the last query was of the form ON DUPLICATE KEY UPDATE */
    protected boolean lastQueryIsOnDupKeyUpdate = false;

    /** Are we currently executing a statement? */
    protected final AtomicBoolean statementExecuting = new AtomicBoolean(false);

    /** Are we currently closing results implicitly (internally)? */
    private boolean isImplicitlyClosingResults = false;

    /**
     * Constructor for a Statement.
     * 
     * @param c
     *            the Connection instantation that creates us
     * @param catalog
     *            the database name in use when we were created
     * 
     * @throws SQLException
     *             if an error occurs.
     */
    public StatementImpl(MySQLConnection c, String catalog) throws SQLException {
        if ((c == null) || c.isClosed()) {
            throw SQLError.createSQLException(Messages.getString("Statement.0"), SQLError.SQL_STATE_CONNECTION_NOT_OPEN, null);
        }

        this.connection = c;
        this.connectionId = this.connection.getId();
        this.exceptionInterceptor = this.connection.getExceptionInterceptor();

        this.currentCatalog = catalog;
        this.pedantic = this.connection.getPedantic();
        this.continueBatchOnError = this.connection.getContinueBatchOnError();
        this.useLegacyDatetimeCode = this.connection.getUseLegacyDatetimeCode();
        this.sendFractionalSeconds = this.connection.getSendFractionalSeconds();
        this.doEscapeProcessing = this.connection.getEnableEscapeProcessing();

        if (!this.connection.getDontTrackOpenResources()) {
            this.connection.registerStatement(this);
        }

        this.maxFieldSize = this.connection.getMaxAllowedPacket();

        int defaultFetchSize = this.connection.getDefaultFetchSize();
        if (defaultFetchSize != 0) {
            setFetchSize(defaultFetchSize);
        }

        if (this.connection.getUseUnicode()) {
            this.charEncoding = this.connection.getEncoding();
            this.charConverter = this.connection.getCharsetConverter(this.charEncoding);
        }

        boolean profiling = this.connection.getProfileSql() || this.connection.getUseUsageAdvisor() || this.connection.getLogSlowQueries();
        if (this.connection.getAutoGenerateTestcaseScript() || profiling) {
            this.statementId = statementCounter++;
        }
        if (profiling) {
            this.pointOfOrigin = LogUtils.findCallingClassAndMethod(new Throwable());
            this.profileSQL = this.connection.getProfileSql();
            this.useUsageAdvisor = this.connection.getUseUsageAdvisor();
            this.eventSink = ProfilerEventHandlerFactory.getInstance(this.connection);
        }

        int maxRowsConn = this.connection.getMaxRows();
        if (maxRowsConn != -1) {
            setMaxRows(maxRowsConn);
        }

        this.holdResultsOpenOverClose = this.connection.getHoldResultsOpenOverStatementClose();

        this.version5013OrNewer = this.connection.versionMeetsMinimum(5, 0, 13);
    }

    /**
     * @param sql
     * 
     * @throws SQLException
     */
    public void addBatch(String sql) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.batchedArgs == null) {
                this.batchedArgs = new ArrayList<Object>();
            }

            if (sql != null) {
                this.batchedArgs.add(sql);
            }
        }
    }

    /**
     * Get the batched args as added by the addBatch method(s).
     * The list is unmodifiable and might contain any combination of String,
     * BatchParams, or BatchedBindValues depending on how the parameters were
     * batched.
     * 
     * @return an unmodifiable List of batched args
     */
    public List<Object> getBatchedArgs() {
        return this.batchedArgs == null ? null : Collections.unmodifiableList(this.batchedArgs);
    }

    /**
     * Cancels this Statement object if both the DBMS and driver support
     * aborting an SQL statement. This method can be used by one thread to
     * cancel a statement that is being executed by another thread.
     */
    public void cancel() throws SQLException {
        if (!this.statementExecuting.get()) {
            return;
        }

        if (!this.isClosed && this.connection != null && this.connection.versionMeetsMinimum(5, 0, 0)) {
            Connection cancelConn = null;
            java.sql.Statement cancelStmt = null;

            try {
                cancelConn = this.connection.duplicate();
                cancelStmt = cancelConn.createStatement();
                cancelStmt.execute("KILL QUERY " + this.connection.getIO().getThreadId());
                this.wasCancelled = true;
            } finally {
                if (cancelStmt != null) {
                    cancelStmt.close();
                }

                if (cancelConn != null) {
                    cancelConn.close();
                }
            }

        }
    }

    // --------------------------JDBC 2.0-----------------------------

    /**
     * Checks if closed() has been called, and throws an exception if so
     * 
     * @throws SQLException
     *             if this statement has been closed
     */
    protected MySQLConnection checkClosed() throws SQLException {
        MySQLConnection c = this.connection;

        if (c == null) {
            throw SQLError.createSQLException(Messages.getString("Statement.49"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }

        return c;
    }

    /**
     * Checks if the given SQL query with the given first non-ws char is a DML
     * statement. Throws an exception if it is.
     * 
     * @param sql
     *            the SQL to check
     * @param firstStatementChar
     *            the UC first non-ws char of the statement
     * 
     * @throws SQLException
     *             if the statement contains DML
     */
    protected void checkForDml(String sql, char firstStatementChar) throws SQLException {
        if ((firstStatementChar == 'I') || (firstStatementChar == 'U') || (firstStatementChar == 'D') || (firstStatementChar == 'A')
                || (firstStatementChar == 'C') || (firstStatementChar == 'T') || (firstStatementChar == 'R')) {
            String noCommentSql = StringUtils.stripComments(sql, "'\"", "'\"", true, false, true, true);

            if (StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "INSERT") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "UPDATE")
                    || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DELETE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DROP")
                    || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "CREATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "ALTER")
                    || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "TRUNCATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "RENAME")) {
                throw SQLError.createSQLException(Messages.getString("Statement.57"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }
        }
    }

    /**
     * Method checkNullOrEmptyQuery.
     * 
     * @param sql
     *            the SQL to check
     * 
     * @throws SQLException
     *             if query is null or empty.
     */
    protected void checkNullOrEmptyQuery(String sql) throws SQLException {
        if (sql == null) {
            throw SQLError.createSQLException(Messages.getString("Statement.59"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }

        if (sql.length() == 0) {
            throw SQLError.createSQLException(Messages.getString("Statement.61"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }
    }

    /**
     * JDBC 2.0 Make the set of commands in the current batch empty. This method
     * is optional.
     * 
     * @exception SQLException
     *                if a database-access error occurs, or the driver does not
     *                support batch statements
     */
    public void clearBatch() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.batchedArgs != null) {
                this.batchedArgs.clear();
            }
        }
    }

    /**
     * After this call, getWarnings returns null until a new warning is reported
     * for this Statement.
     * 
     * @exception SQLException
     *                if a database access error occurs (why?)
     */
    public void clearWarnings() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            this.clearWarningsCalled = true;
            this.warningChain = null;
        }
    }

    /**
     * In many cases, it is desirable to immediately release a Statement's
     * database and JDBC resources instead of waiting for this to happen when it
     * is automatically closed. The close method provides this immediate
     * release.
     * 
     * <p>
     * <B>Note:</B> A Statement is automatically closed when it is garbage collected. When a Statement is closed, its current ResultSet, if one exists, is also
     * closed.
     * </p>
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public void close() throws SQLException {
        realClose(true, true);
    }

    /**
     * Close any open result sets that have been 'held open'
     */
    protected void closeAllOpenResults() throws SQLException {
        MySQLConnection locallyScopedConn = this.connection;

        if (locallyScopedConn == null) {
            return; // already closed
        }

        synchronized (locallyScopedConn.getConnectionMutex()) {
            if (this.openResults != null) {
                for (ResultSetInternalMethods element : this.openResults) {
                    try {
                        element.realClose(false);
                    } catch (SQLException sqlEx) {
                        AssertionFailedException.shouldNotHappen(sqlEx);
                    }
                }

                this.openResults.clear();
            }
        }
    }

    /**
     * Close all result sets in this statement. This includes multi-results
     */
    protected void implicitlyCloseAllOpenResults() throws SQLException {
        this.isImplicitlyClosingResults = true;
        try {
            if (!(this.connection.getHoldResultsOpenOverStatementClose() || this.connection.getDontTrackOpenResources() || this.holdResultsOpenOverClose)) {
                if (this.results != null) {
                    this.results.realClose(false);
                }
                if (this.generatedKeysResults != null) {
                    this.generatedKeysResults.realClose(false);
                }
                closeAllOpenResults();
            }
        } finally {
            this.isImplicitlyClosingResults = false;
        }
    }

    public void removeOpenResultSet(ResultSetInternalMethods rs) {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                if (this.openResults != null) {
                    this.openResults.remove(rs);
                }

                boolean hasMoreResults = rs.getNextResultSet() != null;

                // clear the current results or GGK results
                if (this.results == rs && !hasMoreResults) {
                    this.results = null;
                }
                if (this.generatedKeysResults == rs) {
                    this.generatedKeysResults = null;
                }

                // trigger closeOnCompletion if:
                // a) the result set removal wasn't triggered internally
                // b) there are no additional results
                if (!this.isImplicitlyClosingResults && !hasMoreResults) {
                    checkAndPerformCloseOnCompletionAction();
                }
            }
        } catch (SQLException e) {
            // we can't break the interface, having this be no-op in case of error is ok
        }
    }

    public int getOpenResultSetCount() {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                if (this.openResults != null) {
                    return this.openResults.size();
                }

                return 0;
            }
        } catch (SQLException e) {
            // we can't break the interface, having this be no-op in case of error is ok

            return 0;
        }
    }

    /**
     * Check if all ResultSets generated by this statement are closed. If so,
     * close this statement.
     */
    private void checkAndPerformCloseOnCompletionAction() {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                if (isCloseOnCompletion() && !this.connection.getDontTrackOpenResources() && getOpenResultSetCount() == 0
                        && (this.results == null || !this.results.reallyResult() || this.results.isClosed())
                        && (this.generatedKeysResults == null || !this.generatedKeysResults.reallyResult() || this.generatedKeysResults.isClosed())) {
                    realClose(false, false);
                }
            }
        } catch (SQLException e) {
        }
    }

    /**
     * @param sql
     */
    private ResultSetInternalMethods createResultSetUsingServerFetch(String sql) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            java.sql.PreparedStatement pStmt = this.connection.prepareStatement(sql, this.resultSetType, this.resultSetConcurrency);

            pStmt.setFetchSize(this.fetchSize);

            if (this.maxRows > -1) {
                pStmt.setMaxRows(this.maxRows);
            }

            statementBegins();

            pStmt.execute();

            //
            // Need to be able to get resultset irrespective if we issued DML or not to make this work.
            //
            ResultSetInternalMethods rs = ((StatementImpl) pStmt).getResultSetInternal();

            rs.setStatementUsedForFetchingRows((com.mysql.jdbc.PreparedStatement) pStmt);

            this.results = rs;

            return rs;
        }
    }

    /**
     * We only stream result sets when they are forward-only, read-only, and the
     * fetch size has been set to Integer.MIN_VALUE
     * 
     * @return true if this result set should be streamed row at-a-time, rather
     *         than read all at once.
     */
    protected boolean createStreamingResultSet() {
        return ((this.resultSetType == java.sql.ResultSet.TYPE_FORWARD_ONLY) && (this.resultSetConcurrency == java.sql.ResultSet.CONCUR_READ_ONLY)
                && (this.fetchSize == Integer.MIN_VALUE));
    }

    private int originalResultSetType = 0;
    private int originalFetchSize = 0;

    /*
     * (non-Javadoc)
     * 
     * @see com.mysql.jdbc.IStatement#enableStreamingResults()
     */
    public void enableStreamingResults() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            this.originalResultSetType = this.resultSetType;
            this.originalFetchSize = this.fetchSize;

            setFetchSize(Integer.MIN_VALUE);
            setResultSetType(ResultSet.TYPE_FORWARD_ONLY);
        }
    }

    public void disableStreamingResults() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.fetchSize == Integer.MIN_VALUE && this.resultSetType == ResultSet.TYPE_FORWARD_ONLY) {
                setFetchSize(this.originalFetchSize);
                setResultSetType(this.originalResultSetType);
            }
        }
    }

    /**
     * Adjust net_write_timeout to a higher value if we're streaming result sets. More often than not, someone runs into
     * an issue where they blow net_write_timeout when using this feature, and if they're willing to hold a result set open
     * for 30 seconds or more, one more round-trip isn't going to hurt.
     *
     * This is reset by RowDataDynamic.close().
     */
    protected void setupStreamingTimeout(MySQLConnection con) throws SQLException {
        if (createStreamingResultSet() && con.getNetTimeoutForStreamingResults() > 0) {
            executeSimpleNonQuery(con, "SET net_write_timeout=" + con.getNetTimeoutForStreamingResults());
        }
    }

    /**
     * Execute a SQL statement that may return multiple results. We don't have
     * to worry about this since we do not support multiple ResultSets. You can
     * use getResultSet or getUpdateCount to retrieve the result.
     * 
     * @param sql
     *            any SQL statement
     * 
     * @return true if the next result is a ResulSet, false if it is an update
     *         count or there are no more results
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public boolean execute(String sql) throws SQLException {
        return executeInternal(sql, false);
    }

    private boolean executeInternal(String sql, boolean returnGeneratedKeys) throws SQLException {
        MySQLConnection locallyScopedConn = checkClosed();

        synchronized (locallyScopedConn.getConnectionMutex()) {
            checkClosed();

            checkNullOrEmptyQuery(sql);

            resetCancelledState();

            char firstNonWsChar = StringUtils.firstAlphaCharUc(sql, findStartOfStatement(sql));
            boolean maybeSelect = firstNonWsChar == 'S';

            this.retrieveGeneratedKeys = returnGeneratedKeys;

            this.lastQueryIsOnDupKeyUpdate = returnGeneratedKeys && firstNonWsChar == 'I' && containsOnDuplicateKeyInString(sql);

            if (!maybeSelect && locallyScopedConn.isReadOnly()) {
                throw SQLError.createSQLException(Messages.getString("Statement.27") + Messages.getString("Statement.28"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                        getExceptionInterceptor());
            }

            boolean readInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled();
            if (returnGeneratedKeys && firstNonWsChar == 'R') {
                // If this is a 'REPLACE' query, we need to be able to parse the 'info' message returned from the server to determine the actual number of keys
                // generated.
                locallyScopedConn.setReadInfoMsgEnabled(true);
            }

            try {
                setupStreamingTimeout(locallyScopedConn);

                if (this.doEscapeProcessing) {
                    Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, locallyScopedConn.serverSupportsConvertFn(), locallyScopedConn);

                    if (escapedSqlResult instanceof String) {
                        sql = (String) escapedSqlResult;
                    } else {
                        sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;
                    }
                }

                implicitlyCloseAllOpenResults();

                if (sql.charAt(0) == '/') {
                    if (sql.startsWith(PING_MARKER)) {
                        doPingInstead();

                        return true;
                    }
                }

                CachedResultSetMetaData cachedMetaData = null;

                ResultSetInternalMethods rs = null;

                this.batchedGeneratedKeys = null;

                if (useServerFetch()) {
                    rs = createResultSetUsingServerFetch(sql);
                } else {
                    CancelTask timeoutTask = null;

                    String oldCatalog = null;

                    try {
                        if (locallyScopedConn.getEnableQueryTimeouts() && this.timeoutInMillis != 0 && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
                            timeoutTask = new CancelTask(this);
                            locallyScopedConn.getCancelTimer().schedule(timeoutTask, this.timeoutInMillis);
                        }

                        if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
                            oldCatalog = locallyScopedConn.getCatalog();
                            locallyScopedConn.setCatalog(this.currentCatalog);
                        }

                        //
                        // Check if we have cached metadata for this query...
                        //

                        Field[] cachedFields = null;

                        if (locallyScopedConn.getCacheResultSetMetadata()) {
                            cachedMetaData = locallyScopedConn.getCachedMetaData(sql);

                            if (cachedMetaData != null) {
                                cachedFields = cachedMetaData.fields;
                            }
                        }

                        //
                        // Only apply max_rows to selects
                        //
                        locallyScopedConn.setSessionMaxRows(maybeSelect ? this.maxRows : -1);

                        statementBegins();

                        rs = locallyScopedConn.execSQL(this, sql, this.maxRows, null, this.resultSetType, this.resultSetConcurrency, createStreamingResultSet(),
                                this.currentCatalog, cachedFields);

                        if (timeoutTask != null) {
                            if (timeoutTask.caughtWhileCancelling != null) {
                                throw timeoutTask.caughtWhileCancelling;
                            }

                            timeoutTask.cancel();
                            timeoutTask = null;
                        }

                        synchronized (this.cancelTimeoutMutex) {
                            if (this.wasCancelled) {
                                SQLException cause = null;

                                if (this.wasCancelledByTimeout) {
                                    cause = new MySQLTimeoutException();
                                } else {
                                    cause = new MySQLStatementCancelledException();
                                }

                                resetCancelledState();

                                throw cause;
                            }
                        }
                    } finally {
                        if (timeoutTask != null) {
                            timeoutTask.cancel();
                            locallyScopedConn.getCancelTimer().purge();
                        }

                        if (oldCatalog != null) {
                            locallyScopedConn.setCatalog(oldCatalog);
                        }
                    }
                }

                if (rs != null) {
                    this.lastInsertId = rs.getUpdateID();

                    this.results = rs;

                    rs.setFirstCharOfQuery(firstNonWsChar);

                    if (rs.reallyResult()) {
                        if (cachedMetaData != null) {
                            locallyScopedConn.initializeResultsMetadataFromCache(sql, cachedMetaData, this.results);
                        } else {
                            if (this.connection.getCacheResultSetMetadata()) {
                                locallyScopedConn.initializeResultsMetadataFromCache(sql, null /* will be created */, this.results);
                            }
                        }
                    }
                }

                return ((rs != null) && rs.reallyResult());
            } finally {
                locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);

                this.statementExecuting.set(false);
            }
        }
    }

    protected void statementBegins() {
        this.clearWarningsCalled = false;
        this.statementExecuting.set(true);
    }

    protected void resetCancelledState() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.cancelTimeoutMutex == null) {
                return;
            }

            synchronized (this.cancelTimeoutMutex) {
                this.wasCancelled = false;
                this.wasCancelledByTimeout = false;
            }
        }
    }

    /**
     * @see StatementImpl#execute(String, int)
     */
    public boolean execute(String sql, int returnGeneratedKeys) throws SQLException {
        return executeInternal(sql, returnGeneratedKeys == java.sql.Statement.RETURN_GENERATED_KEYS);
    }

    /**
     * @see StatementImpl#execute(String, int[])
     */
    public boolean execute(String sql, int[] generatedKeyIndices) throws SQLException {
        return executeInternal(sql, generatedKeyIndices != null && generatedKeyIndices.length > 0);
    }

    /**
     * @see StatementImpl#execute(String, String[])
     */
    public boolean execute(String sql, String[] generatedKeyNames) throws SQLException {
        return executeInternal(sql, generatedKeyNames != null && generatedKeyNames.length > 0);
    }

    /**
     * JDBC 2.0 Submit a batch of commands to the database for execution. This
     * method is optional.
     * 
     * @return an array of update counts containing one element for each command
     *         in the batch. The array is ordered according to the order in
     *         which commands were inserted into the batch
     * 
     * @exception SQLException
     *                if a database-access error occurs, or the driver does not
     *                support batch statements
     * @throws java.sql.BatchUpdateException
     */
    public int[] executeBatch() throws SQLException {
        return Util.truncateAndConvertToInt(executeBatchInternal());
    }

    protected long[] executeBatchInternal() throws SQLException {
        MySQLConnection locallyScopedConn = checkClosed();

        synchronized (locallyScopedConn.getConnectionMutex()) {
            if (locallyScopedConn.isReadOnly()) {
                throw SQLError.createSQLException(Messages.getString("Statement.34") + Messages.getString("Statement.35"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                        getExceptionInterceptor());
            }

            implicitlyCloseAllOpenResults();

            if (this.batchedArgs == null || this.batchedArgs.size() == 0) {
                return new long[0];
            }

            // we timeout the entire batch, not individual statements
            int individualStatementTimeout = this.timeoutInMillis;
            this.timeoutInMillis = 0;

            CancelTask timeoutTask = null;

            try {
                resetCancelledState();

                statementBegins();

                try {
                    this.retrieveGeneratedKeys = true; // The JDBC spec doesn't forbid this, but doesn't provide for it either...we do..

                    long[] updateCounts = null;

                    if (this.batchedArgs != null) {
                        int nbrCommands = this.batchedArgs.size();

                        this.batchedGeneratedKeys = new ArrayList<ResultSetRow>(this.batchedArgs.size());

                        boolean multiQueriesEnabled = locallyScopedConn.getAllowMultiQueries();

                        if (locallyScopedConn.versionMeetsMinimum(4, 1, 1)
                                && (multiQueriesEnabled || (locallyScopedConn.getRewriteBatchedStatements() && nbrCommands > 4))) {
                            return executeBatchUsingMultiQueries(multiQueriesEnabled, nbrCommands, individualStatementTimeout);
                        }

                        if (locallyScopedConn.getEnableQueryTimeouts() && individualStatementTimeout != 0 && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
                            timeoutTask = new CancelTask(this);
                            locallyScopedConn.getCancelTimer().schedule(timeoutTask, individualStatementTimeout);
                        }

                        updateCounts = new long[nbrCommands];

                        for (int i = 0; i < nbrCommands; i++) {
                            updateCounts[i] = -3;
                        }

                        SQLException sqlEx = null;

                        int commandIndex = 0;

                        for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) {
                            try {
                                String sql = (String) this.batchedArgs.get(commandIndex);
                                updateCounts[commandIndex] = executeUpdateInternal(sql, true, true);
                                // limit one generated key per OnDuplicateKey statement
                                getBatchedGeneratedKeys(this.results.getFirstCharOfQuery() == 'I' && containsOnDuplicateKeyInString(sql) ? 1 : 0);
                            } catch (SQLException ex) {
                                updateCounts[commandIndex] = EXECUTE_FAILED;

                                if (this.continueBatchOnError && !(ex instanceof MySQLTimeoutException) && !(ex instanceof MySQLStatementCancelledException)
                                        && !hasDeadlockOrTimeoutRolledBackTx(ex)) {
                                    sqlEx = ex;
                                } else {
                                    long[] newUpdateCounts = new long[commandIndex];

                                    if (hasDeadlockOrTimeoutRolledBackTx(ex)) {
                                        for (int i = 0; i < newUpdateCounts.length; i++) {
                                            newUpdateCounts[i] = java.sql.Statement.EXECUTE_FAILED;
                                        }
                                    } else {
                                        System.arraycopy(updateCounts, 0, newUpdateCounts, 0, commandIndex);
                                    }

                                    throw SQLError.createBatchUpdateException(ex, newUpdateCounts, getExceptionInterceptor());
                                }
                            }
                        }

                        if (sqlEx != null) {
                            throw SQLError.createBatchUpdateException(sqlEx, updateCounts, getExceptionInterceptor());
                        }
                    }

                    if (timeoutTask != null) {
                        if (timeoutTask.caughtWhileCancelling != null) {
                            throw timeoutTask.caughtWhileCancelling;
                        }

                        timeoutTask.cancel();

                        locallyScopedConn.getCancelTimer().purge();
                        timeoutTask = null;
                    }

                    return (updateCounts != null) ? updateCounts : new long[0];
                } finally {
                    this.statementExecuting.set(false);
                }
            } finally {

                if (timeoutTask != null) {
                    timeoutTask.cancel();

                    locallyScopedConn.getCancelTimer().purge();
                }

                resetCancelledState();

                this.timeoutInMillis = individualStatementTimeout;

                clearBatch();
            }
        }
    }

    protected final boolean hasDeadlockOrTimeoutRolledBackTx(SQLException ex) {
        int vendorCode = ex.getErrorCode();

        switch (vendorCode) {
            case MysqlErrorNumbers.ER_LOCK_DEADLOCK:
            case MysqlErrorNumbers.ER_LOCK_TABLE_FULL:
                return true;
            case MysqlErrorNumbers.ER_LOCK_WAIT_TIMEOUT:
                return !this.version5013OrNewer;
            default:
                return false;
        }
    }

    /**
     * Rewrites batch into a single query to send to the server. This method
     * will constrain each batch to be shorter than max_allowed_packet on the
     * server.
     * 
     * @return update counts in the same manner as executeBatch()
     * @throws SQLException
     */
    private long[] executeBatchUsingMultiQueries(boolean multiQueriesEnabled, int nbrCommands, int individualStatementTimeout) throws SQLException {

        MySQLConnection locallyScopedConn = checkClosed();

        synchronized (locallyScopedConn.getConnectionMutex()) {
            if (!multiQueriesEnabled) {
                locallyScopedConn.getIO().enableMultiQueries();
            }

            java.sql.Statement batchStmt = null;

            CancelTask timeoutTask = null;

            try {
                long[] updateCounts = new long[nbrCommands];

                for (int i = 0; i < nbrCommands; i++) {
                    updateCounts[i] = Statement.EXECUTE_FAILED;
                }

                int commandIndex = 0;

                StringBuilder queryBuf = new StringBuilder();

                batchStmt = locallyScopedConn.createStatement();

                if (locallyScopedConn.getEnableQueryTimeouts() && individualStatementTimeout != 0 && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
                    timeoutTask = new CancelTask((StatementImpl) batchStmt);
                    locallyScopedConn.getCancelTimer().schedule(timeoutTask, individualStatementTimeout);
                }

                int counter = 0;

                int numberOfBytesPerChar = 1;

                String connectionEncoding = locallyScopedConn.getEncoding();

                if (StringUtils.startsWithIgnoreCase(connectionEncoding, "utf")) {
                    numberOfBytesPerChar = 3;
                } else if (CharsetMapping.isMultibyteCharset(connectionEncoding)) {
                    numberOfBytesPerChar = 2;
                }

                int escapeAdjust = 1;

                batchStmt.setEscapeProcessing(this.doEscapeProcessing);

                if (this.doEscapeProcessing) {
                    escapeAdjust = 2; // We assume packet _could_ grow by this amount, as we're not sure how big statement will end up after  escape processing
                }

                SQLException sqlEx = null;

                int argumentSetsInBatchSoFar = 0;

                for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) {
                    String nextQuery = (String) this.batchedArgs.get(commandIndex);

                    if (((((queryBuf.length() + nextQuery.length()) * numberOfBytesPerChar) + 1 /* for semicolon */
                            + MysqlIO.HEADER_LENGTH) * escapeAdjust) + 32 > this.connection.getMaxAllowedPacket()) {
                        try {
                            batchStmt.execute(queryBuf.toString(), java.sql.Statement.RETURN_GENERATED_KEYS);
                        } catch (SQLException ex) {
                            sqlEx = handleExceptionForBatch(commandIndex, argumentSetsInBatchSoFar, updateCounts, ex);
                        }

                        counter = processMultiCountsAndKeys((StatementImpl) batchStmt, counter, updateCounts);

                        queryBuf = new StringBuilder();
                        argumentSetsInBatchSoFar = 0;
                    }

                    queryBuf.append(nextQuery);
                    queryBuf.append(";");
                    argumentSetsInBatchSoFar++;
                }

                if (queryBuf.length() > 0) {
                    try {
                        batchStmt.execute(queryBuf.toString(), java.sql.Statement.RETURN_GENERATED_KEYS);
                    } catch (SQLException ex) {
                        sqlEx = handleExceptionForBatch(commandIndex - 1, argumentSetsInBatchSoFar, updateCounts, ex);
                    }

                    counter = processMultiCountsAndKeys((StatementImpl) batchStmt, counter, updateCounts);
                }

                if (timeoutTask != null) {
                    if (timeoutTask.caughtWhileCancelling != null) {
                        throw timeoutTask.caughtWhileCancelling;
                    }

                    timeoutTask.cancel();

                    locallyScopedConn.getCancelTimer().purge();

                    timeoutTask = null;
                }

                if (sqlEx != null) {
                    throw SQLError.createBatchUpdateException(sqlEx, updateCounts, getExceptionInterceptor());
                }

                return (updateCounts != null) ? updateCounts : new long[0];
            } finally {
                if (timeoutTask != null) {
                    timeoutTask.cancel();

                    locallyScopedConn.getCancelTimer().purge();
                }

                resetCancelledState();

                try {
                    if (batchStmt != null) {
                        batchStmt.close();
                    }
                } finally {
                    if (!multiQueriesEnabled) {
                        locallyScopedConn.getIO().disableMultiQueries();
                    }
                }
            }
        }
    }

    protected int processMultiCountsAndKeys(StatementImpl batchedStatement, int updateCountCounter, long[] updateCounts) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            updateCounts[updateCountCounter++] = batchedStatement.getLargeUpdateCount();

            boolean doGenKeys = this.batchedGeneratedKeys != null;

            byte[][] row = null;

            if (doGenKeys) {
                long generatedKey = batchedStatement.getLastInsertID();

                row = new byte[1][];
                row[0] = StringUtils.getBytes(Long.toString(generatedKey));
                this.batchedGeneratedKeys.add(new ByteArrayRow(row, getExceptionInterceptor()));
            }

            while (batchedStatement.getMoreResults() || batchedStatement.getLargeUpdateCount() != -1) {
                updateCounts[updateCountCounter++] = batchedStatement.getLargeUpdateCount();

                if (doGenKeys) {
                    long generatedKey = batchedStatement.getLastInsertID();

                    row = new byte[1][];
                    row[0] = StringUtils.getBytes(Long.toString(generatedKey));
                    this.batchedGeneratedKeys.add(new ByteArrayRow(row, getExceptionInterceptor()));
                }
            }

            return updateCountCounter;
        }
    }

    protected SQLException handleExceptionForBatch(int endOfBatchIndex, int numValuesPerBatch, long[] updateCounts, SQLException ex)
            throws BatchUpdateException, SQLException {
        for (int j = endOfBatchIndex; j > endOfBatchIndex - numValuesPerBatch; j--) {
            updateCounts[j] = EXECUTE_FAILED;
        }

        if (this.continueBatchOnError && !(ex instanceof MySQLTimeoutException) && !(ex instanceof MySQLStatementCancelledException)
                && !hasDeadlockOrTimeoutRolledBackTx(ex)) {
            return ex;
        } // else: throw the exception immediately

        long[] newUpdateCounts = new long[endOfBatchIndex];
        System.arraycopy(updateCounts, 0, newUpdateCounts, 0, endOfBatchIndex);

        throw SQLError.createBatchUpdateException(ex, newUpdateCounts, getExceptionInterceptor());
    }

    /**
     * Execute a SQL statement that returns a single ResultSet
     * 
     * @param sql
     *            typically a static SQL SELECT statement
     * 
     * @return a ResulSet that contains the data produced by the query
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public java.sql.ResultSet executeQuery(String sql) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            MySQLConnection locallyScopedConn = this.connection;

            this.retrieveGeneratedKeys = false;

            resetCancelledState();

            checkNullOrEmptyQuery(sql);

            setupStreamingTimeout(locallyScopedConn);

            if (this.doEscapeProcessing) {
                Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, locallyScopedConn.serverSupportsConvertFn(), this.connection);

                if (escapedSqlResult instanceof String) {
                    sql = (String) escapedSqlResult;
                } else {
                    sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;
                }
            }

            char firstStatementChar = StringUtils.firstAlphaCharUc(sql, findStartOfStatement(sql));

            if (sql.charAt(0) == '/') {
                if (sql.startsWith(PING_MARKER)) {
                    doPingInstead();

                    return this.results;
                }
            }

            checkForDml(sql, firstStatementChar);

            implicitlyCloseAllOpenResults();

            CachedResultSetMetaData cachedMetaData = null;

            if (useServerFetch()) {
                this.results = createResultSetUsingServerFetch(sql);

                return this.results;
            }

            CancelTask timeoutTask = null;

            String oldCatalog = null;

            try {
                if (locallyScopedConn.getEnableQueryTimeouts() && this.timeoutInMillis != 0 && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
                    timeoutTask = new CancelTask(this);
                    locallyScopedConn.getCancelTimer().schedule(timeoutTask, this.timeoutInMillis);
                }

                if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
                    oldCatalog = locallyScopedConn.getCatalog();
                    locallyScopedConn.setCatalog(this.currentCatalog);
                }

                //
                // Check if we have cached metadata for this query...
                //

                Field[] cachedFields = null;

                if (locallyScopedConn.getCacheResultSetMetadata()) {
                    cachedMetaData = locallyScopedConn.getCachedMetaData(sql);

                    if (cachedMetaData != null) {
                        cachedFields = cachedMetaData.fields;
                    }
                }

                locallyScopedConn.setSessionMaxRows(this.maxRows);

                statementBegins();

                this.results = locallyScopedConn.execSQL(this, sql, this.maxRows, null, this.resultSetType, this.resultSetConcurrency,
                        createStreamingResultSet(), this.currentCatalog, cachedFields);

                if (timeoutTask != null) {
                    if (timeoutTask.caughtWhileCancelling != null) {
                        throw timeoutTask.caughtWhileCancelling;
                    }

                    timeoutTask.cancel();

                    locallyScopedConn.getCancelTimer().purge();

                    timeoutTask = null;
                }

                synchronized (this.cancelTimeoutMutex) {
                    if (this.wasCancelled) {
                        SQLException cause = null;

                        if (this.wasCancelledByTimeout) {
                            cause = new MySQLTimeoutException();
                        } else {
                            cause = new MySQLStatementCancelledException();
                        }

                        resetCancelledState();

                        throw cause;
                    }
                }
            } finally {
                this.statementExecuting.set(false);

                if (timeoutTask != null) {
                    timeoutTask.cancel();

                    locallyScopedConn.getCancelTimer().purge();
                }

                if (oldCatalog != null) {
                    locallyScopedConn.setCatalog(oldCatalog);
                }
            }

            this.lastInsertId = this.results.getUpdateID();

            if (cachedMetaData != null) {
                locallyScopedConn.initializeResultsMetadataFromCache(sql, cachedMetaData, this.results);
            } else {
                if (this.connection.getCacheResultSetMetadata()) {
                    locallyScopedConn.initializeResultsMetadataFromCache(sql, null /* will be created */, this.results);
                }
            }

            return this.results;
        }
    }

    protected void doPingInstead() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.pingTarget != null) {
                this.pingTarget.doPing();
            } else {
                this.connection.ping();
            }

            ResultSetInternalMethods fakeSelectOneResultSet = generatePingResultSet();
            this.results = fakeSelectOneResultSet;
        }
    }

    protected ResultSetInternalMethods generatePingResultSet() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            Field[] fields = { new Field(null, "1", Types.BIGINT, 1) };
            ArrayList<ResultSetRow> rows = new ArrayList<ResultSetRow>();
            byte[] colVal = new byte[] { (byte) '1' };

            rows.add(new ByteArrayRow(new byte[][] { colVal }, getExceptionInterceptor()));

            return (ResultSetInternalMethods) DatabaseMetaData.buildResultSet(fields, rows, this.connection);
        }
    }

    protected void executeSimpleNonQuery(MySQLConnection c, String nonQuery) throws SQLException {
        c.execSQL(this, nonQuery, -1, null, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, false, this.currentCatalog, null, false).close();
    }

    /**
     * Execute a SQL INSERT, UPDATE or DELETE statement. In addition SQL statements that return nothing such as SQL DDL statements can be executed.
     * 
     * @param sql
     *            a SQL statement
     * 
     * @return either a row count, or 0 for SQL commands
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public int executeUpdate(String sql) throws SQLException {
        return Util.truncateAndConvertToInt(executeLargeUpdate(sql));
    }

    protected long executeUpdateInternal(String sql, boolean isBatch, boolean returnGeneratedKeys) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            MySQLConnection locallyScopedConn = this.connection;

            checkNullOrEmptyQuery(sql);

            resetCancelledState();

            char firstStatementChar = StringUtils.firstAlphaCharUc(sql, findStartOfStatement(sql));

            this.retrieveGeneratedKeys = returnGeneratedKeys;

            this.lastQueryIsOnDupKeyUpdate = returnGeneratedKeys && firstStatementChar == 'I' && containsOnDuplicateKeyInString(sql);

            ResultSetInternalMethods rs = null;

            if (this.doEscapeProcessing) {
                Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, this.connection.serverSupportsConvertFn(), this.connection);

                if (escapedSqlResult instanceof String) {
                    sql = (String) escapedSqlResult;
                } else {
                    sql = ((EscapeProcessorResult) escapedSqlResult).escapedSql;
                }
            }

            if (locallyScopedConn.isReadOnly(false)) {
                throw SQLError.createSQLException(Messages.getString("Statement.42") + Messages.getString("Statement.43"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                        getExceptionInterceptor());
            }

            if (StringUtils.startsWithIgnoreCaseAndWs(sql, "select")) {
                throw SQLError.createSQLException(Messages.getString("Statement.46"), "01S03", getExceptionInterceptor());
            }

            implicitlyCloseAllOpenResults();

            // The checking and changing of catalogs must happen in sequence, so synchronize on the same mutex that _conn is using

            CancelTask timeoutTask = null;

            String oldCatalog = null;

            boolean readInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled();
            if (returnGeneratedKeys && firstStatementChar == 'R') {
                // If this is a 'REPLACE' query, we need to be able to parse the 'info' message returned from the server to determine the actual number of keys
                // generated.
                locallyScopedConn.setReadInfoMsgEnabled(true);
            }

            try {
                if (locallyScopedConn.getEnableQueryTimeouts() && this.timeoutInMillis != 0 && locallyScopedConn.versionMeetsMinimum(5, 0, 0)) {
                    timeoutTask = new CancelTask(this);
                    locallyScopedConn.getCancelTimer().schedule(timeoutTask, this.timeoutInMillis);
                }

                if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
                    oldCatalog = locallyScopedConn.getCatalog();
                    locallyScopedConn.setCatalog(this.currentCatalog);
                }

                //
                // Only apply max_rows to selects
                //
                locallyScopedConn.setSessionMaxRows(-1);

                statementBegins();

                // null catalog: force read of field info on DML
                rs = locallyScopedConn.execSQL(this, sql, -1, null, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY, false,
                        this.currentCatalog, null, isBatch);

                if (timeoutTask != null) {
                    if (timeoutTask.caughtWhileCancelling != null) {
                        throw timeoutTask.caughtWhileCancelling;
                    }

                    timeoutTask.cancel();

                    locallyScopedConn.getCancelTimer().purge();

                    timeoutTask = null;
                }

                synchronized (this.cancelTimeoutMutex) {
                    if (this.wasCancelled) {
                        SQLException cause = null;

                        if (this.wasCancelledByTimeout) {
                            cause = new MySQLTimeoutException();
                        } else {
                            cause = new MySQLStatementCancelledException();
                        }

                        resetCancelledState();

                        throw cause;
                    }
                }
            } finally {
                locallyScopedConn.setReadInfoMsgEnabled(readInfoMsgState);

                if (timeoutTask != null) {
                    timeoutTask.cancel();

                    locallyScopedConn.getCancelTimer().purge();
                }

                if (oldCatalog != null) {
                    locallyScopedConn.setCatalog(oldCatalog);
                }

                if (!isBatch) {
                    this.statementExecuting.set(false);
                }
            }

            this.results = rs;

            rs.setFirstCharOfQuery(firstStatementChar);

            this.updateCount = rs.getUpdateCount();

            this.lastInsertId = rs.getUpdateID();

            return this.updateCount;
        }
    }

    /**
     * @see StatementImpl#executeUpdate(String, int)
     */
    public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        return Util.truncateAndConvertToInt(executeLargeUpdate(sql, autoGeneratedKeys));
    }

    /**
     * @see StatementImpl#executeUpdate(String, int[])
     */
    public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
        return Util.truncateAndConvertToInt(executeLargeUpdate(sql, columnIndexes));
    }

    /**
     * @see StatementImpl#executeUpdate(String, String[])
     */
    public int executeUpdate(String sql, String[] columnNames) throws SQLException {
        return Util.truncateAndConvertToInt(executeLargeUpdate(sql, columnNames));
    }

    /**
     * Optimization to only use one calendar per-session, or calculate it for
     * each call, depending on user configuration
     */
    protected Calendar getCalendarInstanceForSessionOrNew() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.connection != null) {
                return this.connection.getCalendarInstanceForSessionOrNew();
            }
            // punt, no connection around
            return new GregorianCalendar();
        }
    }

    /**
     * JDBC 2.0 Return the Connection that produced the Statement.
     * 
     * @return the Connection that produced the Statement
     * 
     * @throws SQLException
     *             if an error occurs
     */
    public java.sql.Connection getConnection() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.connection;
        }
    }

    /**
     * JDBC 2.0 Determine the fetch direction.
     * 
     * @return the default fetch direction
     * 
     * @exception SQLException
     *                if a database-access error occurs
     */
    public int getFetchDirection() throws SQLException {
        return java.sql.ResultSet.FETCH_FORWARD;
    }

    /**
     * JDBC 2.0 Determine the default fetch size.
     * 
     * @return the number of rows to fetch at a time
     * 
     * @throws SQLException
     *             if an error occurs
     */
    public int getFetchSize() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.fetchSize;
        }
    }

    /**
     * @throws SQLException
     */
    public java.sql.ResultSet getGeneratedKeys() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (!this.retrieveGeneratedKeys) {
                throw SQLError.createSQLException(Messages.getString("Statement.GeneratedKeysNotRequested"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                        getExceptionInterceptor());
            }

            if (this.batchedGeneratedKeys == null) {
                if (this.lastQueryIsOnDupKeyUpdate) {
                    return this.generatedKeysResults = getGeneratedKeysInternal(1);
                }
                return this.generatedKeysResults = getGeneratedKeysInternal();
            }

            Field[] fields = new Field[1];
            fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 20);
            fields[0].setConnection(this.connection);

            this.generatedKeysResults = com.mysql.jdbc.ResultSetImpl.getInstance(this.currentCatalog, fields, new RowDataStatic(this.batchedGeneratedKeys),
                    this.connection, this, false);

            return this.generatedKeysResults;
        }
    }

    /*
     * Needed because there's no concept of super.super to get to this
     * implementation from ServerPreparedStatement when dealing with batched
     * updates.
     */
    protected ResultSetInternalMethods getGeneratedKeysInternal() throws SQLException {
        long numKeys = getLargeUpdateCount();
        return getGeneratedKeysInternal(numKeys);
    }

    protected ResultSetInternalMethods getGeneratedKeysInternal(long numKeys) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            Field[] fields = new Field[1];
            fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 20);
            fields[0].setConnection(this.connection);
            fields[0].setUseOldNameMetadata(true);

            ArrayList<ResultSetRow> rowSet = new ArrayList<ResultSetRow>();

            long beginAt = getLastInsertID();

            if (beginAt < 0) { // looking at an UNSIGNED BIGINT that has overflowed
                fields[0].setUnsigned();
            }

            if (this.results != null) {
                String serverInfo = this.results.getServerInfo();

                //
                // Only parse server info messages for 'REPLACE' queries
                //
                if ((numKeys > 0) && (this.results.getFirstCharOfQuery() == 'R') && (serverInfo != null) && (serverInfo.length() > 0)) {
                    numKeys = getRecordCountFromInfo(serverInfo);
                }

                if ((beginAt != 0 /* BIGINT UNSIGNED can wrap the protocol representation */) && (numKeys > 0)) {
                    for (int i = 0; i < numKeys; i++) {
                        byte[][] row = new byte[1][];
                        if (beginAt > 0) {
                            row[0] = StringUtils.getBytes(Long.toString(beginAt));
                        } else {
                            byte[] asBytes = new byte[8];
                            asBytes[7] = (byte) (beginAt & 0xff);
                            asBytes[6] = (byte) (beginAt >>> 8);
                            asBytes[5] = (byte) (beginAt >>> 16);
                            asBytes[4] = (byte) (beginAt >>> 24);
                            asBytes[3] = (byte) (beginAt >>> 32);
                            asBytes[2] = (byte) (beginAt >>> 40);
                            asBytes[1] = (byte) (beginAt >>> 48);
                            asBytes[0] = (byte) (beginAt >>> 56);

                            BigInteger val = new BigInteger(1, asBytes);

                            row[0] = val.toString().getBytes();
                        }
                        rowSet.add(new ByteArrayRow(row, getExceptionInterceptor()));
                        beginAt += this.connection.getAutoIncrementIncrement();
                    }
                }
            }

            com.mysql.jdbc.ResultSetImpl gkRs = com.mysql.jdbc.ResultSetImpl.getInstance(this.currentCatalog, fields, new RowDataStatic(rowSet),
                    this.connection, this, false);

            return gkRs;
        }
    }

    /**
     * Returns the id used when profiling
     * 
     * @return the id used when profiling.
     */
    protected int getId() {
        return this.statementId;
    }

    /**
     * getLastInsertID returns the value of the auto_incremented key after an
     * executeQuery() or excute() call.
     * 
     * <p>
     * This gets around the un-threadsafe behavior of "select LAST_INSERT_ID()" which is tied to the Connection that created this Statement, and therefore could
     * have had many INSERTS performed before one gets a chance to call "select LAST_INSERT_ID()".
     * </p>
     * 
     * @return the last update ID.
     */
    public long getLastInsertID() {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                return this.lastInsertId;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e); // evolve interface to throw SQLException
        }
    }

    /**
     * getLongUpdateCount returns the current result as an update count, if the
     * result is a ResultSet or there are no more results, -1 is returned. It
     * should only be called once per result.
     * 
     * <p>
     * This method returns longs as MySQL server versions newer than 3.22.4 return 64-bit values for update counts
     * </p>
     * 
     * @return the current update count.
     */
    public long getLongUpdateCount() {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                if (this.results == null) {
                    return -1;
                }

                if (this.results.reallyResult()) {
                    return -1;
                }

                return this.updateCount;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e); // evolve interface to throw SQLException
        }
    }

    /**
     * The maxFieldSize limit (in bytes) is the maximum amount of data returned
     * for any column value; it only applies to BINARY, VARBINARY,
     * LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR columns. If the limit is
     * exceeded, the excess data is silently discarded.
     * 
     * @return the current max column size limit; zero means unlimited
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public int getMaxFieldSize() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.maxFieldSize;
        }
    }

    /**
     * The maxRows limit is set to limit the number of rows that any ResultSet
     * can contain. If the limit is exceeded, the excess rows are silently
     * dropped.
     * 
     * @return the current maximum row limit; zero means unlimited
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public int getMaxRows() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.maxRows <= 0) {
                return 0;
            }

            return this.maxRows;
        }
    }

    /**
     * getMoreResults moves to a Statement's next result. If it returns true,
     * this result is a ResulSet.
     * 
     * @return true if the next ResultSet is valid
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public boolean getMoreResults() throws SQLException {
        return getMoreResults(CLOSE_CURRENT_RESULT);
    }

    /**
     * @see StatementImpl#getMoreResults(int)
     */
    public boolean getMoreResults(int current) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.results == null) {
                return false;
            }

            boolean streamingMode = createStreamingResultSet();

            if (streamingMode) {
                if (this.results.reallyResult()) {
                    while (this.results.next()) {
                        // need to drain remaining rows to get to server status which tells us whether more results actually exist or not
                    }
                }
            }

            ResultSetInternalMethods nextResultSet = this.results.getNextResultSet();

            switch (current) {
                case java.sql.Statement.CLOSE_CURRENT_RESULT:

                    if (this.results != null) {
                        if (!(streamingMode || this.connection.getDontTrackOpenResources())) {
                            this.results.realClose(false);
                        }

                        this.results.clearNextResult();
                    }

                    break;

                case java.sql.Statement.CLOSE_ALL_RESULTS:

                    if (this.results != null) {
                        if (!(streamingMode || this.connection.getDontTrackOpenResources())) {
                            this.results.realClose(false);
                        }

                        this.results.clearNextResult();
                    }

                    closeAllOpenResults();

                    break;

                case java.sql.Statement.KEEP_CURRENT_RESULT:
                    if (!this.connection.getDontTrackOpenResources()) {
                        this.openResults.add(this.results);
                    }

                    this.results.clearNextResult(); // nobody besides us should
                    // ever need this value...
                    break;

                default:
                    throw SQLError.createSQLException(Messages.getString("Statement.19"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }

            this.results = nextResultSet;

            if (this.results == null) {
                this.updateCount = -1;
                this.lastInsertId = -1;
            } else if (this.results.reallyResult()) {
                this.updateCount = -1;
                this.lastInsertId = -1;
            } else {
                this.updateCount = this.results.getUpdateCount();
                this.lastInsertId = this.results.getUpdateID();
            }

            boolean moreResults = (this.results != null) && this.results.reallyResult();
            if (!moreResults) {
                checkAndPerformCloseOnCompletionAction();
            }
            return moreResults;
        }
    }

    /**
     * The queryTimeout limit is the number of seconds the driver will wait for
     * a Statement to execute. If the limit is exceeded, a SQLException is
     * thrown.
     * 
     * @return the current query timeout limit in seconds; 0 = unlimited
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public int getQueryTimeout() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.timeoutInMillis / 1000;
        }
    }

    /**
     * Parses actual record count from 'info' message
     * 
     * @param serverInfo
     */
    private long getRecordCountFromInfo(String serverInfo) {
        StringBuilder recordsBuf = new StringBuilder();
        long recordsCount = 0;
        long duplicatesCount = 0;

        char c = (char) 0;

        int length = serverInfo.length();
        int i = 0;

        for (; i < length; i++) {
            c = serverInfo.charAt(i);

            if (Character.isDigit(c)) {
                break;
            }
        }

        recordsBuf.append(c);
        i++;

        for (; i < length; i++) {
            c = serverInfo.charAt(i);

            if (!Character.isDigit(c)) {
                break;
            }

            recordsBuf.append(c);
        }

        recordsCount = Long.parseLong(recordsBuf.toString());

        StringBuilder duplicatesBuf = new StringBuilder();

        for (; i < length; i++) {
            c = serverInfo.charAt(i);

            if (Character.isDigit(c)) {
                break;
            }
        }

        duplicatesBuf.append(c);
        i++;

        for (; i < length; i++) {
            c = serverInfo.charAt(i);

            if (!Character.isDigit(c)) {
                break;
            }

            duplicatesBuf.append(c);
        }

        duplicatesCount = Long.parseLong(duplicatesBuf.toString());

        return recordsCount - duplicatesCount;
    }

    /**
     * getResultSet returns the current result as a ResultSet. It should only be
     * called once per result.
     * 
     * @return the current result set; null if there are no more
     * 
     * @exception SQLException
     *                if a database access error occurs (why?)
     */
    public java.sql.ResultSet getResultSet() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return ((this.results != null) && this.results.reallyResult()) ? (java.sql.ResultSet) this.results : null;
        }
    }

    /**
     * JDBC 2.0 Determine the result set concurrency.
     * 
     * @return CONCUR_UPDATABLE or CONCUR_READONLY
     * 
     * @throws SQLException
     *             if an error occurs
     */
    public int getResultSetConcurrency() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.resultSetConcurrency;
        }
    }

    /**
     * @see StatementImpl#getResultSetHoldability()
     */
    public int getResultSetHoldability() throws SQLException {
        return java.sql.ResultSet.HOLD_CURSORS_OVER_COMMIT;
    }

    protected ResultSetInternalMethods getResultSetInternal() {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                return this.results;
            }
        } catch (SQLException e) {
            return this.results; // you end up with the same thing as before, you'll get exception when actually trying to use it
        }
    }

    /**
     * JDBC 2.0 Determine the result set type.
     * 
     * @return the ResultSet type (SCROLL_SENSITIVE or SCROLL_INSENSITIVE)
     * 
     * @throws SQLException
     *             if an error occurs.
     */
    public int getResultSetType() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.resultSetType;
        }
    }

    /**
     * getUpdateCount returns the current result as an update count, if the
     * result is a ResultSet or there are no more results, -1 is returned. It
     * should only be called once per result.
     * 
     * @return the current result as an update count.
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public int getUpdateCount() throws SQLException {
        return Util.truncateAndConvertToInt(getLargeUpdateCount());
    }

    /**
     * The first warning reported by calls on this Statement is returned. A
     * Statement's execute methods clear its java.sql.SQLWarning chain.
     * Subsequent Statement warnings will be chained to this
     * java.sql.SQLWarning.
     * 
     * <p>
     * The Warning chain is automatically cleared each time a statement is (re)executed.
     * </p>
     * 
     * <p>
     * <B>Note:</B> If you are processing a ResultSet then any warnings associated with ResultSet reads will be chained on the ResultSet object.
     * </p>
     * 
     * @return the first java.sql.SQLWarning or null
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public java.sql.SQLWarning getWarnings() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {

            if (this.clearWarningsCalled) {
                return null;
            }

            if (this.connection.versionMeetsMinimum(4, 1, 0)) {
                SQLWarning pendingWarningsFromServer = SQLError.convertShowWarningsToSQLWarnings(this.connection);

                if (this.warningChain != null) {
                    this.warningChain.setNextWarning(pendingWarningsFromServer);
                } else {
                    this.warningChain = pendingWarningsFromServer;
                }

                return this.warningChain;
            }

            return this.warningChain;
        }
    }

    /**
     * Closes this statement, and frees resources.
     * 
     * @param calledExplicitly
     *            was this called from close()?
     * 
     * @throws SQLException
     *             if an error occurs
     */
    protected void realClose(boolean calledExplicitly, boolean closeOpenResults) throws SQLException {
        MySQLConnection locallyScopedConn = this.connection;

        if (locallyScopedConn == null || this.isClosed) {
            return; // already closed
        }

        // do it ASAP to reduce the chance of calling this method concurrently from ConnectionImpl.closeAllOpenStatements()
        if (!locallyScopedConn.getDontTrackOpenResources()) {
            locallyScopedConn.unregisterStatement(this);
        }

        if (this.useUsageAdvisor) {
            if (!calledExplicitly) {
                String message = Messages.getString("Statement.63") + Messages.getString("Statement.64");

                this.eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_WARN, "", this.currentCatalog, this.connectionId, this.getId(), -1,
                        System.currentTimeMillis(), 0, Constants.MILLIS_I18N, null, this.pointOfOrigin, message));
            }
        }

        if (closeOpenResults) {
            closeOpenResults = !(this.holdResultsOpenOverClose || this.connection.getDontTrackOpenResources());
        }

        if (closeOpenResults) {
            if (this.results != null) {

                try {
                    this.results.close();
                } catch (Exception ex) {
                }
            }

            if (this.generatedKeysResults != null) {

                try {
                    this.generatedKeysResults.close();
                } catch (Exception ex) {
                }
            }

            closeAllOpenResults();
        }

        this.isClosed = true;

        this.results = null;
        this.generatedKeysResults = null;
        this.connection = null;
        this.warningChain = null;
        this.openResults = null;
        this.batchedGeneratedKeys = null;
        this.localInfileInputStream = null;
        this.pingTarget = null;
    }

    /**
     * setCursorName defines the SQL cursor name that will be used by subsequent
     * execute methods. This name can then be used in SQL positioned
     * update/delete statements to identify the current row in the ResultSet
     * generated by this statement. If a database doesn't support positioned
     * update/delete, this method is a no-op.
     * 
     * <p>
     * <b>Note:</b> This MySQL driver does not support cursors.
     * </p>
     * 
     * @param name
     *            the new cursor name
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public void setCursorName(String name) throws SQLException {
        // No-op
    }

    /**
     * If escape scanning is on (the default), the driver will do escape
     * substitution before sending the SQL to the database.
     * 
     * @param enable
     *            true to enable; false to disable
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public void setEscapeProcessing(boolean enable) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            this.doEscapeProcessing = enable;
        }
    }

    /**
     * JDBC 2.0 Give a hint as to the direction in which the rows in a result
     * set will be processed. The hint applies only to result sets created using
     * this Statement object. The default value is ResultSet.FETCH_FORWARD.
     * 
     * @param direction
     *            the initial direction for processing rows
     * 
     * @exception SQLException
     *                if a database-access error occurs or direction is not one
     *                of ResultSet.FETCH_FORWARD, ResultSet.FETCH_REVERSE, or
     *                ResultSet.FETCH_UNKNOWN
     */
    public void setFetchDirection(int direction) throws SQLException {
        switch (direction) {
            case java.sql.ResultSet.FETCH_FORWARD:
            case java.sql.ResultSet.FETCH_REVERSE:
            case java.sql.ResultSet.FETCH_UNKNOWN:
                break;

            default:
                throw SQLError.createSQLException(Messages.getString("Statement.5"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }
    }

    /**
     * JDBC 2.0 Give the JDBC driver a hint as to the number of rows that should
     * be fetched from the database when more rows are needed. The number of
     * rows specified only affects result sets created using this statement. If
     * the value specified is zero, then the hint is ignored. The default value
     * is zero.
     * 
     * @param rows
     *            the number of rows to fetch
     * 
     * @exception SQLException
     *                if a database-access error occurs, or the condition 0
     *                &lt;= rows &lt;= this.getMaxRows() is not satisfied.
     */
    public void setFetchSize(int rows) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (((rows < 0) && (rows != Integer.MIN_VALUE)) || ((this.maxRows > 0) && (rows > this.getMaxRows()))) {
                throw SQLError.createSQLException(Messages.getString("Statement.7"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }

            this.fetchSize = rows;
        }
    }

    public void setHoldResultsOpenOverClose(boolean holdResultsOpenOverClose) {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                this.holdResultsOpenOverClose = holdResultsOpenOverClose;
            }
        } catch (SQLException e) {
            // FIXME: can't break interface at this point
        }
    }

    /**
     * Sets the maxFieldSize
     * 
     * @param max
     *            the new max column size limit; zero means unlimited
     * 
     * @exception SQLException
     *                if size exceeds buffer size
     */
    public void setMaxFieldSize(int max) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (max < 0) {
                throw SQLError.createSQLException(Messages.getString("Statement.11"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }

            int maxBuf = (this.connection != null) ? this.connection.getMaxAllowedPacket() : MysqlIO.getMaxBuf();

            if (max > maxBuf) {
                throw SQLError.createSQLException(Messages.getString("Statement.13", new Object[] { Long.valueOf(maxBuf) }),
                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }

            this.maxFieldSize = max;
        }
    }

    /**
     * Set the maximum number of rows
     * 
     * @param max
     *            the new max rows limit; zero means unlimited
     * 
     * @exception SQLException
     *                if a database access error occurs
     * 
     * @see getMaxRows
     */
    public void setMaxRows(int max) throws SQLException {
        setLargeMaxRows(max);
    }

    /**
     * Sets the queryTimeout limit
     * 
     * @param seconds
     *            -
     *            the new query timeout limit in seconds
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public void setQueryTimeout(int seconds) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (seconds < 0) {
                throw SQLError.createSQLException(Messages.getString("Statement.21"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }

            this.timeoutInMillis = seconds * 1000;
        }
    }

    /**
     * Sets the concurrency for result sets generated by this statement
     * 
     * @param concurrencyFlag
     */
    void setResultSetConcurrency(int concurrencyFlag) {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                this.resultSetConcurrency = concurrencyFlag;
            }
        } catch (SQLException e) {
            // FIXME: Can't break interface atm, we'll get the exception later when you try and do something useful with a closed statement...
        }
    }

    /**
     * Sets the result set type for result sets generated by this statement
     * 
     * @param typeFlag
     */
    void setResultSetType(int typeFlag) {
        try {
            synchronized (checkClosed().getConnectionMutex()) {
                this.resultSetType = typeFlag;
            }
        } catch (SQLException e) {
            // FIXME: Can't break interface atm, we'll get the exception later when you try and do something useful with a closed statement...
        }
    }

    protected void getBatchedGeneratedKeys(java.sql.Statement batchedStatement) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.retrieveGeneratedKeys) {
                java.sql.ResultSet rs = null;

                try {
                    rs = batchedStatement.getGeneratedKeys();

                    while (rs.next()) {
                        this.batchedGeneratedKeys.add(new ByteArrayRow(new byte[][] { rs.getBytes(1) }, getExceptionInterceptor()));
                    }
                } finally {
                    if (rs != null) {
                        rs.close();
                    }
                }
            }
        }
    }

    protected void getBatchedGeneratedKeys(int maxKeys) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.retrieveGeneratedKeys) {
                java.sql.ResultSet rs = null;

                try {
                    if (maxKeys == 0) {
                        rs = getGeneratedKeysInternal();
                    } else {
                        rs = getGeneratedKeysInternal(maxKeys);
                    }

                    while (rs.next()) {
                        this.batchedGeneratedKeys.add(new ByteArrayRow(new byte[][] { rs.getBytes(1) }, getExceptionInterceptor()));
                    }
                } finally {
                    this.isImplicitlyClosingResults = true;
                    try {
                        if (rs != null) {
                            rs.close();
                        }
                    } finally {
                        this.isImplicitlyClosingResults = false;
                    }
                }
            }
        }
    }

    private boolean useServerFetch() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.connection.isCursorFetchEnabled() && this.fetchSize > 0 && this.resultSetConcurrency == ResultSet.CONCUR_READ_ONLY
                    && this.resultSetType == ResultSet.TYPE_FORWARD_ONLY;
        }
    }

    public boolean isClosed() throws SQLException {
        MySQLConnection locallyScopedConn = this.connection;
        if (locallyScopedConn == null) {
            return true;
        }
        synchronized (locallyScopedConn.getConnectionMutex()) {
            return this.isClosed;
        }
    }

    private boolean isPoolable = true;

    public boolean isPoolable() throws SQLException {
        return this.isPoolable;
    }

    public void setPoolable(boolean poolable) throws SQLException {
        this.isPoolable = poolable;
    }

    /**
     * @see java.sql.Wrapper#isWrapperFor(Class)
     */
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        checkClosed();

        // This works for classes that aren't actually wrapping anything
        return iface.isInstance(this);
    }

    /**
     * @see java.sql.Wrapper#unwrap(Class)
     */
    public <T> T unwrap(Class<T> iface) throws java.sql.SQLException {
        try {
            // This works for classes that aren't actually wrapping anything
            return iface.cast(this);
        } catch (ClassCastException cce) {
            throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }
    }

    protected static int findStartOfStatement(String sql) {
        int statementStartPos = 0;

        if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) {
            statementStartPos = sql.indexOf("*/");

            if (statementStartPos == -1) {
                statementStartPos = 0;
            } else {
                statementStartPos += 2;
            }
        } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--") || StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) {
            statementStartPos = sql.indexOf('\n');

            if (statementStartPos == -1) {
                statementStartPos = sql.indexOf('\r');

                if (statementStartPos == -1) {
                    statementStartPos = 0;
                }
            }
        }

        return statementStartPos;
    }

    private InputStream localInfileInputStream;

    protected final boolean version5013OrNewer;

    public InputStream getLocalInfileInputStream() {
        return this.localInfileInputStream;
    }

    public void setLocalInfileInputStream(InputStream stream) {
        this.localInfileInputStream = stream;
    }

    public void setPingTarget(PingTarget pingTarget) {
        this.pingTarget = pingTarget;
    }

    public ExceptionInterceptor getExceptionInterceptor() {
        return this.exceptionInterceptor;
    }

    protected boolean containsOnDuplicateKeyInString(String sql) {
        return getOnDuplicateKeyLocation(sql, this.connection.getDontCheckOnDuplicateKeyUpdateInSQL(), this.connection.getRewriteBatchedStatements(),
                this.connection.isNoBackslashEscapesSet()) != -1;
    }

    protected static int getOnDuplicateKeyLocation(String sql, boolean dontCheckOnDuplicateKeyUpdateInSQL, boolean rewriteBatchedStatements,
            boolean noBackslashEscapes) {
        return dontCheckOnDuplicateKeyUpdateInSQL && !rewriteBatchedStatements ? -1 : StringUtils.indexOfIgnoreCase(0, sql, ON_DUPLICATE_KEY_UPDATE_CLAUSE,
                "\"'`", "\"'`", noBackslashEscapes ? StringUtils.SEARCH_MODE__MRK_COM_WS : StringUtils.SEARCH_MODE__ALL);
    }

    private boolean closeOnCompletion = false;

    public void closeOnCompletion() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            this.closeOnCompletion = true;
        }
    }

    public boolean isCloseOnCompletion() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            return this.closeOnCompletion;
        }
    }

    /**
     * JDBC 4.2
     * Same as {@link #executeBatch()} but returns long[] instead of int[].
     */
    public long[] executeLargeBatch() throws SQLException {
        return executeBatchInternal();
    }

    /**
     * JDBC 4.2
     * Same as {@link #executeUpdate(String)} but returns long instead of int.
     */
    public long executeLargeUpdate(String sql) throws SQLException {
        return executeUpdateInternal(sql, false, false);
    }

    /**
     * JDBC 4.2
     * Same as {@link #executeUpdate(String, int)} but returns long instead of int.
     */
    public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        return executeUpdateInternal(sql, false, autoGeneratedKeys == java.sql.Statement.RETURN_GENERATED_KEYS);
    }

    /**
     * JDBC 4.2
     * Same as {@link #executeUpdate(String, int[])} but returns long instead of int.
     */
    public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
        return executeUpdateInternal(sql, false, columnIndexes != null && columnIndexes.length > 0);
    }

    /**
     * JDBC 4.2
     * Same as {@link #executeUpdate(String, String[])} but returns long instead of int.
     */
    public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException {
        return executeUpdateInternal(sql, false, columnNames != null && columnNames.length > 0);
    }

    /**
     * JDBC 4.2
     * Same as {@link #getMaxRows()} but returns long instead of int.
     */
    public long getLargeMaxRows() throws SQLException {
        // Max rows is limited by MySQLDefs.MAX_ROWS anyway...
        return getMaxRows();
    }

    /**
     * JDBC 4.2
     * Same as {@link #getUpdateCount()} but returns long instead of int;
     */
    public long getLargeUpdateCount() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if (this.results == null) {
                return -1;
            }

            if (this.results.reallyResult()) {
                return -1;
            }

            return this.results.getUpdateCount();
        }
    }

    /**
     * JDBC 4.2
     * Same as {@link #setMaxRows(int)} but accepts a long value instead of an int.
     */
    public void setLargeMaxRows(long max) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            if ((max > MysqlDefs.MAX_ROWS) || (max < 0)) {
                throw SQLError.createSQLException(Messages.getString("Statement.15") + max + " > " + MysqlDefs.MAX_ROWS + ".",
                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }

            if (max == 0) {
                max = -1;
            }

            this.maxRows = (int) max;
        }
    }

    boolean isCursorRequired() throws SQLException {
        return false;
    }
}