File: tutorial.html

package info (click to toggle)
mysql%2B%2B 3.0.0-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 10,328 kB
  • ctags: 9,487
  • sloc: cpp: 33,486; sh: 3,091; perl: 809; makefile: 683
file content (1980 lines) | stat: -rw-r--r-- 109,737 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>3.Tutorial</title><link rel="stylesheet" href="tangentsoft.css" type="text/css"><meta name="generator" content="DocBook XSL Stylesheets V1.69.1"><link rel="start" href="index.html" title="MySQL++ v3.0.0 User Manual"><link rel="up" href="index.html" title="MySQL++ v3.0.0 User Manual"><link rel="prev" href="overview.html" title="2.Overview"><link rel="next" href="tquery.html" title="4.Template Queries"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">3.Tutorial</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="overview.html">Prev</a></td><th width="60%" align="center"></th><td width="20%" align="right"><a accesskey="n" href="tquery.html">Next</a></td></tr></table><hr></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="tutorial"></a>3.Tutorial</h2></div></div></div><p>This tutorial is meant to give you a jump start in using
  MySQL++. While it is a very complicated and powerful library,
  it&#8217;s possible to make quite functional programs without tapping
  but a fraction of its power. This section will introduce you to the
  most useful fraction.</p><p>This tutorial assumes you know C++ fairly well, in particular
  the Standard Template Library (STL) and exceptions.</p><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="examples"></a>3.1.Running the Examples</h3></div></div></div><p>All of the examples are complete running programs. If you
    built the library from source, the examples should have been built
    as well. If you use RPMs instead, the example programs&#8217; source
    code and a simplified <code class="filename">Makefile</code> are in the
    <code class="filename">mysql++-devel</code> package. They are typically
    installed in
    <code class="filename">/usr/share/doc/mysql++-devel-*/examples</code>, but it
    can vary on different Linuxes.</p><p>Before you get started, please read through any of the
    <code class="filename">README*</code> files included with the MySQL++
    distribution that are relevant to your platform. We won&#8217;t
    repeat all of that here.</p><p>Most of the examples require a test database, created by
    <code class="filename">resetdb</code>. You can run it like so:</p><pre class="screen">resetdb [-s server_addr] [-u user] [-p password]</pre><p>Actually, there&#8217;s a problem with that. It assumes that
    the MySQL++ library is already installed in a directory that the
    operating system&#8217;s dynamic linker can find. (MySQL++ is almost
    never built statically.) Unless you&#8217;re installing from RPMs,
    you&#8217;ve had to build the library from source, and you should
    run at least a few of the examples before installing the library to
    be sure it&#8217;s working correctly. Since your operating
    system&#8217;s dynamic linkage system can&#8217;t find the MySQL++
    libraries without help until they&#8217;re installed, we&#8217;ve
    created a few helper scripts to help run the examples.</p><p>MySQL++ comes with the <code class="filename">exrun</code> shell script
    for Unixy systems, and the <code class="filename">exrun.bat</code> batch file
    for Windows. You pass the example program and its arguments to the
    <code class="filename">exrun</code> helper, which sets up the library search
    path so that it will find the as-yet uninstalled version of the
    MySQL++ library first. So on a Unixy system, the above command
    becomes:</p><pre class="screen">./exrun resetdb [-s server_addr] [-u user] [-p password]</pre><p>See <code class="filename">README.examples</code> for more
    details.</p><p>All of the program arguments are optional.</p><p>If you don&#8217;t give <code class="option">-s</code>, the underlying
    MySQL C API assumes the server is on the local machine.  Depending
    on how the C API library and the server are configured, it can use
    any of several different IPC methods to contact the server. You can
    instead specify how to contact the server yourself, with the method
    depending on the value you give for the server address:</p><div class="itemizedlist"><ul type="disc"><li><p><span class="emphasis"><em>localhost</em></span> &#8212; this is the
        default; it doesn&#8217;t buy you anything</p></li><li><p>On Windows, a simple period tells the underlying MySQL C
        API to use named pipes, if it&#8217;s available.</p></li><li><p><span class="emphasis"><em>172.20.0.252:12345</em></span>
        &#8212; this would connect to IP address
        <code class="computeroutput">172.20.0.252</code> on TCP port
        <code class="computeroutput">12345</code>.</p></li><li><p><span class="emphasis"><em>my.server.name:svc_name</em></span> &#8212; this
        would first look up TCP service name
        <code class="computeroutput">svc_name</code> in your system&#8217;s
        network services database (<code class="filename">/etc/services</code> on
        Unixy systems, and something like
        <code class="filename">c:\windows\system32\drivers\etc\services</code> on
        modern Windows variants). If it finds an entry for the service,
        it then tries to connect to that port on the domain name
        given.</p></li></ul></div><p>You can mix symbolic host and service names in any
    combination. If the name doesn&#8217;t contain a colon, it uses the
    default port, 3306.</p><p>If you don&#8217;t give <code class="option">-u</code>, it assumes your
    user name on the local machine is the same as your user name on the
    database server.</p><p>If you don&#8217;t give <code class="option">-p</code>, it will assume
    the MySQL user doesn&#8217;t have a password, which had better not
    be the case.  It&#8217;s a wild world out there; play safe,
    kids.</p><p>A typical invocation is:</p><pre class="screen">exrun.bat resetdb -u mydbuser -p nunyabinness</pre><p>For <code class="filename">resetdb</code>, the user name needs to be
    for an account with permission to create databases. Once the
    database is created, you can use any account that has read and write
    permissions for the sample database,
    <code class="filename">mysql_cpp_data</code>.</p><p>You may also have to re-run <code class="filename">resetdb</code>
    after running some of the other examples, as they change the
    database.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="simple"></a>3.2.A Simple Example</h3></div></div></div><p>The following example demonstrates how to open a connection,
    execute a simple query, and display the results. This is
    <code class="filename">examples/simple1.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"

#include &lt;mysql++.h&gt;

#include &lt;iostream&gt;
#include &lt;iomanip&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    // Connect to the sample database.
    mysqlpp::Connection conn(false);
    if (conn.connect(db, server, user, pass)) {
        // Retrieve a subset of the sample stock table set up by resetdb
        // and display it.
        mysqlpp::Query query = conn.query("select item from stock");
        if (mysqlpp::StoreQueryResult res = query.store()) {
            cout &lt;&lt; "We have:" &lt;&lt; endl;
            for (size_t i = 0; i &lt; res.num_rows(); ++i) {
                cout &lt;&lt; '\t' &lt;&lt; res[i][0] &lt;&lt; endl;
            }
        }
        else {
            cerr &lt;&lt; "Failed to get item list: " &lt;&lt; query.error() &lt;&lt; endl;
            return 1;
        }

        return 0;
    }
    else {
        cerr &lt;&lt; "DB connection failed: " &lt;&lt; conn.error() &lt;&lt; endl;
        return 1;
    }
}
</pre><p>This example simply gets the entire "item" column from the
    example table, and prints those values out.</p><p>Notice that MySQL++&#8217;s <tt><a href="../refman/classmysqlpp_1_1StoreQueryResult.html">StoreQueryResult</a></tt> derives from
    <code class="classname">std::vector</code>, and <tt><a href="../refman/classmysqlpp_1_1Row.html">Row</a></tt> provides an interface that makes it a
    <code class="classname">vector</code> work-alike. This means you can access
    elements with subscript notation, walk through them with iterators,
    run STL algorithms on them, etc.</p><p><code class="classname">Row</code> provides a little more in this area
    than a plain old <code class="classname">vector</code>: you can also access
    fields by name using subscript notation.</p><p>The only thing that isn&#8217;t explicit in the code above is
    that we delegate command line argument parsing to
    <code class="function">parse_command_line()</code> in the
    <code class="filename">excommon</code> module. This function exists to give
    the examples a consistent interface, not to hide important details.
    You can treat it like a black box: it takes <code class="varname">argc</code>
    and <code class="varname">argv</code> as inputs and sends back database
    connection parameters.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="simple2"></a>3.3.A More Complicated Example</h3></div></div></div><p>The <code class="filename">simple1</code> example above was pretty
    trivial. Let&#8217;s get a little deeper. Here is
    <code class="filename">examples/simple2.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"

#include &lt;mysql++.h&gt;

#include &lt;iostream&gt;
#include &lt;iomanip&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    // Connect to the sample database.
    mysqlpp::Connection conn(false);
    if (conn.connect(db, server, user, pass)) {
        // Retrieve the sample stock table set up by resetdb
        mysqlpp::Query query = conn.query("select * from stock");
        mysqlpp::StoreQueryResult res = query.store();

        // Display results
        if (res) {
            // Display header
            cout.setf(ios::left);
            cout &lt;&lt; setw(31) &lt;&lt; "Item" &lt;&lt;
                    setw(10) &lt;&lt; "Num" &lt;&lt;
                    setw(10) &lt;&lt; "Weight" &lt;&lt;
                    setw(10) &lt;&lt; "Price" &lt;&lt;
                    "Date" &lt;&lt; endl &lt;&lt; endl;

            // Get each row in result set, and print its contents
            for (size_t i = 0; i &lt; res.num_rows(); ++i) {
                cout &lt;&lt; setw(30) &lt;&lt; res[i]["item"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; res[i]["num"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; res[i]["weight"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; res[i]["price"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; res[i]["sdate"] &lt;&lt;
                        endl;
            }
        }
        else {
            cerr &lt;&lt; "Failed to get stock table: " &lt;&lt; query.error() &lt;&lt; endl;
            return 1;
        }

        return 0;
    }
    else {
        cerr &lt;&lt; "DB connection failed: " &lt;&lt; conn.error() &lt;&lt; endl;
        return 1;
    }
}
</pre><p>The main point of this example is that we&#8217;re accessing
    fields in the row objects by name, instead of index. This is slower,
    but obviously clearer. We&#8217;re also printing out the entire
    table, not just one column.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="headers"></a>3.4.#including MySQL++ Headers</h3></div></div></div><p>You&#8217;ll notice above that we&#8217;re including
    <code class="filename">mysql++.h</code> in the examples. There are many
    headers in MySQL++, but this brings in all but one of them for you.
    MySQL++ has a pretty cohesive design: it doesn&#8217;t have very
    many pieces that are truly independent of the others. So,
    there&#8217;s not much advantage in including the few headers you
    think you need individually: you&#8217;re likely to also drag in all
    the rest indirectly.</p><p>The one header that <code class="filename">mysql++.h</code>
    doesn&#8217;t
    bring in for you is <code class="filename">ssqls.h</code>, which is only
    useful if you use the optional <a href="tutorial.html#ssqlsintro">Specialized SQL Structures</a>
    feature.</p><p>By default on Unixy systems, MySQL++ installs its headers into
    a <code class="filename">mysql++</code> subdirectory of one of the main
    system include directories, either <code class="filename">/usr/include</code>
    or <code class="filename">/usr/local/include</code>. Since it&#8217;s typical
    for either or both of these directories to be in your
    program&#8217;s include path already, you might be wondering if you
    can include the main MySQL++ header like this:</p><pre class="programlisting">#include &lt;mysql++/mysql++.h&gt;</pre><p>The answer is, yes you can. You don&#8217;t need to do anything
    special to make it work.</p><p>Since MySQL is usually installed in much the same way
    (<code class="filename">/usr/include/mysql</code> is common, for example),
    you might then ask if you can get away without having the MySQL C
    API header directory to your program&#8217;s include path. You can,
    but <code class="filename">mysql++.h</code> requires a little help from your
    program to find the C API headers when you do this:</p><pre class="programlisting">#define MYSQLPP_MYSQL_HEADERS_BURIED
#include &lt;mysql++/mysql++.h&gt;</pre><p>This tells it to prefix all includes for C API headers with
    <code class="filename">mysql/</code>.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="exceptions"></a>3.5.Exceptions</h3></div></div></div><p>By default, MySQL++ uses exceptions to signal errors. Most
    of the examples have a full set of exception handlers. This is
    worthy of emulation.</p><p>All of MySQL++&#8217;s custom exceptions
    derive from a common base class, <tt><a href="../refman/classmysqlpp_1_1Exception.html">Exception</a></tt>. That in turn derives from Standard C++&#8217;s
    <code class="classname">std::exception</code> class. Since the library
    can indirectly cause exceptions to come from the Standard
    C++ Library, it&#8217;s possible to catch all exceptions from
    MySQL++ by just catching <code class="classname">std::exception</code>.
    However, it&#8217;s better to have individual catch blocks
    for each of the concrete exception types that you expect, and
    add a handler for either <code class="classname">Exception</code>
    or <code class="classname">std::exception</code> to act as a
    &#8220;catch-all&#8221; for unexpected exceptions.</p><p>Most of these exceptions are optional. When exceptions
    are disabled on a MySQL++ object, it signals errors in some
    other way, typically by returning an error code or setting
    an error flag. Classes that support this feature derive from
    <tt><a href="../refman/classmysqlpp_1_1OptionalExceptions.html">OptionalExceptions</a></tt>. Moreover,
    when such an object creates another object that also derives from
    this interface, it passes on its exception flag. Since everything
    flows from the <tt><a href="../refman/classmysqlpp_1_1Connection.html">Connection</a></tt> object,
    disabling exceptions on it at the start of the program disables
    all optional exceptions. You can see this technique at work in
    the <code class="filename">simple[1-3]</code> examples, which keeps them,
    well, simple.</p><p>Real-world code typically can&#8217;t afford to lose
    out on the additional information and control offered by
    exceptions. But at the same time, it is still sometimes useful
    to disable exceptions temporarily. To do this, put the section
    of code that you want to not throw exceptions inside a block,
    and create a <tt><a href="../refman/classmysqlpp_1_1NoExceptions.html">NoExceptions</a></tt> object
    at the top of that block. When created, it saves the exception
    flag of the <code class="classname">OptionalExceptions</code> derivative
    you pass to it, and then disables exceptions on it. When the
    <code class="classname">NoExceptions</code> object goes out of scope
    at the end of the block, it restores the exceptions flag to its
    previous state:</p><pre class="programlisting">mysqlpp::Connection con(...); // exceptions enabled

{
  mysqlpp::NoExceptions ne(con);
  if (!con.select_db("a_db_that_might_not_exist_yet")) {
    // Our DB doesn't exist yet, so create and select it here; no need
    // to push handling of this case way off in an exception handler.
  }
}</pre><p>When one <code class="classname">OptionalExceptions</code> derivative
    passes its exceptions flag to another such object, it is only
    passing a copy; the two objects&#8217; flags operate independently.
    There&#8217;s no way to globally enable or disable this flag on
    existing objects in a single call. If you&#8217;re using the
    <code class="classname">NoExceptions</code> feature and you&#8217;re
    still seeing optional exceptions thrown, you disabled exceptions
    on the wrong object. The exception thrower could be unrelated to
    the object you disabled exceptions on, it could be its parent,
    or it could be a child created before you disabled optional
    exceptions.</p><p>MySQL++ throws some exceptions unconditionally:</p><div class="itemizedlist"><ul type="disc"><li><p>The largest set of non-optional exceptions are
      those from the Standard C++ Library. For instance, if your code
      said &#8220;<code class="varname">row[21]</code>&#8221; on a row containing
      only 5 fields, the <code class="classname">std::vector</code> underlying
      the row object will throw an exception. (It will, that is, if it
      conforms to the standard.) You might consider wrapping your
      program&#8217;s main loop in a try block catching
      <code class="classname">std::exception</code>s, just in case you trigger
      one of these exceptions.</p></li><li><p><tt><a href="../refman/classmysqlpp_1_1String.html">String</a></tt> will always
      throw <tt><a href="../refman/classmysqlpp_1_1BadConversion.html">BadConversion</a></tt> when you ask it
      to do an improper type conversion. For example, you&#8217;ll get
      an exception if you try to convert &#8220;1.25&#8221; to
      <span class="type">int</span>, but not when you convert &#8220;1.00&#8221; to
      <span class="type">int</span>. In the latter case, MySQL++ knows that it can
      safely throw away the fractional part.</p></li><li><p>If you use template queries and don&#8217;t pass
      enough parameters when instantiating the template,
      <code class="classname">Query</code> will throw a <tt><a href="../refman/classmysqlpp_1_1BadParamCount.html">BadParamCount</a></tt> exception.</p></li><li><p>If you use a C++ data type in a query
      that MySQL++ doesn&#8217;t know to convert to SQL, MySQL++
      will throw a <tt><a href="../refman/classmysqlpp_1_1TypeLookupFailed.html">TypeLookupFailed</a></tt>
      exception. It typically happens with <a href="ssqls.html" title="5.Specialized SQL Structures">Section5, &#8220;Specialized SQL Structures&#8221;</a>,
      especially when using data types other than the ones defined
      in <code class="filename">lib/sql_types.h</code>.</p></li></ul></div><p>It&#8217;s educational to modify the examples to force
    exceptions. For instance, misspell a field name, use an out-of-range
    index, or change a type to force a <code class="classname">String</code>
    conversion error.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="qescape"></a>3.6.Quoting and Escaping</h3></div></div></div><p>SQL syntax often requires certain data to be quoted. Consider
    this query:</p><pre class="programlisting">
SELECT * FROM stock WHERE item = 'Hotdog Buns' </pre><p>Because the string &#8220;Hotdog Buns&#8221; contains a space,
    it must be quoted. With MySQL++, you don&#8217;t have to add these
    quote marks manually:</p><pre class="programlisting">
string s = "Hotdog Buns";
query &lt;&lt; "SELECT * FROM stock WHERE item = " &lt;&lt; quote_only &lt;&lt; s; </pre><p>That code produces the same query string as in the previous
    example. We used the MySQL++ <span class="type">quote_only</span> manipulator,
    which causes single quotes to be added around the next item inserted
    into the stream. This works for any type of data that can be
    converted to MySQL++&#8217;s <tt><a href="../refman/classmysqlpp_1_1SQLTypeAdapter.html">SQLTypeAdapter</a></tt> type, plus the <tt><a href="../refman/classmysqlpp_1_1Set.html">Set</a></tt> template. <a href="tutorial.html#ssqlsintro">Specialized SQL Structures</a>
    also use these manipulators internally.</p><p>Quoting is pretty simple, but SQL syntax also often requires
    that certain characters be &#8220;escaped&#8221;. Imagine if the
    string in the previous example was &#8220;Frank's Brand Hotdog
    Buns&#8221; instead. The resulting query would be:</p><pre class="programlisting">
SELECT * FROM stock WHERE item = 'Frank's Brand Hotdog Buns' </pre><p>That&#8217;s not valid SQL syntax. The correct syntax is:</p><pre class="programlisting">
SELECT * FROM stock WHERE item = 'Frank''s Brand Hotdog Buns' </pre><p>As you might expect, MySQL++ provides that feature, too,
    through its <span class="type">escape</span> manipulator. But here, we want both
    quoting and escaping. That brings us to the most widely useful
    manipulator:</p><pre class="programlisting">
string s = "Frank's Brand Hotdog Buns";
query &lt;&lt; "SELECT * FROM stock WHERE item = " &lt;&lt; quote &lt;&lt; s; </pre><p>The <span class="type">quote</span> manipulator both quotes strings and
    escapes any characters that are special in SQL.</p><p>MySQL++ provides other manipulators as well. See the <a href="../refman/manip_8h.html" target="_top">manip.h</a> page in the <a href="../refman/index.html" target="_top">reference manual</a>.</p><p>It&#8217;s important to realize that MySQL++&#8217;s quoting
    and escaping mechanism is type-aware. Manipulators have no effect
    unless you insert the manipulator into a
    <code class="classname">Query</code> or <tt><a href="../refman/classmysqlpp_1_1SQLQueryParms.html">SQLQueryParms</a></tt> stream.
    <sup>[<a name="id2873328" href="#ftn.id2873328">1</a>]</sup> Also, values are only quoted and/or
    escaped if they are of a data type that may need it. For example,
    <tt><a href="../refman/structmysqlpp_1_1Date.html">Date</a></tt> must be quoted but
    never needs to be escaped, and integer types need neither quoting
    nor escaping. Manipulators are suggestions to the library, not
    commands: MySQL++ will ignore these suggestions if it knows it
    won&#8217;t result in syntactically-incorrect SQL.</p><p>It&#8217;s also important to realize that quoting and escaping
    in <code class="classname">Query</code> streams and template queries is
    never implicit.<sup>[<a name="id2873362" href="#ftn.id2873362">2</a>]</sup> You must use manipulators
    and template query flags as necessary to tell MySQL++ where quoting
    and escaping is necessary. It would be nice if MySQL++ could do
    quoting and escaping implicitly based on data type, but this
    isn&#8217;t possible in all cases.<sup>[<a name="whyexpmanip" href="#ftn.whyexpmanip">3</a>]</sup> Since
    MySQL++ can&#8217;t reliably guess when quoting and escaping is
    appropriate, and the programmer doesn&#8217;t need
    to<sup>[<a name="id2873415" href="#ftn.id2873415">4</a>]</sup>, MySQL++ makes you
    tell it.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="ssqlsintro"></a>3.7.Specialized SQL Structures</h3></div></div></div><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="ssqls1"></a>Retrieving data</h4></div></div></div><p>The next example introduces one of the most powerful
      features of MySQL++: Specialized SQL Structures (SSQLS). This is
      <code class="filename">examples/ssqls1.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"
#include "stock.h"

#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {                       
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Retrieve just the item column from the stock table, and store
        // the data in a vector of 'stock' SSQLS structures.  See the
        // user manual for the consequences arising from this quiet
        // ability to store a subset of the table in the stock SSQLS.
        mysqlpp::Query query = con.query("select item from stock");
        vector&lt;stock&gt; res;
        query.storein(res);

        // Display the items
        cout &lt;&lt; "We have:" &lt;&lt; endl;
        vector&lt;stock&gt;::iterator it;
        for (it = res.begin(); it != res.end(); ++it) {
            cout &lt;&lt; '\t' &lt;&lt; it-&gt;item &lt;&lt; endl;
        }
    }
    catch (const mysqlpp::BadQuery&amp; er) {
        // Handle any query errors
        cerr &lt;&lt; "Query error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::BadConversion&amp; er) {
        // Handle bad conversions; e.g. type mismatch populating 'stock'
        cerr &lt;&lt; "Conversion error: " &lt;&lt; er.what() &lt;&lt; endl &lt;&lt;
                "\tretrieved data size: " &lt;&lt; er.retrieved &lt;&lt;
                ", actual size: " &lt;&lt; er.actual_size &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }

    return 0;
}
</pre><p>Here is the stock.h header used by that example, and
      many others:</p><pre class="programlisting">#include &lt;mysql++.h&gt;
#include &lt;ssqls.h&gt;

// The following is calling a very complex macro which will create
// "struct stock", which has the member variables:
//
//   sql_char item;
//   ...
//   Null&lt;sql_mediumtext&gt; description;
//
// plus methods to help populate the class from a MySQL row.  See the
// SSQLS sections in the user manual for further details.
sql_create_6(stock,
    1, 6, // The meaning of these values is covered in the user manual
    mysqlpp::sql_char, item,
    mysqlpp::sql_bigint, num,
    mysqlpp::sql_double, weight,
    mysqlpp::sql_double, price,
    mysqlpp::sql_date, sdate,
    mysqlpp::Null&lt;mysqlpp::sql_mediumtext&gt;, description)

</pre><p>This example produces the same output as
      <code class="filename">simple1.cpp</code> (see <a href="tutorial.html#simple" title="3.2.A Simple Example">Section3.2, &#8220;A Simple Example&#8221;</a>),
      but it uses higher-level data structures paralleling the
      database schema instead of MySQL++&#8217;s lower-level
      generic data structures. It also uses MySQL++&#8217;s <a href="tutorial.html#exceptions">exceptions</a> for error handling instead of doing
      everything inline. For small example programs like these, the
      overhead of SSQLS and exceptions doesn&#8217;t pay off very
      well, but in a real program, they end up working much better
      than hand-rolled code.</p><p>Notice that we are only pulling a single column from the
      <code class="varname">stock</code> table, but we are storing the rows in a
      <span class="type">std::vector&lt;stock&gt;</span>. It may strike you as
      inefficient to have five unused fields per record. It&#8217;s
      easily remedied by defining a subset SSQLS:</p><pre class="programlisting">
sql_create_1(stock_subset,
    1, 0,
    string, item)
    
vector&lt;stock_subset&gt; res;
query.storein(res);
// ...etc...</pre><p>MySQL++ is flexible about populating
      SSQLSes.<sup>[<a name="id2873562" href="#ftn.id2873562">5</a>]</sup> It works much like the Web,
      a design that&#8217;s enabled the development of the largest
      distributed system in the world. Just as a browser ignores
      tags and attributes it doesn&#8217;t understand, you can
      populate an SSQLS from a query result set containing columns
      that don&#8217;t exist in the SSQLS. And as a browser uses
      sensible defaults when the page doesn&#8217;t give explicit
      values, you can have an SSQLS with more fields defined than
      are in the query result set, and these SSQLS fields will get
      default values. (Zero for numeric types, <span class="type">false</span>
      for <span class="type">bool</span>, and a type-specific default for anything
      more complex, like <span class="type">mysqlpp::DateTime</span>.)</p><p>In more concrete terms, the example above is able to
      populate the <code class="classname">stock</code> objects using as
      much information as it has, and leave the remaining fields at
      their defaults. Conversely, you could also stuff the results
      of <code class="computeroutput">SELECT * FROM stock</code> into
      the <code class="classname">stock_subset</code> SSQLS declared above;
      the extra fields would just be ignored.</p><p>We're trading run-time efficiency for flexibility here,
      usually the right thing in a distributed system. Since MySQL is
      a networked database server, many uses of it will qualify as
      distributed systems. You can't count on being able to update
      both the server(s) and all the clients at the same time, so
      you have to make them flexible enough to cope with differences
      while the changes propagate. As long as the new database schema
      isn&#8217;t too grossly different from the old, your programs
      should continue to run until you get around to updating them
      to use the new schema.</p><p>There&#8217;s a danger that this quiet coping behavior
      may mask problems, but considering that the previous behavior
      was for the program to crash when the database schema got out
      of synch with the SSQLS definition, it&#8217;s likely to be
      taken as an improvement.</p></div><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="ssqls2"></a>Adding data</h4></div></div></div><p>SSQLS can also be used to add data to a table. This is
      <code class="filename">examples/ssqls2.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"
#include "stock.h"

#include &lt;iostream&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Create and populate a stock object.  We could also have used
        // the set() member, which takes the same parameters as this
        // constructor.
        stock row("Hot Dogs", 100, 1.5, 1.75,
                mysqlpp::sql_date("1998-09-25"), mysqlpp::null);

        // Form the query to insert the row into the stock table.
        mysqlpp::Query query = con.query();
        query.insert(row);

        // Show the query about to be executed.
        cout &lt;&lt; "Query: " &lt;&lt; query &lt;&lt; endl;

        // Execute the query.  We use execute() because INSERT doesn't
        // return a result set.
        query.execute();

        // Retrieve and print out the new table contents.
        print_stock_table(query);
    }
    catch (const mysqlpp::BadQuery&amp; er) {
        // Handle any query errors
        cerr &lt;&lt; "Query error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::BadConversion&amp; er) {  
        // Handle bad conversions
        cerr &lt;&lt; "Conversion error: " &lt;&lt; er.what() &lt;&lt; endl &lt;&lt;
                "\tretrieved data size: " &lt;&lt; er.retrieved &lt;&lt;
                ", actual size: " &lt;&lt; er.actual_size &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }

    return 0;
}
</pre><p>That&#8217;s all there is to it!</p><p>There is one subtlety: MySQL++ automatically quotes and
      escapes the data when building SQL queries using SSQLS structures.
      It&#8217;s efficient, too: MySQL++ is smart enough to apply
      quoting and escaping only for those data types that actually
      require it.</p><p>Because this example modifies the sample database, you
      may want to run resetdb after running this program.</p></div><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="ssqls3"></a>Modifying data</h4></div></div></div><p>It almost as easy to modify data with SSQLS. This is
      <code class="filename">examples/ssqls3.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"
#include "stock.h"

#include &lt;iostream&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Build a query to retrieve the stock item that has Unicode
        // characters encoded in UTF-8 form.
        mysqlpp::Query query = con.query(
                "select * from stock where item = \"Nrnberger Brats\"");

        // Retrieve the row, throwing an exception if it fails.
        mysqlpp::StoreQueryResult res = query.store();
        if (res.empty()) {
            throw mysqlpp::BadQuery("UTF-8 bratwurst item not found in "
                    "table, run resetdb");
        }

        // Because there should only be one row in the result set,
        // there's no point in storing the result in an STL container.
        // We can store the first row directly into a stock structure
        // because one of an SSQLS's constructors takes a Row object.
        stock row = res[0];

        // Create a copy so that the replace query knows what the
        // original values are.
        stock orig_row = row;

        // Change the stock object's item to use only 7-bit ASCII, and
        // to deliberately be wider than normal column widths printed
        // by print_stock_table().
        row.item = "Nuerenberger Bratwurst";

        // Form the query to replace the row in the stock table.
        query.update(orig_row, row);

        // Show the query about to be executed.
        cout &lt;&lt; "Query: " &lt;&lt; query &lt;&lt; endl;

        // Run the query with execute(), since UPDATE doesn't return a
        // result set.
        query.execute();

        // Retrieve and print out the new table contents.
        print_stock_table(query);
    }
    catch (const mysqlpp::BadQuery&amp; er) {
        // Handle any query errors
        cerr &lt;&lt; "Query error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::BadConversion&amp; er) {
        // Handle bad conversions
        cerr &lt;&lt; "Conversion error: " &lt;&lt; er.what() &lt;&lt; endl &lt;&lt;
                "\tretrieved data size: " &lt;&lt; er.retrieved &lt;&lt;
                ", actual size: " &lt;&lt; er.actual_size &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }

    return 0;
}
</pre><p>Don&#8217;t forget to run resetdb after running the
      example.</p></div><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="ssqls4"></a>Less-than-comparable</h4></div></div></div><p>SSQLS structures can be sorted and stored in STL associative
      containers as demonstrated in the next example. This is
      <code class="filename">examples/ssqls4.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"
#include "stock.h"

#include &lt;iostream&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Retrieve all rows from the stock table and put them in an
        // STL set.  Notice that this works just as well as storing them
        // in a vector, which we did in ssqls1.cpp.  It works because
        // SSQLS objects are less-than comparable.
        mysqlpp::Query query = con.query("select * from stock");
        set&lt;stock&gt; res;
        query.storein(res);

        // Display the result set.  Since it is an STL set and we set up
        // the SSQLS to compare based on the item column, the rows will
        // be sorted by item.
        print_stock_header(res.size());
        set&lt;stock&gt;::iterator it;
        cout.precision(3);
        for (it = res.begin(); it != res.end(); ++it) {
            print_stock_row(it-&gt;item.c_str(), it-&gt;num, it-&gt;weight,
                    it-&gt;price, it-&gt;sdate);
        }

        // Use set's find method to look up a stock item by item name.
        // This also uses the SSQLS comparison setup.
        it = res.find(stock("Hotdog Buns"));
        if (it != res.end()) {
            cout &lt;&lt; endl &lt;&lt; "Currently " &lt;&lt; it-&gt;num &lt;&lt;
                    " hotdog buns in stock." &lt;&lt; endl;
        }
        else {
            cout &lt;&lt; endl &lt;&lt; "Sorry, no hotdog buns in stock." &lt;&lt; endl;
        }
    }
    catch (const mysqlpp::BadQuery&amp; er) {
        // Handle any query errors
        cerr &lt;&lt; "Query error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::BadConversion&amp; er) {
        // Handle bad conversions
        cerr &lt;&lt; "Conversion error: " &lt;&lt; er.what() &lt;&lt; endl &lt;&lt;
                "\tretrieved data size: " &lt;&lt; er.retrieved &lt;&lt;
                ", actual size: " &lt;&lt; er.actual_size &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }

    return 0;
}
</pre><p>The <code class="methodname">find()</code> call works because
      of the way the SSQLS was declared. It&#8217;s properly covered
      elsewhere, but suffice it to say, the "1" in the declaration
      of <code class="classname">stock</code> above tells it that only the
      first field needs to be checked in comparing two SSQLSes. In
      database terms, this makes it the primary key. Therefore, when
      searching for a match, our exemplar only had to have its first
      field populated.</p><p>For more details on the SSQLS feature, see <a href="ssqls.html" title="5.Specialized SQL Structures">Section5, &#8220;Specialized SQL Structures&#8221;</a>.</p></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="sql_types"></a>3.8.C++ Equivalents of SQL Column Types</h3></div></div></div><p>The <code class="filename">sql_types.h</code> header declares typedefs
    for all MySQL column types. These typedefs all begin with
    <span class="type">sql_</span> and end with a lowercase version of the standard
    SQL type name. For instance, the MySQL++ typedef corresponding to
    <span class="type">TINYINT UNSIGNED</span> is
    <code class="classname">mysqlpp::sql_tinyint_unsigned</code>.  You do not
    have to use these typedefs; in this particular case, you might get
    away with using something as loose as <span class="type">int</span>.</p><p>The most obivious reason to use these typedefs is clarity.
    Someone reading code that uses these typedefs can&#8217;t be
    confused about what the corresponding SQL type is.</p><p>There&#8217;s also a correctness aspect to using these
    typedefs. The definitions of these types have changed over time as
    new, improved types have become available in MySQL++. For a past
    example, <span class="type">sql_tinyint</span> used to just be an alias for
    <span class="type">signed char</span>, but when MySQL++ began treating
    <span class="type">char</span> as a single-character string instead of an
    integer, we changed the <span class="type">sql_tinyint</span> typedef to be an
    alias for <span class="type">mysqlpp::tiny_int&lt;signed char&gt;</span>. Code
    using the type aliases changed over transparently, while code using
    what used to be the correct corresponding C++ type usually broke.
    This is likely to happen again in the future, too. One example that
    comes to mind is that <span class="type">sql_decimal</span> is currently an alias
    for <span class="type">double</span>, but SQL&#8217;s <span class="type">DECIMAL</span> type
    is a fixed-point data type, while <span class="type">double</span> is
    floating-point.  Thus, you lose accuracy when converting
    <span class="type">DECIMAL</span> column data to <span class="type">sql_decimal</span> right
    now. In the future, we may add a fixed-point data type to MySQL++;
    if we do, we&#8217;ll certainly change the tyepdef alias to use it
    instead of <span class="type">double</span>.</p><p>Most of these typedefs use standard C++ data types, but a few
    are aliases for a MySQL++ specific type. For instance, the SQL type
    <code class="classname">DATETIME</code> is mirrored in MySQL++ by
    <code class="classname">mysqlpp::DateTime</code>. For consistency,
    <code class="filename">sql_types.h</code> includes a typedef alias for
    <code class="classname">DateTime</code> called
    <code class="classname">mysqlpp::sql_datetime</code>.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="sql-null"></a>3.9.Handling SQL Nulls</h3></div></div></div><p>There is no equivalent of SQL&#8217;s null in the standard C++
    type system.</p><p>The primary distinction is one of type: in SQL, null is a
    column attribute, which affects whether that column can hold a SQL
    null. Just like the <span class="symbol">const</span> keyword in the C++ type
    system, this effectively doubles the number of SQL data types. To
    emulate this, MySQL++ provides the <tt><a href="../refman/classmysqlpp_1_1null.html">Null</a></tt> template to allow the creation of distinct
    &#8220;nullable&#8221; versions of existing C++ types. So for
    example, if you have a <span class="type">TINYINT UNSIGNED</span> column that can
    have nulls, the proper declaration for MySQL++ would be:</p><pre class="programlisting">
mysqlpp::Null&lt;mysqlpp::sql_tinyint_unsigned&gt; myfield;</pre><p>Template instantiations are first-class types in the C++
    language, on par with any other type. You can use
    <code class="classname">Null</code> template instantiations anywhere
    you&#8217;d use the plain version of that type. (You can see a
    complete list of <code class="classname">Null</code> template instantiations
    for all column types that MySQL understands at the top of
    <code class="filename">lib/type_info.cpp</code>.)</p><p>There&#8217;s a secondary distinction between SQL null and
    anything available in the standard C++ type system: SQL null is a
    distinct value, equal to nothing else. We can&#8217;t use
    C++&#8217;s <span class="symbol">NULL</span> for this because it is ambiguous,
    being equal to 0 in integer context. MySQL++ provides the global
    <code class="varname">null</code> object, which you can assign to a
    <code class="classname">Null</code> template instance to make it equal to
    SQL null:</p><pre class="programlisting">
myfield = mysqlpp::null;</pre><p>By default, MySQL++ enforces the uniqueness of SQL null at
    compile time. If you try to convert a SQL null to any other data
    type, the compiler will emit an error message saying something
    about <span class="type">CannotConvertNullToAnyOtherDataType</span>. It&#8217;s
    safe to insert a SQL null into a C++ stream, though: you get
    &#8220;(NULL)&#8221;.</p><p>If you don&#8217;t like this behavior, you can change it
    by passing a different value for the second parameter to template
    <code class="classname">Null</code>. By default, this parameter is <tt><a href="../refman/structmysqlpp_1_1NullIsNull.html">NullIsNull</a></tt>, meaning that we should
    enforce the uniqueness of SQL null. To relax this distinction,
    you can instantiate the <code class="classname">Null</code> template with a
    different behavior type: <tt><a href="../refman/structmysqlpp_1_1NullIsZero.html">NullIsZero</a></tt>
    or <tt><a href="../refman/structmysqlpp_1_1NullIsBlank.html">NullIsBlank</a></tt>. Consider this
    code:</p><pre class="programlisting">
mysqlpp::Null&lt;unsigned char, mysqlpp::NullIsZero&gt; myfield(mysqlpp::null);
cout &lt;&lt; myfield &lt;&lt; endl;
cout &lt;&lt; int(myfield) &lt;&lt; endl;</pre><p>This will print &#8220;0&#8221; twice. If you had used the
    default for the second <code class="classname">Null</code> template
    parameter, the first output statement would have printed
    &#8220;(NULL)&#8221;, and the second wouldn&#8217;t even
    compile.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="Transaction"></a>3.10.Using Transactions</h3></div></div></div><p>The <tt><a href="../refman/classmysqlpp_1_1Transaction.html">Transaction</a></tt> class makes it
    easier to use SQL transactions in an exception-safe manner. Normally
    you create the <code class="classname">Transaction</code> object on the
    stack before you issue the queries in your transaction set. Then,
    when all the queries in the transaction set have been issued, you
    call <code class="function">Transaction::commit()</code>, which commits the
    transaction set. If the <code class="classname">Transaction</code> object
    goes out of scope before you call <code class="function">commit()</code>, the
    transaction set is rolled back. This ensures that if some code
    throws an exception after the transaction is started but before it
    is committed, the transaction isn&#8217;t left unresolved.</p><p><code class="filename">examples/transaction.cpp</code> illustrates
    this:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"
#include "stock.h"

#include &lt;iostream&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Show initial state
        mysqlpp::Query query = con.query();
        cout &lt;&lt; "Initial state of stock table:" &lt;&lt; endl;
        print_stock_table(query);

        // Insert a few rows in a single transaction set
        {
            mysqlpp::Transaction trans(con);

            stock row("Sauerkraut", 42, 1.2, 0.75,
                    mysqlpp::sql_date("2006-03-06"), mysqlpp::null);
            query.insert(row);
            query.execute();

            cout &lt;&lt; "\nRow inserted, but not committed." &lt;&lt; endl;
            cout &lt;&lt; "Verify this with another program (e.g. simple1), "
                    "then hit Enter." &lt;&lt; endl;
            getchar();

            cout &lt;&lt; "\nCommitting transaction gives us:" &lt;&lt; endl;
            trans.commit();
            print_stock_table(query);
        }
            
        // Now let's test auto-rollback
        {
            mysqlpp::Transaction trans(con);
            cout &lt;&lt; "\nNow adding catsup to the database..." &lt;&lt; endl;

            stock row("Catsup", 3, 3.9, 2.99,
                    mysqlpp::sql_date("2006-03-06"), mysqlpp::null);
            query.insert(row);
            query.execute();
        }
        cout &lt;&lt; "\nNo, yuck! We don't like catsup. Rolling it back:" &lt;&lt;
                endl;
        print_stock_table(query);
            
    }
    catch (const mysqlpp::BadQuery&amp; er) {
        // Handle any query errors
        cerr &lt;&lt; "Query error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::BadConversion&amp; er) {  
        // Handle bad conversions
        cerr &lt;&lt; "Conversion error: " &lt;&lt; er.what() &lt;&lt; endl &lt;&lt;
                "\tretrieved data size: " &lt;&lt; er.retrieved &lt;&lt;
                ", actual size: " &lt;&lt; er.actual_size &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }

    return 0;
}
</pre><p>One of the downsides of transactions is that the locking it
    requires in the database server is prone to deadlocks. The classic
    case where this happens is when two programs both want access to the
    same two rows within a single transaction each, but they modify them
    in opposite orders. If the timing is such that the programs
    interleave their lock acquisitions, the two come to an impasse:
    neither can get access to the other row they want to modify until
    the other program commits its transaction and thus release the row
    locks, but neither can finish the transaction because they&#8217;re
    waiting on row locks the database server is holding on behalf of the
    other program.</p><p>The MySQL server is smart enough to detect this condition, but
    the best it can do is abort the second transaction. This breaks the
    impasse, allowing the first program to complete its
    transaction.</p><p>The second program now has to deal with the fact that its
    transaction just got aborted. There&#8217;s a subtlety in detecting
    this situation when using MySQL++. By default, MySQL++ signals
    errors like these with exceptions. In the exception handler, you
    might expect to get <code class="constant">ER_LOCK_DEADLOCK</code> from
    <code class="methodname">Query::errnum()</code> (or
    <code class="methodname">Connection::errnum()</code>, same thing), but what
    you&#8217;ll almost certainly get instead is 0, meaning &#8220;no
    error.&#8221; Why? It&#8217;s because you&#8217;re probably using a
    <code class="classname">Transaction</code> object to get automatic
    roll-backs in the face of exceptions. In this case, the roll-back
    happens before your exception handler is called by issuing a
    <span><strong class="command">ROLLBACK</strong></span> query to the database server. Thus,
    <code class="methodname">Query::errnum()</code> returns the error code
    associated with this roll-back query, not the deadlocked transaction
    that caused the exception.</p><p>To avoid this problem, a few of the exception objects as of
    MySQL++ v3.0 include this last error number in the exception object
    itself. It&#8217;s populated at the point of the exception, so it
    can differ from the value you would get from
    <code class="methodname">Query::errnum()</code> later on when the exception
    handler runs.</p><p>The example <code class="filename">examples/deadlock.cpp</code>
    demonstrates the problem:</p><pre class="programlisting">#include "cmdline.h"

#include &lt;mysql++.h&gt;
#include &lt;mysqld_error.h&gt;

#include &lt;iostream&gt;

using namespace std;

// Bring in global holding the value given to the -m switch
extern int run_mode;


int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    // Check that the mode parameter was also given and it makes sense
    if ((run_mode != 1) &amp;&amp; (run_mode != 2)) {
        cerr &lt;&lt; argv[0] &lt;&lt; " must be run with -m1 or -m2 as one of "
                "its command-line arguments." &lt;&lt; endl;
        return 1;
    }

    mysqlpp::Connection con;
    try {
        // Establish the connection to the database server
        con.connect(db, server, user, pass);

        // Start a transaction set.  Transactions create mutex locks on
        // modified rows, so if two programs both touch the same pair of
        // rows but in opposite orders at the wrong time, one of the two
        // programs will deadlock.  The MySQL server knows how to detect
        // this situation, and its error return causes MySQL++ to throw
        // a BadQuery exception.  The point of this example is that if
        // you want to detect this problem, you would check the value of
        // BadQuery::errnum(), not Connection::errnum(), because the
        // transaction rollback process executes a query which succeeds,
        // setting the MySQL C API's "last error number" value to 0.
        // The exception object carries its own copy of the error number
        // at the point the exception was thrown for this very reason.
        mysqlpp::Query query = con.query();
        mysqlpp::Transaction trans(con);

        // Build and run the queries, with the order depending on the -m
        // flag, so that a second copy of the program will deadlock if
        // run while the first is waiting for Enter.
        char dummy[100];
        for (int i = 0; i &lt; 2; ++i) {
            int lock = run_mode + (run_mode == 1 ? i : -i);
            cout &lt;&lt; "Trying lock " &lt;&lt; lock &lt;&lt; "..." &lt;&lt; endl;

            query &lt;&lt; "select * from deadlock_test" &lt;&lt; lock &lt;&lt; 
                    " where x = " &lt;&lt; lock &lt;&lt; " for update";
            query.store();

            cout &lt;&lt; "Acquired lock " &lt;&lt; lock &lt;&lt; ".  Press Enter to ";
            cout &lt;&lt; (i == 0 ? "try next lock" : "exit");
            cout &lt;&lt; ": " &lt;&lt; flush;
            cin.getline(dummy, sizeof(dummy));
        }
    }
    catch (mysqlpp::BadQuery e) {
        if (e.errnum() == ER_LOCK_DEADLOCK) {
            cerr &lt;&lt; "Transaction deadlock detected!" &lt;&lt; endl;
            cerr &lt;&lt; "Connection::errnum = " &lt;&lt; con.errnum() &lt;&lt;
                    ", BadQuery::errnum = " &lt;&lt; e.errnum() &lt;&lt; endl;
        }
        else {
            cerr &lt;&lt; "Unexpected query error: " &lt;&lt; e.what() &lt;&lt; endl;
        }
        return 1;
    }
    catch (mysqlpp::Exception e) {
        cerr &lt;&lt; "General error: " &lt;&lt; e.what() &lt;&lt; endl;      
        return 1;
    }

    return 0;
}
</pre><p>This example works a little differently than the others.  You
    run one copy of the example, then when it pauses waiting for you to
    press <span><strong class="keycap">Enter</strong></span>, you run another copy.  Then, depending
    on which one you press <span><strong class="keycap">Enter</strong></span> in, one of the two
    will abort with the deadlock exception. You can see from the error
    message you get that it matters which method you call to get the
    error number. What you do about it is up to you as it depends on
    your program&#8217;s design and system architecture.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="querytypes"></a>3.11.Which Query Type to Use?</h3></div></div></div><p>There are three major ways to execute a query in MySQL++:
    <code class="methodname">Query::execute()</code>,
    <code class="methodname">Query::store()</code>, and
    <code class="methodname">Query::use()</code>. Which should you use, and
    why?</p><p><code class="methodname">execute()</code> is for queries that do not
    return data <span class="emphasis"><em>per se</em></span>. For instance,
    <span><strong class="command">CREATE INDEX</strong></span>. You do get back some information
    from the MySQL server, which <code class="methodname">execute()</code>
    returns to its caller in a <tt><a href="../refman/classmysqlpp_1_1SimpleResult.html">SimpleResult</a></tt> object. In addition to the obvious &#8212; a
    flag stating whether the query succeeded or not &#8212; this object
    also contains things like the number of rows that the query
    affected. If you only need the success status, it&#8217;s a little
    more efficient to call <code class="methodname">Query::exec()</code>
    instead, as it simply returns <span class="type">bool</span>.</p><p>If your query does pull data from the database, the simplest
    option is <code class="methodname">store()</code>. (All of the examples up
    to this point have used this method.)  This returns a <tt><a href="../refman/classmysqlpp_1_1StoreQueryResult.html">StoreQueryResult</a></tt> object, which contains the
    entire result set. It&#8217;s especially convenient because
    <code class="classname">StoreQueryResult</code> derives from
    <code class="classname">std::vector&lt;mysqlpp::Row&gt;</code>, so it opens
    the whole panoply of STL operations for accessing the rows in the
    result set. Access rows randomly with subscript notation, iterate
    forwards and backwards over the result set, run STL algorithms on
    the set...it all works naturally.</p><p>If you like the idea of storing your results in an STL
    container but don&#8217;t want to use
    <code class="classname">std::vector</code>, you can call
    <code class="methodname">Query::storein()</code> instead. It lets you store
    the results in any standard STL container (yes, both sequential and
    set-associative types) instead of using
    <code class="classname">StoreQueryResult</code>. You do miss out on some of
    the additional database information held by
    <code class="classname">StoreQueryResult</code>&#8217;s other base class,
    <tt><a href="../refman/classmysqlpp_1_1ResultBase.html">ResultBase</a></tt>, however.</p><p><code class="methodname">store*()</code> queries are convenient, but
    the cost of keeping the entire result set in main memory can
    sometimes be too high. It can be surprisingly costly, in fact. A
    MySQL database server stores data compactly on disk, but it returns
    query data to the client in a textual form. This results in a kind
    of data bloat that affects numeric and BLOB types the most. MySQL++
    and the underlying C API library also have their own memory
    overheads in addition to this. So, if you happen to know that the
    database server stores every record of a particular table in 1 KB,
    pulling a million records from that table could easily take several
    GB of memory with a <code class="methodname">store()</code> query,
    depending on what&#8217;s actually stored in that table.</p><p>For these large result sets, the superior option is a
    <code class="methodname">use()</code> query. This returns a <tt><a href="../refman/classmysqlpp_1_1UseQueryResult.html">UseQueryResult</a></tt> object, which is similar to
    <code class="classname">StoreQueryResult</code>, but without all of the
    random-access features. This is because a &#8220;use&#8221; query
    tells the database server to send the results back one row at a
    time, to be processed linearly. It&#8217;s analogous to a C++
    stream&#8217;s input iterator, as opposed to a random-access
    iterator that a container like vector offers. By accepting this
    limitation, you can process arbitrarily large result sets. This
    technique is demonstrated in
    <code class="filename">examples/simple3.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"

#include &lt;mysql++.h&gt;

#include &lt;iostream&gt;
#include &lt;iomanip&gt;

using namespace std;

int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    // Connect to the sample database.
    mysqlpp::Connection conn(false);
    if (conn.connect(db, server, user, pass)) {
        // Ask for all rows from the sample stock table and display
        // them.  Unlike simple2 example, we retreive each row one at
        // a time instead of storing the entire result set in memory
        // and then iterating over it.
        mysqlpp::Query query = conn.query("select * from stock");
        if (mysqlpp::UseQueryResult res = query.use()) {
            // Display header
            cout.setf(ios::left);
            cout &lt;&lt; setw(31) &lt;&lt; "Item" &lt;&lt;
                    setw(10) &lt;&lt; "Num" &lt;&lt;
                    setw(10) &lt;&lt; "Weight" &lt;&lt;
                    setw(10) &lt;&lt; "Price" &lt;&lt;
                    "Date" &lt;&lt; endl &lt;&lt; endl;

            // Get each row in result set, and print its contents
            while (mysqlpp::Row row = res.fetch_row()) {
                cout &lt;&lt; setw(30) &lt;&lt; row["item"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; row["num"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; row["weight"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; row["price"] &lt;&lt; ' ' &lt;&lt;
                        setw(9) &lt;&lt; row["sdate"] &lt;&lt;
                        endl;
            }

            // Check for error: can't distinguish "end of results" and
            // error cases in return from fetch_row() otherwise.
            if (conn.errnum()) {
                cerr &lt;&lt; "Error received in fetching a row: " &lt;&lt;
                        conn.error() &lt;&lt; endl;
                return 1;
            }
            return 0;
        }
        else {
            cerr &lt;&lt; "Failed to get stock item: " &lt;&lt; query.error() &lt;&lt; endl;
            return 1;
        }
    }
    else {
        cerr &lt;&lt; "DB connection failed: " &lt;&lt; conn.error() &lt;&lt; endl;
        return 1;
    }
}
</pre><p>This example does the same thing as
    <code class="filename">simple2</code>, only with a &#8220;use&#8221; query
    instead of a &#8220;store&#8221; query.</p><p>Valuable as <code class="methodname">use()</code> queries are, they
    should not be the first resort in solving problems of excessive
    memory use. It&#8217;s better if you can find a way to simply not
    pull as much data from the database in the first place. Maybe
    you&#8217;re saying <span><strong class="command">SELECT *</strong></span> even though you
    don&#8217;t immedidately need all the columns from the table. Or,
    maybe you&#8217;re filtering the result set with C++ code after you
    get it from the database server. If you can do that filtering with a
    more restrictive <span><strong class="command">WHERE</strong></span> clause on the
    <span><strong class="command">SELECT</strong></span>, it&#8217;ll not only save memory,
    it&#8217;ll save bandwidth between the database server and client,
    and can even save CPU time. If the filtering criteria can&#8217;t be
    expressed in a <span><strong class="command">WHERE</strong></span> clause, however, read on to
    the next section.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="store_if"></a>3.12.Conditional Result Row Handling</h3></div></div></div><p>Sometimes you must pull more data from the database server
    than you actually need and filter it in memory. SQL&#8217;s
    <span><strong class="command">WHERE</strong></span> clause is powerful, but not as powerful as
    C++. Instead of storing the full result set and then picking over it
    to find the rows you want to keep, use
    <code class="methodname">Query::store_if()</code>. This is
    <code class="filename">examples/store_if.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"
#include "stock.h"

#include &lt;mysql++.h&gt;

#include &lt;iostream&gt;

#include &lt;math.h&gt;


// Define a functor for testing primality.
struct is_prime
{
    bool operator()(const stock&amp; s)
    {
        if ((s.num == 2) || (s.num == 3)) {
            return true;    // 2 and 3 are trivial cases
        }
        else if ((s.num &lt; 2) || ((s.num % 2) == 0)) {
            return false;   // can't be prime if &lt; 2 or even
        }
        else {
            // The only possibility left is that it's divisible by an
            // odd number that's less than or equal to its square root.
            for (int i = 3; i &lt;= sqrt(double(s.num)); i += 2) {
                if ((s.num % i) == 0) {
                    return false;
                }
            }
            return true;
        }
    }
};


int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Collect the stock items with prime quantities
        std::vector&lt;stock&gt; results;
        mysqlpp::Query query = con.query();
        query.store_if(results, stock(), is_prime());

        // Show the results
        print_stock_header(results.size());
        std::vector&lt;stock&gt;::const_iterator it;
        for (it = results.begin(); it != results.end(); ++it) {
            print_stock_row(it-&gt;item.c_str(), it-&gt;num, it-&gt;weight,
                    it-&gt;price, it-&gt;sdate);
        }
    }
    catch (const mysqlpp::BadQuery&amp; e) {
        // Something went wrong with the SQL query.
        std::cerr &lt;&lt; "Query failed: " &lt;&lt; e.what() &lt;&lt; std::endl;
        return 1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        std::cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; std::endl;
        return 1;
    }

    return 0;
}
</pre><p>I doubt anyone really needs to select rows from a table that
    have a prime number in a given field. This example is meant to be
    just barely more complex than SQL can manage, to avoid obscuring the
    point. That point being, the
    <code class="methodname">Query::store_if()</code> call here gives you a
    container full of results meeting a criterion that you probably
    can&#8217;t express in SQL. You will no doubt have much more useful
    criteria in your own programs.</p><p>If you need a more complex query than the one
    <code class="methodname">store_if()</code> knows how to build when given an
    SSQLS examplar, there are two overloads that let you use your own
    query string. One overload takes the query string directly, and the
    other uses the query string built with
    <code class="classname">Query</code>&#8217;s stream interface.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="for_each"></a>3.13.Executing Code for Each Row In a Result Set</h3></div></div></div><p>SQL is more than just a database query language. Modern
    database engines can actually do some calculations on the data on
    the server side. But, this isn&#8217;t always the best way to get
    something done. When you need to mix code and a query,
    MySQL++&#8217;s <code class="methodname">Query::for_each()</code> facility
    might be just what you need. This is
    <code class="filename">examples/for_each.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"
#include "stock.h"

#include &lt;mysql++.h&gt;

#include &lt;iostream&gt;

#include &lt;math.h&gt;


// Define a functor to collect statistics about the stock table
class gather_stock_stats
{
public:
    gather_stock_stats() :
    items_(0),
    weight_(0),
    cost_(0)
    {
    }

    void operator()(const stock&amp; s)
    {
        items_  += s.num;
        weight_ += (s.num * s.weight);
        cost_   += (s.num * s.price);
    }
    
private:
    mysqlpp::sql_bigint items_;
    mysqlpp::sql_double weight_, cost_;

    friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os,
            const gather_stock_stats&amp; ss);
};


// Dump the contents of gather_stock_stats to a stream in human-readable
// form.
std::ostream&amp;
operator&lt;&lt;(std::ostream&amp; os, const gather_stock_stats&amp; ss)
{
    os &lt;&lt; ss.items_ &lt;&lt; " items " &lt;&lt;
            "weighing " &lt;&lt; ss.weight_ &lt;&lt; " stone and " &lt;&lt;
            "costing " &lt;&lt; ss.cost_ &lt;&lt; " cowrie shells";
    return os;
}


int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Gather and display the stats for the entire stock table
        mysqlpp::Query query = con.query();
        std::cout &lt;&lt; "There are " &lt;&lt; query.for_each(stock(),
                gather_stock_stats()) &lt;&lt; '.' &lt;&lt; std::endl;
    }
    catch (const mysqlpp::BadQuery&amp; e) {
        // Something went wrong with the SQL query.
        std::cerr &lt;&lt; "Query failed: " &lt;&lt; e.what() &lt;&lt; std::endl;
        return 1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        std::cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; std::endl;
        return 1;
    }

    return 0;
}
</pre><p>You only need to read the <code class="function">main()</code> function
    to get a good idea of what the program does. The key line of code
    passes an SSQLS examplar and a functor to
    <code class="methodname">Query::for_each()</code>.
    <code class="methodname">for_each()</code> uses the SSQLS instance to build
    a <code class="computeroutput">select * from TABLE</code> query,
    <code class="computeroutput">stock</code> in this case. It runs that
    query internally, calling <code class="classname">gather_stock_stats</code>
    on each row. This is a pretty contrived example; you could actually
    do this in SQL, but we&#8217;re trying to prevent the complexity of
    the code from getting in the way of the demonstration here.</p><p>Just as with <code class="methodname">store_if()</code>, described
    above, there are two other overloads for
    <code class="methodname">for_each()</code> that let you use your own query
    string.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="connopts"></a>3.14.Connection Options</h3></div></div></div><p>MySQL has a large number of options that control how it makes
    the connection to the database server, and how that connection
    behaves. The defaults are sufficient for most programs, so only one
    of the MySQL++ example programs make any connection option changes.
    Here is <code class="filename">examples/multiquery.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"

#include &lt;mysql++.h&gt;

#include &lt;iostream&gt;
#include &lt;iomanip&gt;
#include &lt;vector&gt;

using namespace std;
using namespace mysqlpp;


typedef vector&lt;int&gt; IntVectorType;


static void
print_header(IntVectorType&amp; widths, StoreQueryResult&amp; res)
{
    cout &lt;&lt; "  |" &lt;&lt; setfill(' ');
    for (size_t i = 0; i &lt; res.field_names()-&gt;size(); i++) {
        cout &lt;&lt; " " &lt;&lt; setw(widths.at(i)) &lt;&lt; res.field_name(i) &lt;&lt; " |";
    }
    cout &lt;&lt; endl;
}


static void
print_row(IntVectorType&amp; widths, Row&amp; row)
{
    cout &lt;&lt; "  |" &lt;&lt; setfill(' ');
    for (size_t i = 0; i &lt; row.size(); ++i) {
        cout &lt;&lt; " " &lt;&lt; setw(widths.at(i)) &lt;&lt; row[i] &lt;&lt; " |";
    }
    cout &lt;&lt; endl;
}


static void
print_row_separator(IntVectorType&amp; widths)
{
    cout &lt;&lt; "  +" &lt;&lt; setfill('-');
    for (size_t i = 0; i &lt; widths.size(); i++) {
        cout &lt;&lt; "-" &lt;&lt; setw(widths.at(i)) &lt;&lt; '-' &lt;&lt; "-+";
    }
    cout &lt;&lt; endl;
}


static void
print_result(StoreQueryResult&amp; res, int index)
{
    // Show how many rows are in result, if any
    StoreQueryResult::size_type num_results = res.size();
    if (res &amp;&amp; (num_results &gt; 0)) {
        cout &lt;&lt; "Result set " &lt;&lt; index &lt;&lt; " has " &lt;&lt; num_results &lt;&lt;
                " row" &lt;&lt; (num_results == 1 ? "" : "s") &lt;&lt; ':' &lt;&lt; endl;
    }
    else {
        cout &lt;&lt; "Result set " &lt;&lt; index &lt;&lt; " is empty." &lt;&lt; endl;
        return;
    }

    // Figure out the widths of the result set's columns
    IntVectorType widths;
    int size = res.num_fields();
    for (int i = 0; i &lt; size; i++) {
        widths.push_back(max(
                res.field(i).max_length(),
                res.field_name(i).size()));
    }

    // Print result set header
    print_row_separator(widths);
    print_header(widths, res);
    print_row_separator(widths);

    // Display the result set contents
    for (StoreQueryResult::size_type i = 0; i &lt; num_results; ++i) {
        print_row(widths, res[i]);
    }

    // Print result set footer
    print_row_separator(widths);
}


static void
print_multiple_results(Query&amp; query)
{
    // Execute query and print all result sets
    StoreQueryResult res = query.store();
    print_result(res, 0);
    for (int i = 1; query.more_results(); ++i) {
        res = query.store_next();
        print_result(res, i);
    }
}


int
main(int argc, char *argv[])
{
    // Get connection parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Enable multi-queries.  Notice that you almost always set
        // MySQL++ connection options before establishing the server
        // connection, and options are always set using this one
        // interface.  If you're familiar with the underlying C API,
        // you know that there is poor consistency on these matters;
        // MySQL++ abstracts these differences away.
        Connection con;
        con.set_option(new MultiStatementsOption(true));

        // Connect to the database
        if (!con.connect(db, server, user, pass)) {
            return 1;
        }

        // Set up query with multiple queries.
        Query query = con.query();
        query &lt;&lt; "DROP TABLE IF EXISTS test_table; " &lt;&lt;
                "CREATE TABLE test_table(id INT); " &lt;&lt;
                "INSERT INTO test_table VALUES(10); " &lt;&lt;
                "UPDATE test_table SET id=20 WHERE id=10; " &lt;&lt;
                "SELECT * FROM test_table; " &lt;&lt;
                "DROP TABLE test_table";
        cout &lt;&lt; "Multi-query: " &lt;&lt; endl &lt;&lt; query &lt;&lt; endl;

        // Execute statement and display all result sets.
        print_multiple_results(query);

#if MYSQL_VERSION_ID &gt;= 50000
        // If it's MySQL v5.0 or higher, also test stored procedures, which
        // return their results the same way multi-queries do.
        query &lt;&lt; "DROP PROCEDURE IF EXISTS get_stock; " &lt;&lt;
                "CREATE PROCEDURE get_stock" &lt;&lt;
                "( i_item varchar(20) ) " &lt;&lt;
                "BEGIN " &lt;&lt;
                "SET i_item = concat('%', i_item, '%'); " &lt;&lt;
                "SELECT * FROM stock WHERE lower(item) like lower(i_item); " &lt;&lt;
                "END;";
        cout &lt;&lt; "Stored procedure query: " &lt;&lt; endl &lt;&lt; query &lt;&lt; endl;

        // Create the stored procedure.
        print_multiple_results(query);

        // Call the stored procedure and display its results.
        query &lt;&lt; "CALL get_stock('relish')";
        cout &lt;&lt; "Query: " &lt;&lt; query &lt;&lt; endl;
        print_multiple_results(query);
#endif

        return 0;
    }
    catch (const BadOption&amp; err) {
        cerr &lt;&lt; err.what() &lt;&lt; endl;
        cerr &lt;&lt; "This example requires MySQL 4.1.1 or later." &lt;&lt; endl;
        return 1;
    }
    catch (const ConnectionFailed&amp; err) {
        cerr &lt;&lt; "Failed to connect to database server: " &lt;&lt;
                err.what() &lt;&lt; endl;
        return 1;
    }
    catch (const Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return 1;
    }
}
</pre><p>This is a fairly complex example demonstrating the multi-query
    and stored procedure features in newer versions of MySQL. Because
    these are new features, and they change the communication between
    the client and server, you have to enable these features in a
    connection option. The key line is right up at the top of
    <code class="function">main()</code>, where it creates a <tt><a href="../refman/classmysqlpp_1_1MultiStatementsOption.html">MultiStatementsOption</a></tt> object and passes it
    to <code class="methodname">Connection::set_option()</code>. That method
    will take a pointer to any derivative of <tt><a href="../refman/classmysqlpp_1_1Option.html">Option</a></tt>: you just create such an object on the heap and pass
    it in, which gives <code class="classname">Connection</code> the data values
    it needs to set the option. You don&#8217;t need to worry about
    releasing the memory used by the <code class="classname">Option</code>
    objects; it&#8217;s done automatically.</p><p>The only tricky thing about setting options is that only a few
    of them can be set after the connection is up. Most need to be set
    just as shown in the example above: create an unconnected
    <code class="classname">Connection</code> object, set your connection
    options, and only then establish the connection. The option setting
    mechanism takes care of applying the options at the correct time in
    the connection establishment sequence.</p><p>If you&#8217;re familiar with setting connection options in
    the MySQL C API, you&#8217;ll have to get your head around the fact
    that MySQL++&#8217;s connection option mechanism is a much simpler,
    higher-level design that doesn&#8217;t resemble the C API in any
    way. The C API has something like half a dozen different mechanisms
    for setting options that control the connection. The flexibility of
    the C++ type system allows us to wrap all of these up into a single
    high-level mechanism while actually getting greater type safety than
    the C API allows.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="fieldinf"></a>3.15.Getting Field Meta-Information</h3></div></div></div><p>The following example demonstrates how to get information
    about the fields in a result set, such as the name of the field and
    the SQL type. This is
    <code class="filename">examples/fieldinf.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"

#include &lt;iostream&gt;
#include &lt;iomanip&gt;

using namespace std;


// Access the flag that's set when running under the dtest framework, so
// we modify our output to be testable.
extern bool dtest_mode;


int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass)) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Get contents of main example table
        mysqlpp::Query query = con.query("select * from stock");
        mysqlpp::StoreQueryResult res = query.store();

        // Show info about each field in that table
        char widths[] = { 12, 22, 46 };
        cout.setf(ios::left);
        cout &lt;&lt; setw(widths[0]) &lt;&lt; "Field" &lt;&lt;
                setw(widths[1]) &lt;&lt; "SQL Type" &lt;&lt;
                setw(widths[2]) &lt;&lt; "Equivalent C++ Type" &lt;&lt;
                endl;
        for (size_t i = 0; i &lt; sizeof(widths) / sizeof(widths[0]); ++i) {
            cout &lt;&lt; string(widths[i] - 1, '=') &lt;&lt; ' ';
        }
        cout &lt;&lt; endl;
        
        for (size_t i = 0; i &lt; res.field_names()-&gt;size(); i++) {
            // Suppress C++ type name outputs when run under dtest,
            // as they're system-specific.
            const char* cname = dtest_mode ? "n/a" : res.field_type(i).name();
            mysqlpp::FieldTypes::value_type ft = res.field_type(i);
            ostringstream os;
            os &lt;&lt; ft.sql_name() &lt;&lt; " (" &lt;&lt; ft.id() &lt;&lt; ')';
            cout &lt;&lt; setw(widths[0]) &lt;&lt; res.field_name(i).c_str() &lt;&lt;
                    setw(widths[1]) &lt;&lt; os.str() &lt;&lt;
                    setw(widths[2]) &lt;&lt; cname &lt;&lt;
                    endl;
        }
        cout &lt;&lt; endl;

        // Simple type check
        if (res.field_type(0) == typeid(string)) {
            cout &lt;&lt; "SQL type of 'item' field most closely resembles "
                    "the C++ string type." &lt;&lt; endl;
        }

        // Tricky type check: the 'if' path shouldn't happen because the
        // description field has the NULL attribute.  We need to dig a
        // little deeper if we want to ignore this in our type checks.
        if (res.field_type(5) == typeid(string)) {
            cout &lt;&lt; "Should not happen! Type check failure." &lt;&lt; endl;
        }
        else if (res.field_type(5) == typeid(mysqlpp::Null&lt;mysqlpp::String&gt;)) {
            cout &lt;&lt; "SQL type of 'description' field resembles "
                    "a nullable variant of the C++ string type." &lt;&lt; endl;
        }
        else {
            cout &lt;&lt; "Weird: fifth field's type is now " &lt;&lt;
                    res.field_type(5).name() &lt;&lt; endl;
            cout &lt;&lt; "Did something recently change in resetdb?" &lt;&lt; endl;
        }
    }
    catch (const mysqlpp::BadQuery&amp; er) {
        // Handle any query errors
        cerr &lt;&lt; "Query error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }

    return 0;
}
</pre></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="string-types"></a>3.16.MySQL++&#8217;s Special String Types</h3></div></div></div><p>MySQL++ has two classes that work like
    <code class="classname">std::string</code> to some degree: <tt><a href="../refman/classmysqlpp_1_1String.html">String</a></tt> and <tt><a href="../refman/classmysqlpp_1_1SQLTypeAdapter.html">SQLTypeAdapter</a></tt>. These classes exist to provide functionality
    that <code class="classname">std::string</code> doesn&#8217;t provide, but
    they are neither derivatives of nor complete supersets of
    <code class="classname">std::string</code>.  As a result, end-user code
    generally doesn&#8217;t deal with these classes directly, because
    <code class="classname">std::string</code> is a better general-purpose
    string type. In fact, MySQL++ itself uses
    <code class="classname">std::string</code> most of the time, too. But, the
    places these specialized stringish types do get used are so
    important to the way MySQL++ works that it&#8217;s well worth taking
    the time to understand them.</p><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="SQLTypeAdapter"></a>SQLTypeAdapter</h4></div></div></div><p>The simpler of the two is
      <code class="classname">SQLTypeAdapter</code>, or
      <code class="classname">STA</code> for short.<sup>[<a name="id2875223" href="#ftn.id2875223">6</a>]</sup></p><p>As its name suggests, its only purpose is to adapt other
      data types to be used with SQL. It has a whole bunch of conversion
      constructors, one for all data types we expect to be used with
      MySQL++ for values in queries. SQL queries are strings, so
      constructors that take stringish types just make a copy of that
      string, and all the others &#8220;stringize&#8221; the value in
      the format needed by
      SQL.<sup>[<a name="id2875253" href="#ftn.id2875253">7</a>]</sup> The conversion
      constructors preserve type information, so this stringization
      process doesn&#8217;t throw away any essential information.</p><p><code class="classname">STA</code> is used anywhere MySQL++ needs to
      be able to accept any of several data types for use in a SQL
      query. Major users are <code class="classname">Query</code>&#8217;s
      template query mechanism and the <code class="classname">Query</code>
      stream quoting and escaping mechanism. You care about
      <code class="classname">STA</code> because any time you pass a data value
      to MySQL++ to be used in building a SQL query, it goes through
      <code class="classname">STA</code>. <code class="classname">STA</code> is one of
      the key pieces in MySQL++ that makes it easy to generate
      syntactically-correct SQL queries.</p></div><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="String"></a>String</h4></div></div></div><p>If MySQL++ can be said to have its own generic string type,
      it&#8217;s <code class="classname">String</code>, but it&#8217;s not
      really functional enough for general use. It&#8217;s possible that
      in future versions of MySQL++ we&#8217;ll expand its interface to
      include everything <code class="classname">std::string</code> does, so
      that&#8217;s why it&#8217;s called that.<sup>[<a name="id2875324" href="#ftn.id2875324">8</a>]</sup></p><p>The key thing <code class="classname">String</code> provides over
      <code class="classname">std::string</code> is conversion of strings in SQL
      value formats to their native C++ data types. For example, if you
      initialize it with the string &#8220;2007-11-19&#8221;, you can
      assign the <code class="classname">String</code> to a <tt><a href="../refman/structmysqlpp_1_1Date.html">Date</a></tt>, not because
      <code class="classname">Date</code> knows how to initialize itself from
      <code class="classname">String</code>, but the reverse:
      <code class="classname">String</code> has a bunch of implicit conversion
      operators defined for it, so you can use it in any type context
      that makes sense in your application.</p><p>Because <code class="methodname">Row::operator[]</code> returns
      <code class="classname">String</code>, you can say things like
      this:</p><pre class="programlisting">int x = row["x"];</pre><p>In a very real sense, <code class="classname">String</code> is the
      inverse of <code class="classname">STA</code>:
      <code class="classname">String</code> converts SQL value strings to C++
      data types, and <code class="classname">STA</code> converts C++ data types
      to SQL value strings.<sup>[<a name="id2875419" href="#ftn.id2875419">9</a>]</sup></p><p><code class="classname">String</code> has two main uses.</p><p>By far the most common use is as the field value type of
      <code class="classname">Row</code>, as exemplified above. It&#8217;s not
      just the return type of <code class="methodname">Row::operator[]</code>,
      though: it&#8217;s actually the value type used within
      <code class="classname">Row</code>&#8217;s internal array. As a result,
      any time MySQL++ pulls data from the database, it goes through
      <code class="classname">String</code> when converting it from the string
      form used in SQL result sets to the C++ data type you actually
      want the data in. It&#8217;s the core of the structure population
      mechanism in <a href="tutorial.html#ssqlsintro">Specialized SQL Structures</a>, for example.</p><p>Because <code class="classname">String</code> is the last pristine
      form of data in a result set before it gets out of MySQL++&#8217;s
      internals where end-user code can see it, MySQL++&#8217;s
      <span class="type">sql_blob</span> and related <span class="type">typedef</span>s are
      aliases for <code class="classname">String</code>. Using anything else
      would require copies; while the whole &#8220;networked database
      server&#8221; thing means most of MySQL++ can be quite inefficient
      and still not affect benchmark results meaningfully, BLOBs tend to
      be big, so making unnecessary copies can really make a difference.
      Which brings us to...</p></div><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="string-refcount"></a>Reference Counting</h4></div></div></div><p>To avoid unnecessary buffer copies, both
      <code class="classname">STA</code> and <code class="classname">String</code> are
      implemented in terms of a reference-counted copy-on-write buffer
      scheme. Both classes share the same underlying mechanism, and so
      are interoperable. This means that if you construct one of these
      objects from another, it doesn&#8217;t actually copy the string
      data, it only copies a pointer to the data buffer, and increments
      its reference count. If the object has new data assigned to it or
      it&#8217;s otherwise modified, it decrements its reference count
      and creates its own copy of the buffer. This has a lot of
      practical import, such as the fact that
      <code class="methodname">Row::operator[]</code> can return
      <code class="classname">String</code> by value, and it&#8217;s still
      efficient.</p></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="blob"></a>3.17.Dealing with Binary Data</h3></div></div></div><p>The tricky part about dealing with binary data in MySQL++ is
    to ensure that you don&#8217;t ever treat the data as a C string,
    which is really easy to do accidentally. C strings treat zero bytes
    as special end-of-string characters, but they&#8217;re not special
    at all in binary data. Recent releases of MySQL++ do a better job of
    letting you keep data in forms that don&#8217;t have this problem,
    but it&#8217;s still possible to do it incorrectly. These examples
    demonstrate correct techniques.</p><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="blob-save"></a>Loading a binary file into a BLOB column</h4></div></div></div><p>This example shows how to insert binary data into a MySQL
      table&#8217;s BLOB column with MySQL++, and also how to get the
      value of the auto-increment column from the previous insert. (This
      MySQL feature is usually used to create unique IDs for rows as
      they&#8217;re inserted.) The program requires one command line
      parameter over that required by the other examples you&#8217;ve
      seen so far, the path to a JPEG file. This is
      <code class="filename">examples/load_jpeg.cpp</code>:</p><pre class="programlisting">#include "cmdline.h"
#include "printdata.h"

#include &lt;mysql++.h&gt;

#include &lt;fstream&gt;

using namespace std;
using namespace mysqlpp;


// Pull in a state variable used by att_getopt() implementation so we
// can pick up where standard command line processing leaves off.  Feel
// free to ignore this implementation detail.
extern int ag_optind;


static bool
is_jpeg(const unsigned char* img_data)
{
    return (img_data[0] == 0xFF) &amp;&amp; (img_data[1] == 0xD8) &amp;&amp;
            ((memcmp(img_data + 6, "JFIF", 4) == 0) ||
             (memcmp(img_data + 6, "Exif", 4) == 0));
}


int
main(int argc, char *argv[])
{
    // Get database access parameters from command line
    const char* db = 0, *server = 0, *user = 0, *pass = "";
    if (!parse_command_line(argc, argv, &amp;db, &amp;server, &amp;user, &amp;pass,
            "[jpeg_file]")) {
        return 1;
    }

    try {
        // Establish the connection to the database server.
        mysqlpp::Connection con(db, server, user, pass);

        // Assume that the last command line argument is a file.  Try
        // to read that file's data into img_data, and check it to see
        // if it appears to be a JPEG file.  Bail otherwise.
        string img_name, img_data;
        if (argc - ag_optind &gt;= 1) {
            img_name = argv[ag_optind];
            ifstream img_file(img_name.c_str(), ios::ate);
            if (img_file) {
                size_t img_size = img_file.tellg();
                if (img_size &gt; 10) {
                    img_file.seekg(0, ios::beg);
                    unsigned char* img_buffer = new unsigned char[img_size];
                    img_file.read(reinterpret_cast&lt;char*&gt;(img_buffer),
                            img_size);
                    if (is_jpeg(img_buffer)) {
                        img_data.assign(
                                reinterpret_cast&lt;char*&gt;(img_buffer),
                                img_size);
                    }
                    else {
                        cerr &lt;&lt; '"' &lt;&lt; img_file &lt;&lt;
                                "\" isn't a JPEG!" &lt;&lt; endl;
                    }
                    delete[] img_buffer;
                }
                else {
                    cerr &lt;&lt; "File is too short to be a JPEG!" &lt;&lt; endl;
                }
            }
        }
        if (img_data.empty()) {
            print_usage(argv[0], "[jpeg_file]");
            return 1;
        }

        // Insert image data into the BLOB column in the images table.
        // We're inserting it as an std::string instead of using the raw
        // data buffer allocated above because we don't want the data
        // treated as a C string, which would truncate the data at the
        // first null character.
        Query query = con.query();
        query &lt;&lt; "INSERT INTO images (data) VALUES(\"" &lt;&lt;
                mysqlpp::escape &lt;&lt; img_data &lt;&lt; "\")";
        SimpleResult res = query.execute();

        // If we get here, insertion succeeded
        cout &lt;&lt; "Inserted \"" &lt;&lt; img_name &lt;&lt;
                "\" into images table, " &lt;&lt; img_data.size() &lt;&lt;
                " bytes, ID " &lt;&lt; res.insert_id() &lt;&lt; endl;
    }
    catch (const BadQuery&amp; er) {
        // Handle any query errors
        cerr &lt;&lt; "Query error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }
    catch (const BadConversion&amp; er) {
        // Handle bad conversions
        cerr &lt;&lt; "Conversion error: " &lt;&lt; er.what() &lt;&lt; endl &lt;&lt;
                "\tretrieved data size: " &lt;&lt; er.retrieved &lt;&lt;
                ", actual size: " &lt;&lt; er.actual_size &lt;&lt; endl;
        return -1;
    }
    catch (const Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        cerr &lt;&lt; "Error: " &lt;&lt; er.what() &lt;&lt; endl;
        return -1;
    }

    return 0;
}
</pre><p>Notice that we used the <span class="type">escape</span> manipulator when
      building the INSERT query above. This is because we&#8217;re not
      using one of the MySQL++ types that does automatic escaping and
      quoting.</p></div><div class="sect3" lang="en"><div class="titlepage"><div><div><h4 class="title"><a name="blob-retreive"></a>Serving images from BLOB column via CGI</h4></div></div></div><p>This example is also a very short one, considering the
      function that it performs. It retreives data loaded by
      <code class="filename">load_jpeg</code> and prints it out in the form a web
      server can accept for a CGI call. This is
      <code class="filename">examples/cgi_jpeg.cpp</code>:</p><pre class="programlisting">#include &lt;mysql++.h&gt;
#include &lt;ssqls.h&gt;

#define IMG_DATABASE    "mysql_cpp_data"
#define IMG_HOST        "localhost"
#define IMG_USER        "root"
#define IMG_PASSWORD    "nunyabinness"

sql_create_2(images,
    1, 2,
    mysqlpp::sql_int_unsigned, id,
    mysqlpp::sql_blob, data)

int main()
{
    unsigned int img_id = 0;
    char* cgi_query = getenv("QUERY_STRING");
    if (cgi_query) {
        if ((strlen(cgi_query) &lt; 4) || memcmp(cgi_query, "id=", 3)) {
            std::cout &lt;&lt; "Content-type: text/plain" &lt;&lt; std::endl &lt;&lt; std::endl;
            std::cout &lt;&lt; "ERROR: Bad query string" &lt;&lt; std::endl;
            return 1;
        }
        else {
            img_id = atoi(cgi_query + 3);
        }
    }
    else {
        std::cerr &lt;&lt; "Put this program into a web server's cgi-bin "
                "directory, then" &lt;&lt; std::endl;
        std::cerr &lt;&lt; "invoke it with a URL like this:" &lt;&lt; std::endl;
        std::cerr &lt;&lt; std::endl;
        std::cerr &lt;&lt; "    http://server.name.com/cgi-bin/cgi_jpeg?id=2" &lt;&lt;
                std::endl;
        std::cerr &lt;&lt; std::endl;
        std::cerr &lt;&lt; "This will retrieve the image with ID 2." &lt;&lt; std::endl;
        std::cerr &lt;&lt; std::endl;
        std::cerr &lt;&lt; "You will probably have to change some of the #defines "
                "at the top of" &lt;&lt; std::endl;
        std::cerr &lt;&lt; "examples/cgi_jpeg.cpp to allow the lookup to work." &lt;&lt;
                std::endl;
        return 1;
    }

    try {
        mysqlpp::Connection con(IMG_DATABASE, IMG_HOST, IMG_USER,
                IMG_PASSWORD);
        mysqlpp::Query query = con.query();
        query &lt;&lt; "SELECT * FROM images WHERE id = " &lt;&lt; img_id;
        mysqlpp::UseQueryResult res = query.use();
        if (res) {
            images img = res.fetch_row();
            std::cout &lt;&lt; "Content-type: image/jpeg" &lt;&lt; std::endl;
            std::cout &lt;&lt; "Content-length: " &lt;&lt; img.data.length() &lt;&lt; "\n\n";
            std::cout &lt;&lt; img.data;
        }
        else {
            std::cout &lt;&lt; "Content-type: text/plain" &lt;&lt; std::endl &lt;&lt; std::endl;
            std::cout &lt;&lt; "ERROR: No such image with ID " &lt;&lt; img_id &lt;&lt; std::endl;
        }
    }
    catch (const mysqlpp::BadQuery&amp; er) {
        // Handle any query errors
        std::cout &lt;&lt; "Content-type: text/plain" &lt;&lt; std::endl &lt;&lt; std::endl;
        std::cout &lt;&lt; "QUERY ERROR: " &lt;&lt; er.what() &lt;&lt; std::endl;
        return 1;
    }
    catch (const mysqlpp::Exception&amp; er) {
        // Catch-all for any other MySQL++ exceptions
        std::cout &lt;&lt; "Content-type: text/plain" &lt;&lt; std::endl &lt;&lt; std::endl;
        std::cout &lt;&lt; "GENERAL ERROR: " &lt;&lt; er.what() &lt;&lt; std::endl;
        return 1;
    }

    return 0;
}
</pre><p>You install this in a web server&#8217;s CGI program
      directory, then call it with a URL like
      <code class="uri">http://my.server.com/cgi-bin/cgi_jpeg?id=1</code>.  That
      retrieves the JPEG with ID 1 from the table and returns it to the
      web server, which will send it on to the browser.</p></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="concurrentqueries"></a>3.18.Concurrent Queries on a Connection</h3></div></div></div><p>An important limitation of the MySQL C API library &#8212;
    which MySQL++ is built atop, so it shares this limitation &#8212; is
    that you can&#8217;t have two concurrent queries running on a single
    connection. If you try, you get an obscure error message about
    &#8220;Commands out of sync&#8221; from the underlying C API
    library. (You get it in a MySQL++ exception unless you have
    exceptions disabled, in which case you get a failure code and
    <code class="methodname">Connection::error()</code> returns this
    message.)</p><p>The easiest way to cause this error is in a multithreaded
    program where you have a single <tt><a href="../refman/classmysqlpp_1_1Connection.html">Connection</a></tt> object, but allow multiple threads to issue
    queries on it. Unless you put in a lot of work to synchronize
    access, this is almost guaranteed to fail.</p><p>If you give each thread that issues queries has its own
    <code class="classname">Connection</code> object, you can still run into
    trouble if you pass the data you get from queries around to other
    threads. What can happen is that one of these child objects
    indirectly calls back to the <code class="classname">Connection</code> at a
    time where it&#8217;s involved with another query. (There are other
    ways to run into trouble when sharing MySQL++ data structures among
    threads, but the whole topic is complex enough to deserve its own
    chapter, <a href="threads.html" title="7.Using MySQL++ in a Multithreaded Program">Section7, &#8220;Using MySQL++ in a Multithreaded Program&#8221;</a>.)</p><p>It&#8217;s possible to run into this problem in a
    single-threaded program as well. As discussed above (<a href="tutorial.html#querytypes" title="3.11.Which Query Type to Use?">Section3.11, &#8220;Which Query Type to Use?&#8221;</a>), one of the options MySQL offers for
    executing a query lets you issue the query, then consume the rows
    one at a time, on demand: it&#8217;s the &#8220;use&#8221; query. If
    you don&#8217;t consume all rows from a query before you issue
    another on that connection, you are effectively trying to have
    multiple concurrent queries on a single connection, and you end up
    with the same problem. The simplest recipie for disaster is:</p><pre class="programlisting">
UseQueryResult r1 = query.use("select garbage from plink where foobie='tamagotchi'");
UseQueryResult r2 = query.use("select blah from bonk where bletch='smurf'");</pre><p>The second <code class="methodname">use()</code> call fails because
    the first result set hasn&#8217;t been consumed yet.</p></div><div class="footnotes"><br><hr width="100" align="left"><div class="footnote"><p><sup>[<a name="ftn.id2873328" href="#id2873328">1</a>] </sup><code class="classname">SQLQueryParms</code> is used as a
    stream only as an implementation detail within the library. End user
    code simply sees it as a <code class="classname">std::vector</code>
    derivative.</p></div><div class="footnote"><p><sup>[<a name="ftn.id2873362" href="#id2873362">2</a>] </sup>By contrast, the
    <code class="classname">Query</code> methods that take <a href="tutorial.html#ssqlsintro">Specialized SQL Structures</a> <span class="emphasis"><em>do</em></span> add quotes and escape
    strings implicitly. It can do this because SSQLS knows all the SQL
    code and data types, so it never has to guess whether quoting or
    escaping is appropriate.</p></div><div class="footnote"><p><sup>[<a name="ftn.whyexpmanip" href="#whyexpmanip">3</a>] </sup>Unless you&#8217;re smarter than I am, you
    don&#8217;t immediately see why explicit manipulators are necessary.
    We can tell when quoting and escaping is <span class="emphasis"><em>not</em></span>
    appropriate based on type, so doesn&#8217;t that mean we know when
    it <span class="emphasis"><em>is</em></span> appropriate?  Alas, no.  For most data
    types, it is possible to know, or at least make an awfully good
    guess, but it&#8217;s a complete toss-up for C strings, <span class="type">const
    char*</span>. A C string could be either a literal string of SQL
    code, or it can be a value used in a query. Since there&#8217;s no
    easy way to know and it would damage the library&#8217;s usability
    to mandate that C strings only be used for one purpose or the other,
    the library requires you to be explicit.</p></div><div class="footnote"><p><sup>[<a name="ftn.id2873415" href="#id2873415">4</a>] </sup>One hopes the programmer
    <span class="emphasis"><em>knows</em></span>.</p></div><div class="footnote"><p><sup>[<a name="ftn.id2873562" href="#id2873562">5</a>] </sup>This is a new development in MySQL++
      v3.0. Programs built against older versions of MySQL++ would
      crash at almost any mismatch between the database schema and
      the SSQLS definition. This is a serious problem when the design
      of the client programs and the database can&#8217;t be kept
      in lock-step.</p></div><div class="footnote"><p><sup>[<a name="ftn.id2875223" href="#id2875223">6</a>] </sup>In version 2
      of MySQL++ and earlier, <code class="classname">SQLTypeAdapter</code> was
      called <code class="classname">SQLString</code>, but it was confusing
      because its name and the fact that it derived from
      <code class="classname">std::string</code> suggested that it was a
      general-purpose string type. MySQL++ even used it this way in a
      few places internally. In v3, we made it a simple base class and
      renamed it to reflect its proper limited
      function.</p></div><div class="footnote"><p><sup>[<a name="ftn.id2875253" href="#id2875253">7</a>] </sup><code class="classname">SQLTypeAdapter</code>
      doesn&#8217;t do <a href="tutorial.html#qescape">quoting and escaping</a> itself. That happens
      elsewhere, right at the point that the <code class="classname">STA</code>
      gets used to build a query.</p></div><div class="footnote"><p><sup>[<a name="ftn.id2875324" href="#id2875324">8</a>] </sup>If you
      used MySQL++ before v3, <code class="classname">String</code> used to be
      called <code class="classname">ColData</code>. It was renamed because
      starting in v2.3, we began using it for holding more than just
      column data. I considered renaming it
      <code class="classname">SQLString</code> instead, but that would have
      confused old MySQL++ users to no end. Instead, I followed the
      example of <code class="classname">Set</code>, MySQL++&#8217;s specialized
      <code class="classname">std::set</code> variant.</p></div><div class="footnote"><p><sup>[<a name="ftn.id2875419" href="#id2875419">9</a>] </sup>During the development of
      MySQL++ v3.0, I tried merging
      <code class="classname">SQLTypeAdapter</code> and
      <code class="classname">String</code> into a single class to take
      advantage of this. The resulting class gave the C++ compiler the
      freedom to tie itself up in knots, because it was then allowed to
      convert almost any data type to almost any other. You&#8217;d get
      a tangle of ambiguous data type conversion errors from the most
      innocent code.</p></div></div></div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="overview.html">Prev</a></td><td width="20%" align="center"></td><td width="40%" align="right"><a accesskey="n" href="tquery.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">2.Overview</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">4.Template Queries</td></tr></table></div></body></html>