0% found this document useful (0 votes)
5 views326 pages

IBM solidDB 6.5 Programmer Guide

ok

Uploaded by

kinshuk saxena
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views326 pages

IBM solidDB 6.5 Programmer Guide

ok

Uploaded by

kinshuk saxena
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IBM solidDB

IBM solidDB Universal Cache


Version 6.5

Programmer Guide



SC23-9870-06
Note
Before using this information and the product it supports, read the information in “Notices” on page 307.

First edition, sixth revision


This edition applies to version 6, release 5, Fix Pack 14 of IBM solidDB (product number 5724-V17) and IBM
solidDB Universal Cache (product number 5724-W91) and to all subsequent releases and modifications until
otherwise indicated in new editions.

Note: Information in this document might have been updated since this document was made available. For the
latest available information, see the IBM solidDB and IBM solidDB Universal Cache V6.5 Information Center at
[Link]
© Oy International Business Machines Ab Ltd. 1993, 2013
Contents
Figures . . . . . . . . . . . . . . vii Processing error messages . . . . . . . . 40
Terminating transactions and connections . . . . 40
Tables . . . . . . . . . . . . . . . ix Constructing an application . . . . . . . . . 41
Testing and debugging an application . . . . . 49

Summary of changes . . . . . . . . . xi
3 Using solidDB JDBC Driver . . . . . 51
What is solidDB JDBC Driver . . . . . . . . 51
About this manual . . . . . . . . . xiii Getting started with solidDB JDBC Driver . . . . 51
Typographic conventions . . . . . . . . . xiii Registering solidDB JDBC Driver . . . . . . 53
Syntax notation conventions . . . . . . . . xiv Connecting to the database . . . . . . . . 54
Special notes about solidDB and JDBC . . . . . 56
1 Introduction to solidDB APIs . . . . . 1 JDBC driver interfaces and methods . . . . . . 56
solidDB ODBC Driver . . . . . . . . . . . 1 solidDB JDBC Driver extensions . . . . . . . 62
Using solidDB ODBC Driver functions. . . . . 2 WebSphere compatibility . . . . . . . . . 63
ODBC API basic application steps . . . . . . 2 Connection timeout in JDBC. . . . . . . . 64
Format of the solidDB connect string . . . . . 3 Non-standard connection properties . . . . . 64
Client-side configuration file . . . . . . . . 5 JDBC 2.0 optional package API support . . . . . 68
ODBC non-standard behavior . . . . . . . 6 JDBC connection pooling . . . . . . . . . 68
solidDB JDBC Driver . . . . . . . . . . . 6 solidDB Connected RowSet Class:
solidDB Application Programming Interface (SA API) 7 SolidJDBCRowSet . . . . . . . . . . . 77
solidDB Server Control API (SSC API) . . . . . . 7 Java Naming and Directory Interface (JNDI) . . 78
Building client applications . . . . . . . . . 7 Code examples . . . . . . . . . . . . . 78
What is a client? . . . . . . . . . . . . 7 solidDB JDBC Driver type conversion matrix . . . 90
How is the query passed to the server? . . . . 7
How are the results passed back to the client? . . 9 4 Using solidDB SA . . . . . . . . . 93
Using the ODBC driver library . . . . . . . 9 What is solidDB SA? . . . . . . . . . . . 93
Statement cache . . . . . . . . . . . . 10 Getting started with solidDB SA . . . . . . . 94
Writing data by using solidDB SA without SQL . . 95
2 Using solidDB ODBC API . . . . . . 11 Reading data by using solidDB SA without SQL . . 97
Installing solidDB ODBC Driver . . . . . . . 11 Running SQL Statements by Using solidDB SA . . 99
solidDB ODBC Driver 3.51 Features Support . . . 12 Transactions and autocommit mode . . . . . . 99
Overview of usage on Windows operating systems 12 Handling database errors . . . . . . . . . 100
Calling functions . . . . . . . . . . . . 13 Special notes about solidDB SA . . . . . . . 101
Connecting to a data source . . . . . . . . . 15 solidDB SA Function Reference . . . . . . . 103
Network name and connect string syntax . . . 16 SaArrayFlush . . . . . . . . . . . . 105
Using logical data source names . . . . . . 18 SaArrayInsert . . . . . . . . . . . . 106
Empty data source name . . . . . . . . . 19 SaColSearchCreate. . . . . . . . . . . 106
Configuring the solidDB ODBC Data Source for SaColSearchFree . . . . . . . . . . . 107
Windows . . . . . . . . . . . . . . 20 SaColSearchNext . . . . . . . . . . . 107
Using solidDB ODBC Driver with unixODBC . . 20 SaConnect . . . . . . . . . . . . . 108
Retrieving user login information . . . . . . 22 SaCursorAscending . . . . . . . . . . 108
ODBC handle validation . . . . . . . . . . 23 SaCursorAtleast . . . . . . . . . . . 109
Executing transactions . . . . . . . . . . . 24 SaCursorAtmost . . . . . . . . . . . 109
Retrieving information about the data source's SaCursorBegin . . . . . . . . . . . . 110
catalog . . . . . . . . . . . . . . . . 26 SaCursorClearConstr . . . . . . . . . . 110
Using ODBC extensions to SQL . . . . . . . 26 SaCursorColData . . . . . . . . . . . 111
Procedures . . . . . . . . . . . . . 26 SaCursorColDate . . . . . . . . . . . 112
Hints . . . . . . . . . . . . . . . 27 SaCursorColDateFormat . . . . . . . . . 113
Additional ODBC extension functions . . . . 28 SaCursorColDfloat. . . . . . . . . . . 113
solidDB Extensions for ODBC API. . . . . . . 29 SaCursorColDouble . . . . . . . . . . 114
Using cursors. . . . . . . . . . . . . . 31 SaCursorColDynData . . . . . . . . . . 115
Assigning storage for rowsets (binding) . . . . 32 SaCursorColDynStr . . . . . . . . . . 116
Cursor support . . . . . . . . . . . . 33 SaCursorColFloat . . . . . . . . . . . 117
Using bookmarks . . . . . . . . . . . . 38 SaCursorColInt . . . . . . . . . . . . 118
Error text format . . . . . . . . . . . . 38 SaCursorColLong . . . . . . . . . . . 119

iii
SaCursorColNullFlag . . . . . . . . . . 119 SaSetTimestampFormat . . . . . . . . . 155
SaCursorColStr . . . . . . . . . . . . 120 SaSQLExecDirect . . . . . . . . . . . 155
SaCursorColTime . . . . . . . . . . . 121 SaTransBegin . . . . . . . . . . . . 156
SaCursorColTimestamp . . . . . . . . . 122 SaTransCommit . . . . . . . . . . . 156
SaCursorCreate . . . . . . . . . . . . 122 SaTransRollback . . . . . . . . . . . 157
SaCursorDelete . . . . . . . . . . . . 123 SaUserId . . . . . . . . . . . . . . 157
SaCursorDescending . . . . . . . . . . 123
SaCursorEnd . . . . . . . . . . . . 124 5 Using Unicode . . . . . . . . . . 159
SaCursorEqual . . . . . . . . . . . . 124 What is Unicode? . . . . . . . . . . . . 160
SaCursorErrorInfo . . . . . . . . . . . 125 Designing Unicode databases . . . . . . . . 161
SaCursorFree . . . . . . . . . . . . 125 Using solidDB tools with Unicode . . . . . . 163
SaCursorInsert . . . . . . . . . . . . 126 Compatibility between Unicode and partial
SaCursorLike . . . . . . . . . . . . 126 Unicode databases. . . . . . . . . . . . 164
SaCursorNext . . . . . . . . . . . . 127 Converting partial Unicode databases to
SaCursorOpen . . . . . . . . . . . . 127 Unicode . . . . . . . . . . . . . . 164
SaCursorOrderbyVector . . . . . . . . . 127 Developing applications for Unicode . . . . . 166
SaCursorPrev . . . . . . . . . . . . 128 ODBC applications and Unicode databases . . 167
SaCursorReSearch . . . . . . . . . . . 129 JDBC applications and Unicode databases . . . 169
SaCursorSearch. . . . . . . . . . . . 129
SaCursorSearchByRowid . . . . . . . . 130
6 Using Transaction Log Reader . . . 171
SaCursorSearchReset . . . . . . . . . . 130
Considerations for developing applications with
SaCursorSetLockMode . . . . . . . . . 132
Log Reader . . . . . . . . . . . . . . 171
SaCursorSetPosition . . . . . . . . . . 133
Configuring the Log Reader . . . . . . . . 173
SaCursorSetRowsPerMessage . . . . . . . 134
Reading log data with the Log Reader . . . . . 174
SaCursorUpdate . . . . . . . . . . . 134
Partitioning and filtering log records . . . . . 175
SaDateCreate . . . . . . . . . . . . 135
Creating and deleting partitions . . . . . . 175
SaDateFree . . . . . . . . . . . . . 135
Using partition filters. . . . . . . . . . 175
SaDateSetAsciiz . . . . . . . . . . . 135
Setting transaction batches . . . . . . . . . 176
SaDateSetTimet . . . . . . . . . . . . 136
SaDateToAsciiz . . . . . . . . . . . . 137
SaDateToTimet . . . . . . . . . . . . 138 Appendix A. solidDB supported ODBC
SaDefineChSet . . . . . . . . . . . . 138 functions . . . . . . . . . . . . . 177
SaDfloatCmp . . . . . . . . . . . . 139
SaDfloatDiff . . . . . . . . . . . . . 139 Appendix B. solidDB ODBC Driver
SaDfloatOverflow . . . . . . . . . . . 140 3.5.1 attributes support . . . . . . . 187
SaDfloatProd . . . . . . . . . . . . 140
SaDfloatQuot . . . . . . . . . . . . 141
SaDfloatSetAsciiz . . . . . . . . . . . 141 Appendix C. SQLSTATE error codes 195
SaDfloatSum . . . . . . . . . . . . 142
SaDfloatToAsciiz . . . . . . . . . . . 142 Appendix D. Minimum SQL grammar
SaDfloatUnderflow . . . . . . . . . . 143 requirements for ODBC . . . . . . . 217
SaDisconnect . . . . . . . . . . . . 143 SQL statements . . . . . . . . . . . . . 217
SaDynDataAppend . . . . . . . . . . 143 Control statements (logical condition) . . . . 218
SaDynDataChLen . . . . . . . . . . . 144 Data type support . . . . . . . . . . . . 219
SaDynDataClear . . . . . . . . . . . 145 Parameter data types . . . . . . . . . . . 220
SaDynDataCreate . . . . . . . . . . . 145 Literals in ODBC . . . . . . . . . . . . 221
SaDynDataFree . . . . . . . . . . . . 146 List of reserved keywords . . . . . . . . . 222
SaDynDataGetData . . . . . . . . . . 146
SaDynDataGetLen . . . . . . . . . . . 147 Appendix E. Data types . . . . . . . 225
SaDynDataMove . . . . . . . . . . . 147
SQL data types . . . . . . . . . . . . . 225
SaDynDataMoveRef . . . . . . . . . . 148
C data types. . . . . . . . . . . . . . 225
SaDynStrAppend . . . . . . . . . . . 149
Data type identifiers . . . . . . . . . . . 226
SaDynStrCreate. . . . . . . . . . . . 150
SQL data types . . . . . . . . . . . . . 226
SaDynStrFree . . . . . . . . . . . . 150
C data types. . . . . . . . . . . . . . 230
SaDynStrMove . . . . . . . . . . . . 150
Numeric literals . . . . . . . . . . . . 235
SaErrorInfo . . . . . . . . . . . . . 151
Overriding default precision and scale for numeric
SaGlobalInit . . . . . . . . . . . . . 152
data types . . . . . . . . . . . . . . 237
SaSetDateFormat . . . . . . . . . . . 152
Data type identifiers and descriptors . . . . . 238
SaSetSortBufSize . . . . . . . . . . . 153
Decimal digits . . . . . . . . . . . . . 239
SaSetSortMaxFiles . . . . . . . . . . . 153
Transfer octet length . . . . . . . . . . . 240
SaSetTimeFormat . . . . . . . . . . . 154
Constraints of the gregorian calendar . . . . . 242

iv IBM solidDB: Programmer Guide


Converting data from SQL to C data types . . . 243 Server timeouts. . . . . . . . . . . . . 290
Data conversion tables from SQL to C . . . . 245 HotStandby timeouts . . . . . . . . . . . 293
SQL to C data conversion examples . . . . . 255
Converting data from C to SQL data types . . . 256 Appendix H. Client-side configuration
Data conversion tables from C to SQL . . . . 258 parameters . . . . . . . . . . . . 295
C to SQL data conversion examples . . . . . 269
Setting client-side parameters through the [Link]
configuration file . . . . . . . . . . . . 295
Appendix F. Scalar functions. . . . . 271 Client section . . . . . . . . . . . . . 296
ODBC and SQL-92 scalar functions . . . . . . 271 Communication section . . . . . . . . . . 297
String functions . . . . . . . . . . . . 271 Data Sources section . . . . . . . . . . . 298
Numeric functions. . . . . . . . . . . . 275 SharedMemoryAccess section . . . . . . . . 298
Time and date functions . . . . . . . . . . 278 TransparentFailover section. . . . . . . . . 299
System functions . . . . . . . . . . . . 283
Explicit data type conversion . . . . . . . . 284 Index . . . . . . . . . . . . . . . 301
SQL-92 CAST function . . . . . . . . . . 285

Notices . . . . . . . . . . . . . . 307
Appendix G. Timeout controls . . . . 287
Client timeouts . . . . . . . . . . . . . 287

Contents v
vi IBM solidDB: Programmer Guide
Figures
1. ODBC driver setup . . . . . . . . . . 20 2. ODBC data source administrator . . . . . 23

vii
viii IBM solidDB: Programmer Guide
Tables
1. Typographic conventions . . . . . . . . xiii 54. SaColSearchCreate Parameters . . . . . . 107
2. Syntax notation conventions. . . . . . . xiv 55. SaColSearchNext Parameters . . . . . . 107
3. Connect string options . . . . . . . . . 3 56. SaColSearchNext Return Value . . . . . . 108
4. Connect string options . . . . . . . . . 17 57. SaConnect Parameters . . . . . . . . 108
5. Additional ODBC Extension Functions . . . 29 58. SaConnect Return Value . . . . . . . . 108
6. solidDB-specific ODBC functions to ODBC API 29 59. SaCursorAscending parameters . . . . . 109
7. A Sample Resultset . . . . . . . . . . 35 60. SaCursorAtleast Parameters . . . . . . . 109
8. A sample resultset . . . . . . . . . . 35 61. SaCursorAtmost Parameters . . . . . . 110
9. A sample resultset . . . . . . . . . . 36 62. SaCursorBegin Parameters . . . . . . . 110
10. A Sample Resultset . . . . . . . . . . 36 63. SaCursorClearConstr Parameters . . . . . 110
11. A Sample Resultset . . . . . . . . . . 37 64. SaCursorColData Parameters . . . . . . 112
12. Errors in a Data Source . . . . . . . . 39 65. SaCursorColDate Parameters . . . . . . 112
13. Sample Error Messages . . . . . . . . 39 66. SaCursorColDateFormat parameters . . . . 113
14. SQLSTATE values . . . . . . . . . . 39 67. SaCursorColDfloat Parameters . . . . . . 114
15. Differences to the Standard CallableStatement 68. SaCursorColDouble Parameters . . . . . 114
Interface . . . . . . . . . . . . . 57 69. SaCursorColDynData Parameters . . . . . 116
16. Differences to the Standard Connection 70. SaCursorColDynStr Parameters . . . . . 117
Interface . . . . . . . . . . . . . 58 71. SaCursorColFloat Parameters . . . . . . 117
17. Differences to the Standard PreparedStatement 72. SaCursorColInt Parameters . . . . . . . 118
Interface . . . . . . . . . . . . . 59 73. SaCursorColLong Parameters . . . . . . 119
18. Differences to the Standard ResultSet Interface 60 74. SaCursorColNullFlag Parameters . . . . . 120
19. Differences to the Standard Statement Interface 61 75. SaCursorColStr Parameters . . . . . . . 121
20. Differences to the Standard ResultSet Interface 62 76. SaCursorColTime parameters . . . . . . 121
21. Constructor . . . . . . . . . . . . 69 77. SaCursorColTimestamp parameters . . . . 122
22. Constructor . . . . . . . . . . . . 69 78. SaCursorCreate Parameters . . . . . . . 123
23. setDescription. . . . . . . . . . . . 69 79. Return Value. . . . . . . . . . . . 123
24. getDescription . . . . . . . . . . . 70 80. SaCursorDelete parameters . . . . . . . 123
25. setURL . . . . . . . . . . . . . . 70 81. SaCursorDescending parameters . . . . . 124
26. getURL . . . . . . . . . . . . . . 70 82. SaCursorEnd parameters. . . . . . . . 124
27. setUser . . . . . . . . . . . . . . 71 83. SaCursorEqual parameters . . . . . . . 124
28. getUser . . . . . . . . . . . . . . 71 84. SaCursorErrorInfo parameters . . . . . . 125
29. setPassword . . . . . . . . . . . . 72 85. SaCursorFree parameters. . . . . . . . 125
30. getPassword . . . . . . . . . . . . 72 86. SaCursorInsert parameters . . . . . . . 126
31. setConnectionURL . . . . . . . . . . 72 87. SaCursorLike parameters . . . . . . . 126
32. getConnectionURL . . . . . . . . . . 73 88. SaCursorNext parameters . . . . . . . 127
33. getLoginTimeout . . . . . . . . . . . 73 89. SaCursorOpen parameters . . . . . . . 127
34. getLogWriter . . . . . . . . . . . . 73 90. SaCursorOrderbyVector parameters . . . . 128
35. getPooledConnection . . . . . . . . . 74 91. SaCursorPrev parameters . . . . . . . 129
36. getPooledConnection . . . . . . . . . 74 92. SaCursorReSearch Parameters . . . . . . 129
37. setLoginTimeout . . . . . . . . . . . 74 93. SaCursorSearch parameters . . . . . . . 129
38. setLogWriter . . . . . . . . . . . . 75 94. SaCursorSearchByRowid parameters . . . . 130
39. addConnectionEventListener . . . . . . . 75 95. SaCursorSearchReset Parameters . . . . . 132
40. close . . . . . . . . . . . . . . . 76 96. SaCursorSetLockMode Parameters . . . . 133
41. getConnection. . . . . . . . . . . . 76 97. SaCursorSetPosition parameters . . . . . 133
42. removeConnectionEventListener . . . . . 76 98. SaCursorSetRowsPerMessage parameters 134
43. Java data type to SQL data type conversion 90 99. SaCursorUpdate parameters . . . . . . 134
44. Insert operation steps . . . . . . . . . 95 100. SaDateCreate Return Values. . . . . . . 135
45. Update and delete operation steps . . . . . 96 101. SaDateFree parameters . . . . . . . . 135
46. Query Operation Steps . . . . . . . . . 98 102. SaDateSetAsciiz Parameters . . . . . . . 136
47. solidDB SA Function Return Codes . . . . 100 103. SaDateSetTimet parameters . . . . . . . 137
48. Supported SQL Datatype. . . . . . . . 102 104. SaDateToAsciiz parameters . . . . . . . 137
49. solidDB SA Parameter Usage Types . . . . 104 105. SaDateToTimet parameters . . . . . . . 138
50. Return Usage Types for Pointers . . . . . 105 106. SaDefineChSet parameters . . . . . . . 138
51. SaArrayFlush Parameters . . . . . . . 105 107. SaDfloatCmp parameters. . . . . . . . 139
52. SaArrayInsert Parameters . . . . . . . 106 108. SaDfloatDiff parameters . . . . . . . . 139
53. SaColSearchCreate Parameters . . . . . . 107 109. SaDfloatOverflow parameters . . . . . . 140

ix
110. SaDfloatProd Parameters. . . . . . . . 140 160. ODBC Functions' Return Parameter . . . . 239
111. SaDfloatQuot parameters . . . . . . . 141 161. SQL data type decimal digits . . . . . . 240
112. SaDfloatSetAsciiz parameters . . . . . . 141 162. Descriptor field corresponding to decimal
113. SaDfloatSum parameters . . . . . . . . 142 digits . . . . . . . . . . . . . . 240
114. SaDfloatToAsciiz parameters . . . . . . 142 163. ODBC Functions' Return parameter Decimal
115. SaDfloatUnderflow parameters. . . . . . 143 Attributes . . . . . . . . . . . . . 241
116. SaDisconnect Parameters. . . . . . . . 143 164. Transfer Octet Lengths . . . . . . . . 241
117. SaDynDataAppend parameters . . . . . 144 165. Constraints of the Gregorian Calendar 242
118. SaDynDataChLen Parameters . . . . . . 144 166. C Data Type — SQL_C_datatype where
119. SaDynDataClear Parameters . . . . . . 145 Datatype Is: . . . . . . . . . . . . 244
120. SaDynDataCreate Return Value . . . . . 146 167. Character SQL Data to ODBC C Data Types 246
121. SaDynDataFree parameters . . . . . . . 146 168. SQL Data to ODBC C Data Types . . . . . 249
122. SaDynDataGetData parameters . . . . . 146 169. Binary SQL Data to ODBC C Data Types 251
123. SaDynDataGetData Parameters . . . . . 147 170. Date SQL Data to ODBC C Data Types 252
124. SaDynDataMove Parameters . . . . . . 148 171. Time SQL Data to ODBC C Data Types 253
125. SaDynDataMoveRef Parameters . . . . . 149 172. Timestamp SQL Data to ODBC C Data Types 254
126. SaDynStrAppend parameters . . . . . . 149 173. SQL to C Data Conversion Examples 255
127. SaDynStrCreate Return Value . . . . . . 150 174. SQL Data Type — SQL_datatype where
128. SaDynStrFree parameters . . . . . . . 150 Datatype Is: . . . . . . . . . . . . 257
129. SaDynStrMove Parameters . . . . . . . 151 175. C Character Data to ODBC SQL Data Types 259
130. SaErrorInfo Parameters . . . . . . . . 151 176. Numeric C Data to ODBC SQL Data Types 263
131. SaSetDateFormat Parameters . . . . . . 152 177. Bit C Data to ODBC SQL Data Types 264
132. SaSetSortBufSize Parameters . . . . . . 153 178. Binary C Data to ODBC SQL Data Types 265
133. SaSetSortMaxFiles parameters . . . . . . 154 179. Date C Data to ODBC SQL Data Types 266
134. SaSetTimeFormat Parameters . . . . . . 154 180. Time C Data to ODBC SQL Data Types 267
135. SaSetTimestampFormat parameters . . . . 155 181. Timestamp C Data to ODBC SQL Data Ttypes 268
136. SaSQLExecDirect Parameters . . . . . . 155 182. C Data to SQL Data . . . . . . . . . 269
137. SaTransBegin parameters. . . . . . . . 156 183. String Function Arguments . . . . . . . 272
138. SaTransCommit Parameters . . . . . . . 157 184. List of String Functions . . . . . . . . 272
139. SaTransRollback Parameters. . . . . . . 157 185. Numeric Function Arguments . . . . . . 275
140. SaUserId Parameters . . . . . . . . . 157 186. List of Numeric Functions . . . . . . . 276
141. Command line options for solidDB tools for 187. Time and Data Arguments . . . . . . . 278
partial Unicode and Unicode databases . . . 164 188. List of Time and Date Functions . . . . . 278
142. solidDB supported ODBC functions . . . . 177 189. System Function Arguments . . . . . . 283
143. 001 Environment Level . . . . . . . . 187 190. List of System Functions . . . . . . . . 283
144. 002 Connection Level . . . . . . . . . 188 191. Login timeouts . . . . . . . . . . . 287
145. 03 Statement Level . . . . . . . . . . 189 192. Connection timeout . . . . . . . . . 288
146. 04 Column Attributes . . . . . . . . . 192 193. Query Timeout . . . . . . . . . . . 290
147. Error code class values . . . . . . . . 195 194. SQL statement execution timeouts . . . . 291
148. SQLSTATE codes . . . . . . . . . . 195 195. Lock wait timeout . . . . . . . . . . 291
149. Control Statements. . . . . . . . . . 218 196. Optimistic lock wait timeout . . . . . . 292
150. Determining Data Ttype for Several Types of 197. Table lock wait timeout . . . . . . . . 292
Parameters . . . . . . . . . . . . 220 198. Transaction Idle Timeout . . . . . . . . 293
151. List of Reserved Keywords . . . . . . . 222 199. connection idle timeout . . . . . . . . 293
152. Common SQL Data Type Names, Ranges, and 200. Connect timeout . . . . . . . . . . 294
Limits . . . . . . . . . . . . . . 227 201. Ping timeout . . . . . . . . . . . . 294
153. Data types SQLGetTypeInfo returns (1) 229 202. Transparent connection timeout . . . . . 294
154. Data Types SQLGetTypeInfo Returns (2) 229 203. Client parameters . . . . . . . . . . 296
155. Data Types SQLGetTypeInfo Returns (3) 229 204. Communication parameters . . . . . . . 297
156. C vs ODBC Naming Correspondence 231 205. Data Sources parameters . . . . . . . . 298
157. Conversions Involving Numeric Literals 235 206. Shared memory access parameters
158. Override Default Precision and Scale Values (client-side) . . . . . . . . . . . . 298
for Numeric Data Type . . . . . . . . 237 207. TransparentFailover parameters . . . . . 299
159. Concise Type Identifier, Verbose Identifier,
and Type Subcode for Each Datetime . . . 238

x IBM solidDB: Programmer Guide


Summary of changes
Changes for revision 06
v Editorial corrections.

Changes for revision 05


v Information about timeout unit for JDBC method setQueryTimeout() updated in
section Server timeouts. As of V6.5 Fix Pack 12, the timeout unit in SMA
connections is the same as in network-based connections, that is, the timeout
unit is seconds.

Changes for revision 04


v Factory value for parameter [Link] changed from yes to no in section
Client-side configuration parameters.
v Information about support for uppercase and lowercase conversions in Unicode
databases updated in section Developing applications for Unicode: conversions
are now supported for all Unicode characters.
v Section for client-side parameter ODBCHandleValidation corrected; the
ODBCHandleValidation is in the Client section.
v New JDBC connection properties added in section Non-standard connection
properties:
– "solid_socket_linger"
– "solid_socket_linger_time"
v Previously undocumented client-side parameters [Link] and
[Link] added in section Client-side configuration parameters.

Changes for revision 03


v Example of solidDB® connect string with SQLDriverConnect added in section
“Format of the solidDB connect string” on page 3.
v New timeout controls for TF connections added in section HotStandby timeouts.
v New client-side parameters [Link] and
[Link] added in section TransparentFailover section
v Information about system-level and user-level unixODBC configuration files
added in section Using solidDB ODBC Driver with unixODBC.

Changes for revision 02


v Information about the solidDB Light Client has been removed; solidDB Light
Client is deprecated as of 6.5 Fix Pack 4.
v The C type definition corresponding to the ODBC C Typedef SQLINTEGER
corrected to int and SQLUINTEGER to unsigned int in section C data types
v SQL error code class values corrected in section SQLSTATE error codes: Error
class 01 returns both warnings and errors.

Changes for revision 01


v Factory value for connection timeout corrected from 60 000 milliseconds to 0
(infinite); parameters [Link] and [Link] (option -r)
updated in sections Client timeouts, Format of the solidDB connect string, and
Communication section.

xi
v Information on the precision implementation in the functions CURRENT_TIME,
CURTIME, CURRENT_TIMESTAMP, and NOW updated in section Time and
date functions; a milliseconds precision can be defined as an argument (0-6).
v Section Developing applications for Unicode updated: the [Link]=yes
parameter setting is not effective in Unicode databases; blank characters in
CHAR values are always discarded.
v Section Client timeouts updated: the behaviour of client connection timeouts has
changed. If the client can detect reliably that the server is not reachable,
SQLConnect returns immediately, regardless of the timeout setting specified
with, for example, SQL_ATTR_LOGIN_TIMEOUT. This can happen, for
example, if the server is expected to run on the same host, and the client detects
that the server is not running.
v New JDBC connection properties "solid_catalog" and "solid_schema" added in
section Non-standard connection properties.
v The following Optimizer hints have been added in section Hints:
– TRIPLE MERGE JOIN
– UNION FOR OR
– OR FOR OR
– LOOP FOR OR
v Transaction Log Reader usage instructions updated in section Reading log data
with the Log Reader.

xii IBM solidDB: Programmer Guide


About this manual
This guide contains information about using IBM® solidDB through the different
Application Programming Interfaces, with or without the shared memory access
(SMA), linked library access (LLA), or HotStandby.

solidDB ODBC Driver, solidDB Light Client, and solidDB JDBC Driver help your
client application access solidDB.
v The solidDB ODBC Driver conforms to the Microsoft ODBC 3.51 API standard.
v The solidDB Light Client is a lightweight version of the solidDB ODBC API and
is intended for environments where the footprint of the client application must
be very small.
v The solidDB JDBC Driver is a solidDB implementation of the JDBC 2.0 standard.

This guide assumes general knowledge of relational databases and SQL. It also
assumes familiarity with solidDB. If you will use the ODBC driver, this manual
assumes a working knowledge of the C programming language. If you will use the
JDBC driver, this manual assumes a working knowledge of the Java™
programming language.

Typographic conventions
solidDB documentation uses the following typographic conventions:
Table 1. Typographic conventions
Format Used for

Database table This font is used for all ordinary text.

NOT NULL Uppercase letters on this font indicate SQL keywords and
macro names.

[Link] These fonts indicate file names and path expressions.

SET SYNC MASTER YES;


COMMIT WORK; This font is used for program code and program output.
Example SQL statements also use this font.

[Link] This font is used for sample command lines.

TRIG_COUNT() This font is used for function names.

[Link] This font is used for interface names.

LockHashSize This font is used for parameter names, function arguments,


and Windows registry entries.

argument Words emphasized like this indicate information that the


user or the application must provide.

xiii
Table 1. Typographic conventions (continued)
Format Used for

Administrator Guide This style is used for references to other documents, or


chapters in the same document. New terms and emphasized
issues are also written like this.

File path presentation Unless otherwise indicated, file paths are presented in the
UNIX format. The slash (/) character represents the
installation root directory.

Operating systems If documentation contains differences between operating


systems, the UNIX format is mentioned first. The Microsoft
Windows format is mentioned in parentheses after the
UNIX format. Other operating systems are separately
mentioned. There may also be different chapters for
different operating systems.

Syntax notation conventions


solidDB documentation uses the following syntax notation conventions:
Table 2. Syntax notation conventions
Format Used for

INSERT INTO table_name


Syntax descriptions are on this font. Replaceable sections are
on this font.

[Link] This font indicates file names and path expressions.

[] Square brackets indicate optional items; if in bold text,


brackets must be included in the syntax.

| A vertical bar separates two mutually exclusive choices in a


syntax line.

{} Curly brackets delimit a set of mutually exclusive choices in


a syntax line; if in bold text, braces must be included in the
syntax.

... An ellipsis indicates that arguments can be repeated several


times.

.
. A column of three dots indicates continuation of previous
. lines of code.

xiv IBM solidDB: Programmer Guide


1 Introduction to solidDB APIs
solidDB supports ODBC and JDBC interfaces that enable application developers to
write applications with C or Java languages calling ODBC functions or JDBC
methods and writing or generating the SQL string at the application level. solidDB
also provides two proprietary interfaces, solidDB Application Programming
Interface (SA API) and solidDB Server Control API (SSC API). These allow, for
example, C programs to directly call functions inside the database server. These
proprietary interfaces are provided with the linked library access (LLA) and shared
memory access (SMA) libraries.

Other programming environments

Multiple ways exist to raise the abstraction level from the ODBC/JDBC level. It
can be done either by enabling database access from various (usually higher level
programming or scripting languages, such as Visual Basic, Perl, and PHP) or
enabling database access directly through application level objects that are able to
load or save themselves without the application programmer having to be aware
of database connections, transactions, or even SQL Strings.

Database access from higher level programming is usually based on some


middleware component translating the higher level language calls to regular ODBC
or JDBC calls. In these conditions, the middleware component is seen as an
application from the database perspective. Usually the middleware components
hide the difference between database brands. However, as solidDB is a relatively
new product, not all middleware vendors explicitly list it among the supported
database products. In those cases, there is usually an option to have a generic
ODBC database or generic JDBC database that works with solidDB drivers.

Certain programming environments do not have a direct counterpart in solidDB


applications, such as Embedded SQL or Java-based stored procedures. Applications
designed to run on these programming environments must be redesigned to fit
solidDB.

solidDB ODBC Driver


The native solidDB ODBC Driver conforms to the Microsoft ODBC 3.5.1 API
standard.

The solidDB ODBC Driver is a distributed in the form of a library (a Dynamic Link
Library (DLL) on Windows). ThesolidDB installation package includes two ODBC
drivers: one for Unicode and one for ASCII. The Unicode version is a superset of
the ASCII version; you may use it with either Unicode or ASCII character sets.

The solidDB implementation of the ODBC API supports a rich set of database
access operations sufficient for creating robust database applications, including:
v Allocating and deallocating handles
v Getting and setting attributes
v Opening and closing database connections
v Accessing descriptors
v Executing SQL statements

1
v Accessing schema metadata
v Controlling transactions
v Accessing diagnostic information

Depending on the application's request, the solidDB ODBC Driver can


automatically commit each SQL statement or wait for an explicit commit or
rollback request. When the driver performs a commit or rollback operation, the
driver resets all statement requests associated with the connection.

Using solidDB ODBC Driver functions


Users on all platforms can access ODBC Driver supported functions with solidDB
ODBC API.

The solidDB ODBC API is the native call level interface (CLI) for solidDB
databases. It is a distributed in the form of a library (a Dynamic Link Library
(DLL) on Windows). The solidDB ODBC API is compliant with ANSI X3H2 SQL
CLI standard.

solidDB's implementation of ODBC API supports a rich set of database access


operations sufficient for creating robust database applications, including:
v Allocating and deallocating handles
v Getting and setting attributes
v Opening and closing database connections
v Accessing descriptors
v Executing SQL statements
v Accessing schema metadata
v Controlling transactions
v Accessing diagnostic information

Depending on the application's request, the solidDB ODBC Driver can


automatically commit each SQL statement or wait for an explicit commit or
rollback request. When the driver performs a commit or rollback operation, the
driver resets all statement requests associated with the connection.

ODBC API basic application steps


A client database application calls the solidDB ODBC API directly (or through the
ODBC Driver Manager) to perform all interactions with a database. For example,
to insert, delete, update, or select records, you make a series of calls to functions in
the ODBC API.

An application using ODBC API performs the following tasks:.


1. The application allocates memory and creates handles, and establishes a
connection to the database.
a. The application allocates memory for an environment handle (henv) and a
connection handle (hdbc); both are required to establish a database
connection.
An application may request multiple connections for one or more data
sources. Each connection is considered a separate transaction space. In other
words, a COMMIT or ROLLBACK on one connection will not commit or
rollback any statements executed through any other connection.

2 IBM solidDB: Programmer Guide


b. The SQLConnect() call establishes the database connection, specifying the
server name (a connect string or a data source name), user id, and
password.
c. The application then allocates memory for a statement handle.
2. The application executes the statement. This requires a series of function calls.
a. The application calls either SQLExecDirect(), which both prepares and
executes an SQL statement, or SQLPrepare() and SQLExecute(), which
allows statements to be executed multiple times.
b. If the statement was a SELECT, the result columns must be bound to
variables in the application so that the application can see the returned data.
The SQLBindCol() function will bind the application's variables to the
columns of the result set. The rows can then be fetched using SQLFetch()
repeatedly. SELECT statements must be committed as soon as processing of
the resultset is done.
If the statement was an UPDATE, DELETE, or INSERT, then the application
needs to check if the execution succeeded and call SQLEndTran() to commit
the transaction.
3. Finally the application closes the connection and frees any handles.
a. The application frees the statement handle.
b. The application closes the connection.
c. The application frees the connection and environment handles (hdbc and
henv).

Note that step 2 (executing SQL statements) may be done repeatedly, depending
upon how many SQL statements need to be executed.

Read 2, “Using solidDB ODBC API,” on page 11 for more information about using
these API calls.

Format of the solidDB connect string


The client processes use the solidDB connect string (network name) to specify
which server it will connect to.

A default connect string can be defined with the client-side [Link]


configuration parameter. The connect string can also be supplied, for example, at
connection time or when configuring data sources with an ODBC driver manager.

The same format of the connect string applies to the [Link] parameter as
well as to the connect string used by solidDB tools or ODBC applications.

The format of a connect string is the following:


protocol_name [options] [host_computer_name] server_name

where
v options can be any combination of the following:
Table 3. Connect string options

Option Description Protocol


-4 Specifies that client connects using IPv4 protocol only. TCP/IP
-6 Specifies that client connects using IPv6 protocol only. TCP/IP

In Windows environments, this option is mandatory if IPv6 protocol is used.

1 Introduction to solidDB APIs 3


Table 3. Connect string options (continued)

Option Description Protocol


All
-z Enables data compression for this connection
-c milliseconds Specifies the login timeout (the default is operating-system-specific). A login request TCP/IP
fails after the specified time has elapsed.
Specifies the connection (or read) timeout. A network request fails when no response is TCP/IP
-r milliseconds received during the time specified. The value 0 (default) sets the timeout to infinite
(operating system default timeout applies).
-ofilename Turns on the Network trace facility and defines the name of the trace output file All

See Network trace facility in the IBM solidDB Administrator Guide for details.
-plevel Pings the server at the given level (0-5). All

Clients can always use the solidDB Ping facility at level 1 (0 is no operation/default).
Levels 2, 3, 4 or 5 may only be used if the server is set to use the Ping facility at least at
the same level.

See Ping facility in the IBM solidDB Administrator Guide for details.
-t Turns on the Network trace facility All

See Network trace facility in the IBM solidDB Administrator Guide for details.

v host_computer_name is needed with TCP/IP and Named Pipes protocols, if the


client and server are running on different machines.
v server_name depends on the communication protocol:
– In TCP/IP protocol, server_name is a service port number, such as '2315'.
– In other protocols, server_name is a name, such as 'soliddb' or 'chicago_office'.
For details on the syntax in different communication protocols, see
Communication protocols in the IBM solidDB Administrator Guide.

Note:
v The protocol_name and the server_name must match the ones that the server is
using in its network listening name.
v If given at the connection time, the connect string must be enclosed in double
quotation marks.
v All components of the connect string are case insensitive.

Examples
[Com]
Connect=tcp -z -c1000 1315
[Com]
Connect=nmpipe host22 SOLID
solsql "tcp localhost 1315"
solsql "tcp [Link] 1315"
rc = SQLConnect(hdbc, "upipe SOLID", (SWORD)SQL_NTS, "dba", 3, "dba", 3);
rc = SQLDriverConnect(hdbc,
(SQLHWND)NULL,
(SQLCHAR*)"DSN=tcp localhost 1964;UID=dba;PWD=dba",
38,
out_string,
255,
&out_length,
SQL_DRIVER_NOPROMPT);
Related concepts:

4 IBM solidDB: Programmer Guide


“Connecting to a data source” on page 15
A data source can be a database server, a flat file, or another source of data.

Client-side configuration file


solidDB gets its client configuration information from the client-side [Link] file.
The client-side configuration file is used if the ODBC driver is used and the file
must be located in the working directory of the application.

Important: In most cases, only solidDB server-side parameters are used when
programming for the solidDB. However, occasionally there is a need to use
client-side parameters. For example, you may want to create an application that
defines no data source, but takes the data source from the connect string in the
client-side configuration file.

Note: In solidDB documentation, references to [Link] file are usually for the
server-side [Link] file.

When the solidDB is started, it attempts to open the configuration file [Link]. If
the file does not exist, solidDB will use the factory values for the parameters. If the
file exists, but a value for a particular parameter is not set in the [Link] file,
solidDB will use a factory value for that parameter. The factory values may
depend on the operating system you are using.

By default, the client looks for the [Link] file in the current working directory,
which is normally the directory from which you started the client. When searching
for the file, the solidDB uses the following precedence (from high to low):
v location specified by the SOLIDDIR environment variable (if this environment
variable is set)
v current working directory

Client-side parameters

This section describes the most important solidDB client-side parameters.


v [Link]
The Connect parameter in the [Com] section defines the default network name
(connect string) for a client to connect to when it communicates with a server.
Since the client should talk to the same network name as the server is listening
to, the value of the Connect parameter on the client should match the value of
the Listen parameter on the server.
The same format of the connect string applies to all listen configuration
parameters as well as to connect strings used in ODBC and Light Client
applications.
v [Link]
If you change the Trace parameter default setting from No to Yes, solidDB starts
logging trace information about network messages for the established network
connection to the default trace file or to the file specified in the TraceFile
parameter.
v [Link]
If the Trace parameter is set to Yes, then trace information about network
messages is written to a file specified by the TraceFile parameter. If no file name
is specified, the server uses the default value [Link], which is written to
the current working directory of the server or client, depending on which end
the tracing is started at.

1 Introduction to solidDB APIs 5


ODBC non-standard behavior
This section describes the non-standard behavior and limitations of solidDB ODBC
driver.

Error information

Regardless of the version set by the client, the driver returns error information
based on the ODBC 3.0 specification.

Error in SQLPutData using SQL_NULL_DATA as parameter


length

If you try to insert or update one or more data items where one of the items has
SQL_NULL_DATA as the length specifier, no data will be inserted. The column
value will become NULL.

SQLAllocHandle can return incomplete error information

If you call SQLAllocHandle with an invalid handle type, for example,


SQLAllocHandle(-5, hdbc, &hstmt);

the function will return SQL_ERROR but not Error State "HY092" or message
"Invalid Attribute/Option Identifier".

MSAccess - linking the table with certain column types

After linking the table with data types WCHAR, WVARCHAR, and LONG
WVARCHAR, when a user inserts a particular record and then
inserts/updates/deletes another record, the driver shows '#deleted' for the
previous newly added/updated record.

ADO - OpenSchema methods

The following OpenSchema methods are not supported through ADO:


v adSchemaCatalogs
v adSchemaColumnPrivileges
v adSchemaConstraintColumnUsage
v adSchemaConstraintTableUsage
v adSchemaTableConstraint
v adSchemaForeignKeys
v adSchemaTablePrivileges
v adSchemaViews
v adSchemaViewTableUsage

The above mentioned OpenSchema methods are not supported by ADO with any
ODBC Driver. This is a limitation of the Microsoft OLE DB Provider for ODBC.
This is not specific to the solidDB ODBC Driver.

solidDB JDBC Driver


The JDBC 2.0 Driver provides support for JDBC 2.0.

For solidDB JDBC Driver, Java Development Kit (JDK) 1.4.2 or newer is supported.

6 IBM solidDB: Programmer Guide


solidDB JDBC Driver allows you to develop your application with a Java tool that
accesses the database using JDBC. The JDBC API, the core API for JDK 1.2, defines
Java classes to represent database connections, SQL statements, result sets, database
metadata, and so on. It allows you to issue SQL statements and process the results.
JDBC is the primary API for database access in Java.

In order to use JDBC, you have to install the solidDB JDBC Driver. Usage of JDBC
drivers varies depending on your Java development environment.

Instructions and samples for using the solidDB JDBC Driver are located in the
/jdbc subdirectory in the solidDB installation package and in 3, “Using solidDB
JDBC Driver,” on page 51.

solidDB Application Programming Interface (SA API)


solidDB SA is a C-language client library to connect solidDB database products.
This library is used internally in solidDB products and provides access to data in
solidDB database tables. The library contains 90 functions providing low-level
mechanisms for connecting the database and running cursor-based operations.

solidDB Server Control API (SSC API)


The solidDB Server Control API (SSC API) is proprietary API that contains a set of
functions that provide a simple and efficient means to control the tasking system
of a solidDB.

The SSA API is provided with the shared memory access (SMA) and linked library
access (LLA) libraries. For more details, see solidDB Server Control API (SSC API) in
the IBM solidDB Shared Memory Access and Linked Library Access User Guide.

Building client applications


This section provides an overview of how to create a client application that will
work with solidDB. The information in this section applies primarily to C-language
programs that use the ODBC driver.

What is a client?
A client application, or client for short, is a program that submits requests (SQL
queries) to the server and gets results back from the server.

A client program is separate from the server program. In many cases, the client is
also running on a separate computer. Using shared memory access or linked
library access, you can link the client's code directly to the server's code so that
both run as a single process. For more information, see IBM solidDB Shared Memory
Access and Linked Library Access User Guide.

Since the client is a separate program, it cannot directly call functions in the server.
Instead, it must use a communications protocol (such as TCP/IP or named pipes)
to communicate with the server. Different platforms support different protocols. On
some platforms, you may need to link a specific library file (which supports a
specific protocol) to your application so that your application can communicate
with the server.

How is the query passed to the server?


Queries are written using the SQL programming language.

1 Introduction to solidDB APIs 7


One way that the server and client can exchange data is simply to pass literal
strings back and forth. The client could send the server the string:
SELECT name FROM employees WHERE id = 12;

and the server could send back the string:


"Smith, Jane".

In practice, however, communication is usually done via a "driver", such as an


ODBC driver or a JDBC driver. "ODBC" stands for "Open DataBase Connectivity"
and is an API (Application Programming Interface) designed by Microsoft to make
database access more consistent across vendors. If your client program follows the
ODBC conventions, then your client program will be able to talk with any
database server that follows those same conventions. Most major database vendors
support ODBC to at least some extent. The ODBC standard is generally used by
programs written in the C programming language.

"JDBC" stands for "Java DataBase Connectivity". It is based heavily on the ODBC
standard and is essentially "ODBC for Java programs".

There are two major ways to pass specific data values (for example, "Smith, Jane"
to the server. The first way is to simply embed the values as literals in the query.
This can be seen in SQL statements like:
INSERT INTO employees (id, name) VALUES (12, ’Smith, Jane’);

This works well if you have a single statement that you want to execute. There are
times, however, that you may want to execute the same basic statement with
different values. For example, if you want to insert data for 500 employees, you
may not want to compose 500 separate statements such as
INSERT INTO employees (id, name) VALUES (12, ’Smith, Jane’);
INSERT INTO employees (id, name) VALUES (13, ’Jones, Sally’);
...

Instead, you might prefer to compose a single "generic" statement and then pass
specific values for that statement. For example, you might want to compose the
following statement:
INSERT INTO employees (id, name) VALUES (?, ?);

and have the question marks replaced with specific data values. This way you can
easily execute all 500 INSERT statements inside a loop without composing a
unique INSERT statement for each employee. By using parameters, you can specify
different values each time a statement executes. A parameter allows you to specify
a variable that will be used by the client program and the ODBC driver to store
values that the client and server exchange. In essence, you pass a parameter for
each place in the statement where you have a question mark.

Another situation where you might want to use parameters to exchange data
values is when working with data that is difficult to represent as string literals. For
example, if you want to insert a digitized copy of the song "American Pie" into
your database, and you do not want to compose an SQL statement with a literal
that contains a series of hexadecimal numbers to represent that digitized data, then
you can store the digitized data in an array and notify the ODBC driver of the
location of that array.

8 IBM solidDB: Programmer Guide


To use parameters with SQL statements, you go through a multistep process. The
following shows the process of inserting data. The process is somewhat similar
when you want to retrieve data.
1. Prepare the SQL statement. During the prepare phase, the server analyzes the
statement and (among other things) looks to see how many parameters there
will be. The number and meaning of the parameters is shown by the question
marks that are included in the SQL statement.
2. Tell the ODBC driver which variables will be used as parameters. Telling the
ODBC driver which variable is associated with which column or value is called
"binding" the parameters.
3. Put values into the parameters (that is, set the values of the variables).
4. Execute the prepared statement.

During the execution phase, the ODBC driver will read the values you have stored
in the parameters and will pass those values to the server to use with the
statement that it has already prepared.

How are the results passed back to the client?


The result of a query is a set of 0 or more rows. If you are using an ODBC driver
or JDBC driver, you retrieve each row by using the appropriate ODBC or JDBC
functions.

As a general rule, you go through the following steps


1. Prepare the SQL statement. During the prepare phase, the server analyzes the
statement and (among other things) looks to see how many parameters there
will be. The number and meaning of the parameters is shown by the question
marks that are included in the SQL statement.
2. Tell the ODBC driver which variables will be used as parameters. Telling the
ODBC driver which variable is associated with which column or value is called
"binding" the parameters.
3. Execute the prepared statement. This tells the server to execute the query and
collect the result set. However, the result set is not passed to the client
immediately.
4. Fetch the next row of the result set. When you do a fetch, you tell the server
and the ODBC driver to retrieve one row of results from the result set and then
store the values of that row into the parameters that you previously defined for
the ODBC driver to share with your application.

Normally you will perform a loop, fetching one row at a time and reading the data
from the parameters after each fetch.

Using the ODBC driver library


The ODBC driver libraries must be linked with your client application program.

Static vs. Dynamic Libraries

You will then be able to call the functions that are defined in these libraries. For
details about library names, see the SDK Notes in the solidDB package.

Some library files are static — i.e. they are linked to your client application's
executable program at the time that you do a compile-and-link operation. Other
library files are dynamic - these are stored separately from your executable and are
loaded into memory at the time your program executes.

1 Introduction to solidDB APIs 9


The advantage of a static library is that your application is largely self-contained; if
you distribute the application to your customers, those customers do not have to
install a separate shared library in addition to installing your application.

The advantage of a dynamic library is that on many systems it requires less disk
space (and, on some platforms, less memory space) if more than one client uses
that library. For example, if you have two client applications that each link to a 5
MB static library, you will need not only 5 MB of disk space to store the static
library, but also 10 MB of additional disk space to store both copies of the library
that are linked into the application. However, if you link two client applications to
a dynamic library, no additional copies of that library will be required; each
application does not keep its own copy.

For many libraries, solidDB provides both a static and a dynamic version on some
or all platforms.

In addition, on Windows environments, solidDB provides an import library in


some cases. Each import library is associated with a corresponding dynamic link
library. Your application will link to the import library. When the application is
actually loaded and executed, the operating system will load the corresponding
dynamic link library.

Statement cache
Processing of queries is additionally optimized by a built-in statement cache.

Statement cache is an internal memory storing a few previously prepared SQL


statements. The number of cached statements for a session can be set by using a
client-side [Link] configuration parameter [Link]. The default
value is 6.

The statement cache operates in such a way that the prepare phase is omitted if
the prepared statement is in the cache. If a connection is closed, the statement
cache is purged.

In JDBC, the statement cache size can be dynamically set by using a non-standard
"StatementCache" connection property. For more information, see “Non-standard
connection properties” on page 64.

10 IBM solidDB: Programmer Guide


2 Using solidDB ODBC API
This section contains solidDB-specific information and usage samples for
developing applications that use the ODBC API.

In general, solidDB conforms to the Microsoft ODBC 3.51 standard. solidDB ODBC
APIs are defined based on the function prototypes provided by Microsoft. This
guide details those areas where solidDB-specific usage applies and where support
for options, data types, and functions differ.

Note: This IBM solidDB Programmer Guide does not contain a full ODBC API
reference. For details on developing applications with ODBC API, refer to the
Microsoft ODBC Programmer's Reference.

solidDB provides two versions of the ODBC driver, one for Unicode and one for
ASCII. The Unicode version is a superset of the ASCII version; you may use it
with either Unicode or ASCII character sets.

Installing solidDB ODBC Driver


The solidDB installation program installs two ODBC Drivers: one for Unicode and
one for ASCII. The Unicode version is a superset of the ASCII version; you can use
it with either Unicode or ASCII character sets. On Windows environments, you can
also use the solidDB installation program to install only the ODBC driver.

Windows

In Windows environments, the solidDB installation program installs the ODBC


drivers and the following system Data Source Names (DSN) automatically. You can
also add you own user DSNs.
v Windows 32-bit operating systems:
– IBM solidDB 6.5 32-bit – ANSI
– IBM solidDB 6.5 32-bit – Unicode
v Windows 64-bit operating systems:
– IBM solidDB 6.5 64-bit – ANSI
– IBM solidDB 6.5 64-bit – Unicode

Linux and UNIX

In Linux and UNIX environments, the ODBC driver library files are installed to the
following directories:
v <solidDB installation directory>/bin/: dynamic library files
– sac<platform><version>.sa or sac<platform><version>.so – ANSI
– soc<platform><version>.sa or soc<platform><version>.so – Unicode
v <solidDB installation directory>/lib/: static library files
– [Link] or [Link] – ANSI
– [Link] or [Link] – Unicode

The file extension .sa or .so depends on the operating system.

11
Installing ODBC drivers without solidDB installation (Windows)

To install the ODBC drivers without installing solidDB in Windows environments:


1. Start the solidDB installation program.
2. Select Custom installation.
3. Select ODBC (unselect Server and Samples).
4. Follow the displayed instructions to complete the installation.

Installing ODBC drivers without solidDB installation (Linux and


UNIX)

To install the ODBC drivers without installing solidDB in Linux and UNIX
environments:
1. Install solidDB using the installation program.
2. Copy the ODBC driver library file to your client node.

solidDB ODBC Driver 3.51 Features Support


This section provides details about the ODBC Driver 3.51 features support for
users who have migrated from a previous version (1.0, 2.0, and 3.0) of the solidDB
ODBC Driver to solidDB ODBC Driver 3.51.

The following features are supported in this driver:


v Complete support of descriptors
v All catalog API support
v Unicode support
v Multithread support
v ADO/DAO/RDO/OLE DB support
v Data access through MS Access and MS Query
v Block cursor support

Overview of usage on Windows operating systems


On Windows operating systems, the solidDB ODBC Libraries are provided as .DLL
files.

The files are named [Link] and [Link] (where "VV" indicates the
version number) for the Unicode and ASCII versions, respectively. For example, the
Unicode ODBC driver in version 4.1 is named [Link]. To call the functions
in one of these .DLL files, you must link to a solidDB import library file. For the
solidDB on Windows, this import library file is named [Link]
(Unicode) or [Link] (ASCII). This import library file contains the entry
points to the corresponding solidDB ODBC DLL (for example, [Link]).

Note: The library files have been produced with C++. Other development toolkit
manufacturers' linkers may expect different library file formats. In such cases, the
Import Library utility of the development toolkit should be used to build a library
file that is compatible with your linker.

12 IBM solidDB: Programmer Guide


Instructions for usage of solidDB client DLLs (solidDB ODBC
Driver files)

There are two alternatives to building application programs that use the solidDB
ODBC driver:
1. Using Microsoft ODBC Driver Manager.
Microsoft ODBC software needs to be installed on all client workstations and a
Data Source must be defined using solidDB ODBC Driver. If you use the Driver
Manager, then any application that can use the solidDB ODBC driver will also
work with any other ODBC compliant engine.
2. Using solidDB ODBC driver directly.
Connections are opened directly to a server process without using Microsoft
ODBC Driver Manager. This usually makes embedded deployment of solidDB
easier. However, the application can only use the functions provided by the
solidDB library (that is, solidDB ODBC Driver); the application cannot use the
ODBC functions that are implemented by the Microsoft ODBC Driver Manager
or the Microsoft Cursor library.

solidDB provides some sample programs that can be used either with or without
the Microsoft ODBC Driver Manager. These samples are in subdirectories of the
samples directory in your solidDB installation directory. Below are brief
instructions on how to build and run the provided samples in both of the
alternative ways:
v Building the samples to use ODBC Driver Manager.
1. Create a new application project.
2. Add the C-source file (for example, sqled.c or embed.c) to the project.
3. Make the header files visible to the compiler.
4. Define SS_WINDOWS for the compiler.
5. Compile and link.
6. Make sure that you have installed the solidDB ODBC driver. Also, make sure
that the connection string you intend to use is defined as the ODBC data
source name.
7. Run to connect to a listening solidDB server.
v Building the samples to use solidDB ODBC library directly.
The necessary changes to the ODBC Driver Manager configuration are listed
below.
1. Add solidDB ODBC driver library file ([Link]) to the project.
2. Remove ODBC Driver manager libraries ODBC*.LIB from the default library
list.
3. Compile and link.
4. Now it is possible to connect to data sources bypassing ODBC Driver
Manager. Make sure that the SQL API DLL socw32<VV>.dll (where "VV"
indicates the version number) and the solidDB communication DLLs are
available. Data Sources may be defined in [Link] or in the ODBC
Administration Window.
5. Run the client to connect to a listening solidDB server.

Calling functions
This section provides information about how programs call functions in the ODBC
driver.

2 Using solidDB ODBC API 13


Header files and function prototypes

If your program calls functions in the ODBC driver, your program must include
the ODBC header files. These files define the ODBC functions, and the data types
and constants that are used with ODBC functions. The header files are not
solidDB-specific; they are standard header files provided by Microsoft. The solidDB
ODBC driver (like any ODBC driver) implements the functions that are specified
in these header files.

ASCII and Unicode

ODBC drivers come in two "flavors": ASCII and Unicode. The ASCII driver
supports only ASCII character sets. The Unicode driver supports both the Unicode
and the ASCII character sets.

For details on driver, API, and SQL conformance levels, refer to section
Introduction to ODBC in the Microsoft ODBC Programmer's Reference.

Using the ODBC Driver Manager

An application may link directly to the solidDB ODBC driver, or the application
may link to an ODBC Driver Manager.

On Windows systems, the Driver Manager is required if applications that connect


to solidDB use OLE DB or ADO APIs, or you use database tools that require the
Driver Manager, such as Microsoft Access, FoxPro, or Crystal Reports. In most
other cases, you may link directly to the ODBC driver instead of linking to the
Driver Manager.

On Windows systems, Microsoft supplies the Driver Manager, and you link to the
Driver Manager import library ([Link]) to gain access to the Driver Manager.

On other platforms, you can link to another vendor's Driver Manager. For
example, on Linux systems, you can use unixODBC.

For basic application steps that occur whenever an application calls an ODBC
function and details on calling ODBC functions, refer to section Introduction to
ODBC in the Microsoft ODBC Programmer's Reference.

Data types

Appendix E, “Data types,” on page 225 provides information about SQL data types
that are supported by solidDB. The header files from Microsoft provide
information about C-language data types used by your client program. To transfer
data between the application program and the database server, you must use
appropriate types. For example, on most 32-bit platforms, the C-language "int" data
type corresponds to the SQL data type "INT". The C-language "float" data type
corresponds to the SQL "REAL" data type.

Scalar functions

Scalar functions return a value for each row. For example, the "absolute value"
scalar function takes a numeric column as an argument and returns the absolute
value of each value in the column. Scalar functions are invoked with the following
ODBC escape sequence:
{fn scalar-function}

14 IBM solidDB: Programmer Guide


Note: The starting and ending characters are the curly bracket characters, not
parentheses.

For a list of scalar functions and a more complete example of their usage, refer to
Appendix F, “Scalar functions,” on page 271.

solidDB native scalar functions

solidDB provides the following native scalar functions, which cannot be invoked
using the ODBC escape sequence.
v CURRENT_CATALOG() - returns a WVARCHAR string that contains the current
active catalog name. This name is the same as ODBC scalar function {fn
DATABASE()}.
v LOGIN_CATALOG() - returns a WVARCHAR string that contains the login
catalog for the connected user (currently the login catalog is the same as the
system catalog).
v CURRENT_SCHEMA() - returns a WVARCHAR string that contains the current
active schema name.

Function return codes

When an application calls a function, the driver executes the function and returns a
predefined code. These return codes indicate success, warning, or failure status.
The return codes are:
v SQL_SUCCESS
v SQL_SUCCESS_WITH_INFO
v SQL_NO_DATA_FOUND
v SQL_ERROR
v SQL_INVALID_HANDLE
v SQL_STILL_EXECUTING
v SQL_NEED_DATA

If the function returns SQL_SUCCESS_WITH_INFO or SQL_ERROR, the


application can call SQLError to retrieve additional information about the error.

Connecting to a data source


A data source can be a database server, a flat file, or another source of data.

To access the data source, you need to define the solidDB server's network name
which the application will use in a SQLConnect() call (ServerName). The network
name may be given in one of the three following ways:
v Include the network name in the function call directly
v Include the network name in the function call using a logical data source name
mapping
v Give the network name in the function call as an empty string

There are three connectivity types for defining the network name:
v Basic connectivity
v Transparent connectivity
v SMA connectivity

2 Using solidDB ODBC API 15


The following sections describe how to connect to a data source using basic
connectivity.

For information about Transparent Connectivity (TC Info), see the sections Using the
Transparent Connectivity and Syntax of the Transparent Connectivity Info in the IBM
solidDB High Availability User Guide.

For information about SMA connectivity, see section Establishing local connections for
SMA in the IBM solidDB Shared Memory Access and Linked Library Access User Guide.

Network name and connect string syntax


The solidDB network name syntax depends on the connectivity type: basic
connectivity, transparent connectivity (TC Info), or SMA connection.
v Basic connectivity
Basic connectivity is the most commonly used connectivity type where the
connection between the application and the solidDB server uses network
protocols such as TCP/IP.
v Transparent connectivity (TC Info)
Transparent connectivity (TC Info) is used in High Availability (HA)
configurations for specifying the (single) connection between the client and
solidDB HotStandby servers.
v SMA connection
The SMA connection is used in shared memory access (SMA) setups for defining
a local connection between the client and the SMA server.

Network name syntax

The syntax of the network name is the following:


<network name>::=<basic connectivity>|<transparent connectivity>|<SMA connection>

where
v <basic connectivity>::=[<encryption attribute>] <connect string>
<encryption attribute>::=USE_ENCRYPTION=YES|NO
<connect string>::=protocol_name [options] [server_name] [port_number]
For example
USE_ENCRYPTION=YES tcp localhost 1315
v <transparent connectivity>::={[<failure transparency level attribute>]
[<preferred access attribute>] [<encryption attribute>] <connect target
list>} | <cluster info>
For details, see Syntax of the Transparent Connectivity Info in the IBM solidDB High
Availability User Guide
For example
TF=SESSION USE_ENCRYPTION=YES SERVERS=tcp 2315 tcp 1315
v <SMA connection>::= sma <connect string>
<connect string>::=protocol_name [options] [server_name] [port_number]
For example
sma tcp 1315
For more information, see section Establishing local connections for SMA in the
IBM solidDB Shared Memory Access and Linked Library Access User Guide.

16 IBM solidDB: Programmer Guide


solidDB connect string

The solidDB connect string consists of a communication protocol, a possible set of


special options, an optional host computer name and a server name.

By this combination, the client specifies the server it will establish a connection to.
The communication protocol and the server name must match the ones that the
server is using in its network listening name. In addition, most protocols need a
specified host computer name if the client and server are running on different
machines. All components of the client's network name are case insensitive.

The format of a connect string is the following:


protocol_name [options] [host_computer_name] server_name

where
v options can be any combination of the following:
Table 4. Connect string options

Option Description Protocol


-4 Specifies that client connects using IPv4 protocol only. TCP/IP
-6 Specifies that client connects using IPv6 protocol only. TCP/IP

In Windows environments, this option is mandatory if IPv6 protocol is used.


All
-z Enables data compression for this connection
-c milliseconds Specifies the login timeout (the default is operating-system-specific). A login request TCP/IP
fails after the specified time has elapsed.
Specifies the connection (or read) timeout. A network request fails when no response is TCP/IP
-r milliseconds received during the time specified. The value 0 (default) sets the timeout to infinite
(operating system default timeout applies).
-ofilename Turns on the Network trace facility and defines the name of the trace output file All

See Network trace facility in the IBM solidDB Administrator Guide for details.
-plevel Pings the server at the given level (0-5). All

Clients can always use the solidDB Ping facility at level 1 (0 is no operation/default).
Levels 2, 3, 4 or 5 may only be used if the server is set to use the Ping facility at least at
the same level.

See Ping facility in the IBM solidDB Administrator Guide for details.
-t Turns on the Network trace facility All

See Network trace facility in the IBM solidDB Administrator Guide for details.

v host_computer_name is needed with TCP/IP and Named Pipes protocols, if the


client and server are running on different machines.
v server_name depends on the communication protocol:
– In TCP/IP protocol, server_name is a service port number, such as '2315'.
– In other protocols, server_name is a name, such as 'soliddb' or 'chicago_office'.
For details on the syntax in different communication protocols, see
Communication protocols in the IBM solidDB Administrator Guide.

Note:
v The protocol_name and the server_name must match the ones that the server is
using in its network listening name.

2 Using solidDB ODBC API 17


v If given at the connection time, the connect string must be enclosed in double
quotation marks.
v All components of the connect string are case insensitive.

The same format of the connect string applies to the [Link] parameter as
well as to the connect string used by solidDB tools or ODBC applications.

Examples
[Com]
Connect=tcp -z -c1000 1315
[Com]
Connect=nmpipe host22 SOLID
solsql "tcp localhost 1315"
solsql "tcp [Link] 1315"
rc = SQLConnect(hdbc, "upipe SOLID", (SWORD)SQL_NTS, "dba", 3, "dba", 3);
rc = SQLDriverConnect(hdbc,
(SQLHWND)NULL,
(SQLCHAR*)"DSN=tcp localhost 1964;UID=dba;PWD=dba",
38,
out_string,
255,
&out_length,
SQL_DRIVER_NOPROMPT);

Using logical data source names


If the data source name is not a valid solidDB connect string, the driver assumes it
is a logical data source name.

The logical data source name can be mapped to a data source as a 'logical name'
and 'connect string' (network name) pair in the following ways:
v Using the [Data Sources] section in the client-side [Link] file
The syntax of the parameters is the following:
[Data Sources]
logical_name = connect_string; Description
where Description can be used for comments on the purpose of the logical
name
Example:
To map a logical name My_application to a database that you want to connect
using TCP/IP, include the following lines in the [Link] file:
[Data Sources]
My_application = tcpip irix 1313; Sample data source
When an application calls the data source 'My_application', the solidDB client
maps this to a call to 'tcpip irix 1313'.
v In Windows environments, using the registry settings (ODBC Driver
Manager)
You can use the Control Panel > Administrative Tools > Data Sources (ODBC)
dialog or the Registry Editor (regedit) to add mappings.
For details, see Configuring the solidDB ODBC Data Source for Windows in the IBM
solidDB Programmer Guide.

Tip: The solidDB data management tools use the solidDB ODBC API. If you
have defined an ODBC Data Source, you can use the logical name source name
also when connecting to solidDB server with the solidDB tools.

18 IBM solidDB: Programmer Guide


For example, if you have created a data source named 'solid_1' with ServerName
'tcp 2525', you can connect to solidDB with solidDB SQL Editor (solsql) with
the following command:
solsql solid_1

When connecting to the solidDB server, if the network name is not a valid connect
string, the solidDB tools and clients assume it is a logical data source name. To
find a mapping between the logical data source name and a valid connect string,
the solidDB tools and clients check the client-side [Link] file.

In Windows environments, if the [Link] file is not found or the logical data
source name is not defined in the [Data Sources] section, the data source settings
made with the Windows registry settings are checked in the following order.
1. Look for the Data Source Name from the following registry path:
HKEY_CURRENT_USER\software\odbc\[Link]\DSN
2. Look for the Data Source Name from the following registry path
HKEY_LOCAL_MACHINE\software\odbc\[Link]\DSN

The check for the logical data source mappings might impact performance:
v If the file system is particularly slow, for example, because the working directory
is mapped to a network drive, checking the existence of the [Link] file can
have a measurable performance impact.
v In Windows environments, all logical data source mappings in the ODBC
registry are checked. The time consumed for this operation is proportional to the
amount of defined data sources.
– With only few (1 to 5) data sources, the connection time will be
approximately 5 ms.
– With 1000 data sources, the connection time will be approximately 200 ms.
However, if the [Link] file contains the logical data source name mapping,
the tools and clients do not try to access the ODBC registry for the mapping.

Empty data source name


When an application uses the ODBC API directly and calls SQLConnect() without
specifying a solidDB server network name (by giving an empty string), it is read
from the parameter Connect in the [Com] section of the client application's
[Link] file.

The [Link] file must reside in the current working directory of the application
or in a path specified by the SOLIDDIR environment variable.

The following connect line in the [Link] of the application workstation will
connect an application (client) using the TCP/IP protocol to a solidDB server
running on a host computer named 'spiff' and listening with the name (port
number in this case) '1313'.
[Com]
Connect = tcpip spiff 1313

If the Connect parameter is not found in the [Link] configuration file, then the
client uses the environment-dependent default instead. The defaults for the Listen
and Connect parameters are selected so that the application (client) will always
connect to a local solidDB server listening with a default network name. So local
communication (inside one machine) does not necessarily need a configuration file
for establishing a connection.

2 Using solidDB ODBC API 19


Configuring the solidDB ODBC Data Source for Windows
To configure an ODBC data source for Windows platforms, you need to perform
the steps described in this section.

Before you begin

To be able to configure solidDB ODBC data sources, the solidDB ODBC Driver
must be installed.

Procedure
1. Invoke Data Sources (ODBC) from Control Panel > Administrative Tools
2. Open the User DSN tab.
3. Click the Add... button.
4. Select the solidDB ODBC Driver (ANSI or UNICODE according to your
database requirements).
5. Enter the Data Source configuration in the solidDB ODBC Driver Setup box as
shown in the following example.

Note: The NetworkName entry should be compliant with the database server
listen addresses defined in [Link]. The network name follows the
connection string format presented in “Format of the solidDB connect string”
on page 3.

Figure 1. ODBC driver setup

Using solidDB ODBC Driver with unixODBC


unixODBC is an ODBC driver manager for UNIX type environments. Instead of
linking an application directly with the solidDB ODBC driver, a unixODBC
DriverManager can be used.

For detailed information on unixODBC and the unixODBC DriverManager, see


[Link]

20 IBM solidDB: Programmer Guide


Configuration files

The unixODBC DriverManager loads the correct data source driver according to
the specifications in the following two configuration files:
v [Link] or .[Link]: specifies the logical name of the data source and the
actual ODBC driver
The [Link] file defines the system-level settings that are available to all users.
The .[Link] file defines user-level settings.
v [Link]: connects the logical driver name with its physical location in the
file system.
The [Link] is a system-level file.

In addition to the files above, the solidDB ODBC Driver needs a client-side
[Link] configuration file where the logical data source name is connected with
the a valid solidDB connect string.

Syntax of the [Link] configuration files


The [Link] or .[Link] file must include at least the following two items for
each data source:
v Logical name of the data source inside brackets, for example [my_solid]
v Logical name of the actual ODBC driver to be used by using the syntax
Driver=<driver name>, for example Driver = solid_odbc.
An additional description can be added by using the syntax Description=My
first Solid
All additional information is ignored.

Syntax of the [Link] configuration file

The logical name and the physical location of the ODBC driver must be specified
in the [Link] file as follows:
v [<the logical name of the driver>], for example, [solid_odbc]
v Driver = <absolute path to the driver>, for example, Driver =
/home/jsmith/[Link]

Syntax of the client-side [Link] configuration file

In the client-side [Link] file, the logical data source name must be connected to
a valid solidDB connect string (network name) as follows:
v [Data Sources]
v <the logical data source name> = <connect_string> , for example,
my_solid=tcp my_machine 1964

Location of the configuration files

The system-level configuration files, [Link] and [Link] are located in a


system level configuration directory, such as /etc/. For example:
/usr/local/etc/[Link]
/usr/local/etc/[Link]

User-level data sources are specified in ~/.[Link].

2 Using solidDB ODBC API 21


The client-side [Link] file can be located either in the directory set by the
SOLIDDIR environment variable or in the current working directory.

Linking the driver

To link to the unixODBC driver instead of the solidDB ODBC Driver:


1. Copy the unixODBC driver to the location of your choice.
2. Replace the solidDB ODBC Driver library file with the unixODBC library file.
For example:
Direct linking: LDFLAGS = $(SOLID_LIB)/linux/[Link]
unixODBC driver manager: LDFLAGS = $(SOLID_LIB)/linux/[Link]

Examples of configuration files


$HOME/.[Link]
[my_solid]
Description = Testing solidDB
Driver = solid_odbc
$HOME/.[Link]
[solid_odbc]
Description = The solidDB ODBC driver
Driver = /home/jsmith/solid/bin/[Link]
$SOLIDDIR/[Link]
[Data Sources]
my_solid = tcp 1964

Retrieving user login information


This section describes how the Driver Manager retrieves login information.

If the application calls SQLDriverConnect() and requests that the user be prompted
for information, the Driver Manager displays a dialog box similar to the following
example:

22 IBM solidDB: Programmer Guide


Figure 2. ODBC data source administrator

On request from the application, the driver retrieves login information by


displaying a dialog box.

ODBC handle validation


You can control ODBC handle validation with the client-side
[Link] parameter or dynamically with the non-standard
ODBC attribute SQL_ATTR_HANDLE_VALIDATION. For performance reasons, ODBC
handle validation in solidDB is switched off by default.

For example, in Windows environments with ODBC driver manager, the driver
manager performs the handle validation and the solidDB ODBC driver does not
need to repeat the same validation procedures. Also, a carefully written ODBC
application does not normally cause invalid handles to be used; in such a case, the
handle validation in the ODBC driver is not needed. In both cases, the applications
can benefit from performance improvements when skipping the handle validation
in the driver.

To switch ODBC handle validation on or off:


v Set the client-side [Link] to yes or no. Default is no.
[Client]
ODBCHandleValidation=yes
or
v Set the non-standard environment attribute SQL_ATTR_HANDLE_VALIDATION to 1
(on) or 0 (off). Default is 0.
– To switch handle validation on:
SQLSetEnvAttr(henv, SQL_ATTR_HANDLE_VALIDATION, (SQLPOINTER)1, 0);

2 Using solidDB ODBC API 23


– To switch handle validation off:
SQLSetEnvAttr(henv, SQL_ATTR_HANDLE_VALIDATION, (SQLPOINTER)0, 0);

Important: The SQL_ATTR_HANDLE_VALIDATION attribute must be set after creating


the environment handle but before any other handle is created. The
SQL_ATTR_HANDLE_VALIDATION attribute is global; when set, it affects all the
solidDB ODBC handles initiated by the application. This ensures consistency by
preventing the application from allocating both validated and non-validated
handles.

When the handle validation is switched on, any ODBC function may fail with the
standard return value SQL_INVALID_HANDLE.

If handle validation is turned off and invalid handle is used by the application, the
ODBC driver behavior is unpredictable and most likely causes the application to
crash.
Related concepts:
“solidDB Extensions for ODBC API” on page 29
The following functions and connection attributes are solidDB-specific extensions
to ODBC API.
Appendix H, “Client-side configuration parameters,” on page 295
The client-side configuration parameters are stored in the client-side [Link]
configuration file and are read when the client starts.

Executing transactions
This section provides information about how transactions are committed.

In auto-commit mode, each SQL statement is a complete transaction, which is


automatically committed when the statement finishes executing. Refer to the
important notes in the Committing Read-Only Transactions section on committing
read-only SELECTs.

In manual-commit mode, a transaction consists of one or more statements. In


manual-commit mode, when an application submits an SQL statement and no
transaction is open, the driver implicitly begins a transaction. The transaction
remains open until the application commits or rolls back the transaction with
SQLEndTran.

Committing Read-Only Transactions

Important:
v When the isolation level is other than READ COMMITTED, even read-only
statements (for example, SELECT) must be committed. Furthermore, the user
must commit SELECT statements even if the server is in autocommit mode.
Failure to commit statements can reduce performance or cause the server to run
out of memory. This is explained in more detail below.
v If the isolation level is READ COMMITTED, read-only statements need not be
committed. In that case, the explanation below does not apply.

Even a read-only statement must be committed. The reason for this is that solidDB
saves the 'read-level' of each transaction and until that transaction commits, all
subsequent transactions from other connections are also maintained in memory.
(This behavior is part of the row versioning performed by the Bonsai Tree

24 IBM solidDB: Programmer Guide


technology. See solidDB Administration Guide for more details about the Bonsai
Tree.) If a transaction is not committed, the server will need more and more
memory as other transactions accumulate; this will reduce performance, and
eventually the server may run out of available memory. For more details, read the
Performance Tuning chapter in solidDB Administration Guide.

SELECT and autocommit

Using autocommit mode does not ensure that SELECT statements are committed.
The server cannot automatically commit SELECTs because SELECTs do not execute
as a single statement. Each SELECT involves opening a cursor, fetching rows, and
then closing the cursor.

There are two possible ways that the server could automatically commit when
fetching multiple rows: the server could commit after the final fetch, or the server
could commit after each individual fetch. Unfortunately, neither of these is
practical, and therefore the server cannot commit the SELECT statement even in
autocommit mode.

The server cannot automatically commit after the final fetch because the server
does not know which fetch is the final fetch — the server does not know how
many rows the user will fetch. (Until the user closes the cursor, the server does not
know that the user is done fetching.)

It is not practical to commit after each individual fetch because each transaction
should see the data as it was at the time that the transaction started, and therefore
if each fetch is in a different transaction then the data can be from a different
"snapshot" of the database. Putting each fetch in a different transaction would also
make REPEATABLE READ and SERIALIZABLE transaction isolation levels
confusing or meaningless for the cursor, even though the cursor is for a single
SELECT statement.

To commit the SELECT statement, the user may:


v Execute an explicit COMMIT WORK statement.
v Execute a statement to which autocommit does apply (i.e. a statement other than
SELECT).
v If the cursor is the only open cursor, then the user may commit by explicitly
closing the cursor (the server automatically commits when a cursor is closed and
there are no other open cursors (and the server is in autocommit mode). This is
part of why we recommend that you explicitly close every cursor as soon as you
are done with it.

Note: To ensure that the data in the cursor is consistent and recent, the server
actually does an automatic commit immediately prior to opening the cursor (if
autocommit is on). The server then immediately starts a new transaction to contain
the subsequent FETCH statement(s). This new transaction, like any other
transaction, must be committed (or rolled back).

Summary

All statements must be committed, even if they are read-only statements, if an


isolation level other than READ COMMITTED is used.

In most cases when you are doing SELECT statements in autocommit mode, you
should explicitly close each cursor as soon as you are done with it and then

2 Using solidDB ODBC API 25


explicitly COMMIT, even though you are in autocommit mode.

Retrieving information about the data source's catalog


This section describes functions (known as catalog functions) that return information
about a data source's catalog.
v SQLTables returns the names of tables stored in a data source.
v SQLTablePrivileges returns the privileges associated with one or more tables.
v SQLColumns returns the names of columns in one or more tables.
v SQLColumnPrivileges returns the privileges associated with each column in a
single table.
v SQLPrimaryKeys returns the names of columns that comprise the primary key
of a single table.
v SQLForeignKeys returns the names of columns in a single table that are foreign
keys. It also returns the names of columns in other tables that refer to the
primary key of the specified table.
v SQLSpecialColumns returns information about the optimal set of columns that
uniquely identify a row in a single table or the columns in that table that are
automatically updated when any value in the row is updated by a transaction.
v SQLStatistics returns statistics about a single table and the indexes associated
with that table.
v SQLProcedures returns the names of procedures stored in a data source.
v SQLProcedureColumns returns a list of the input and output parameters, as well
as the names of columns in the resultset, for one or more procedures.

Each function returns the information as a resultset. An application retrieves these


results by calling SQLBindCol() and SQLFetch().

Executing Functions Asynchronously

Note: ODBC drivers in all solidDB products do not support asynchronous


execution.

Using ODBC extensions to SQL


ODBC defines extensions to SQL, which are common to most database
management systems.

For details on SQL extensions, refer to Escape Sequences in ODBC in the Microsoft
ODBC Programmer's Reference.

Included in the ODBC extensions to SQL are:


v Procedures
v Hints

Details on solidDB usage for these extensions are described in the following
sections.

Procedures
Stored procedures are procedural program code containing one or more SQL
statements and program logic.

26 IBM solidDB: Programmer Guide


Stored procedures are stored in the database and executed with one call from the
application or another stored procedure.

An application can call a procedure in place of an SQL statement. The escape


clause ODBC uses for calling a procedure is:
{call procedure-name [([parameter][,[parameter]]...)]}

where procedure-name specifies the name of a procedure stored on the data source
and parameter specifies a procedure parameter.

Note: solidDB does not support the optional "?=" included in the ODBC standard:
{[?=] call procedure-name [([parameter][,[parameter]]...)]}

A procedure can have zero or more parameters.


v For input and input/output parameters, parameter can be a literal or a parameter
marker. Because some data sources do not accept literal parameter values, be
sure that interoperable applications use parameter markers.
v For output parameters, parameter must be a parameter marker.
If a procedure call includes parameter markers, the application must bind each
marker by calling SQLBindParameter() prior to calling the procedure.

Procedure calls do not require input and input/output parameters; however, the
following rules apply:
v A procedure called with parentheses but with parameters omitted, such as {call
procedure_name()} may cause the procedure to fail.
v A procedure called without parentheses, such as {call procedure_name}, returns no
parameter values.
v Input parameters may be omitted. Omitted input or input/output parameters
cause the driver to instruct the data source to use the default value of the
parameter. As an option, a parameter's default value can be set using the value
of the length/indicator buffer bound to the parameter to
SQL_DEFAULT_PARAM.
v When a parameter is omitted, the comma delimiting it from other parameters
must be present.
v Omitted input/output parameters or literal parameter values cause the driver to
discard the output value.
v Omitted parameter markers for a procedure's return value cause the driver to
discard the return value.
v If an application specifies a return value parameter for a procedure that does not
return a value, the driver sets the value of the length/indicator buffer bound to
the parameter to SQL_NULL_DATA.

To determine if a data source supports procedures, an application calls


SQLGetInfo() with the SQL_PROCEDURES information type.

For more information about procedures, see Stored procedures in the IBM solidDB
SQL Guide.

Hints
Hints are an extension of SQL that provide directives to the SQL optimizer for
determining the query execution plan that is used. Hints are specified through
embedded pseudo comments within query statements. The optimizer detects these

2 Using solidDB ODBC API 27


directives or hints and bases its query execution plan accordingly. Optimizer hints
allow applications to be optimized under various conditions to the data, query
type, and the database. They not only provide solutions to performance problems
occasionally encountered with queries, but shift control of response times from the
system to the user.

Hints are needed because due to various conditions with the data, user query, and
database, the SQL optimizer is not always able to choose the best possible
execution plan. For example, you might want to force a merge join because you
know, unlike the optimizer, that your data is already sorted. Also, sometimes
specific predicates in queries can cause performance problems that the optimizer
cannot eliminate. The optimizer may be using an index that you know is not
optimal. In this case, you may want to force the optimizer to use one that produces
faster results.

Hints are available for:


v Selecting merge or nested loop join
v Using a fixed join order as given in the from list
v Selecting internal or external sort
v Selecting a particular index
v Selecting a table scan over an index scan
v Selecting sorting before or after grouping
You can place hints in SQL statements as static strings, just after a SELECT,
UPDATE, or DELETE keyword. Hints are not allowed after the INSERT keyword.

Hints syntax

Hints are detected through a pseudo comment syntax as specified in SQL-92.


--(* vendor (SOLID), product (Engine), option(hint)
--hint *)--

hint::=
[MERGE JOIN |
TRIPLE MERGE JOIN |
LOOP JOIN |
JOIN ORDER FIXED |
INTERNAL SORT |
EXTERNAL SORT |
INDEX [REVERSE] table_name.index_name |
PRIMARY KEY [REVERSE] table_name |
FULL SCAN table_name |
[NO] SORT BEFORE GROUP BY |
UNION FOR OR |
OR FOR OR |
LOOP FOR OR]

For more information on the hints syntax, see HINT in the IBM solidDB SQL Guide.

Enabling and disabling hints

Hints are enabled and disabled using the [Link] parameter. By default,
hints are enabled ([Link]=yes).

Additional ODBC extension functions


ODBC provides the following functions related to SQL statements.

28 IBM solidDB: Programmer Guide


Refer to the API reference in the Microsoft ODBC Programmer's Reference for more
information about these functions.
Table 5. Additional ODBC Extension Functions

Function Description

SQLDescribeParam Retrieves information about prepared parameters.

SQLNumParams Retrieves the number of parameters in an SQL statement.

SQLSetStmtAttr These functions set or retrieve statement options, such as


asynchronous processing, orientation for binding rowsets,
SQLSetConnectAttr maximum amount of variable length data to return,
maximum number of resultset rows to return, and query
SQLGetStmtAttr timeout value. Note that SQLSetConnectAttr sets options
for all statements in a connection.

solidDB Extensions for ODBC API


The following functions and connection attributes are solidDB-specific extensions
to ODBC API.

Non-standard ODBC functions


Table 6. solidDB-specific ODBC functions to ODBC API

Function Description

SQLFetchPrev This function is the same as the ODBC function SQLFetch,


but for fetching previous record.

SQLSetParamValue This function sets the value of a parameter marker in the


SQL statement specified in SQLPrepare. Parameter
markers are numbered sequentially from left-to-right,
starting with one, and may be set in any order.

SQLGetCol This function is the same as the ODBC function


SQLGetData.

SQLGetAnyData This function is the same as the ODBC function


SQLGetData.

Non-standard ODBC attributes

The following connection attributes are specific to solidDB.

Note: If the attribute is marked as OUT, it is a read-only attribute and cannot be


set through the ODBC interface.
v SQL_ATTR_TF_LEVEL
OUT: integer (TF level: 0=NONE, 1=CONNECTION, 3=SESSION)
The failure transparency level.
v SQL_ATTR_TF_RECONNECT_TIMEOUT
IN/OUT: integer

2 Using solidDB ODBC API 29


The time in milliseconds the driver should wait until it tries to reconnect to the
primary in case of switchover or failover.
v SQL_ATTR_TF_WAIT_TIMEOUT
IN/OUT: integer
The time in milliseconds the driver should wait for the server to switch state.
v SQL_ATTR_TC_PRIMARY
OUT: string, Primary server connection string
There is always a value indicating the current Primary server.
v SQL_ATTR_TC_SECONDARY
OUT: string, Secondary server connection string
The value indicates the assigned workload server if:
1. PA=READ_MOSTLY, and
2. the Secondary is the designated workload server.
Otherwise, the returned string is empty.
v SQL_ATTR_TF_WAITING
OUT: string, Secondary server connection string.
The value indicates the assigned watchdog (waiting) connection. Waiting
connection is used by ODBC driver internally to detect possible looses (crashes,
unavailability) of the primary server faster. The string is empty if the connection
is not a TC connection.
v SQL_ATTR_PA_LEVEL
OUT: integer (Preferred Access level: 0=WRITE_MOSTLY, 1=READ_MOSTLY)
The attribute indicates whether the load balancing is used or not.
v SQL_ATTR_TC_WORKLOAD_CONNECTION
OUT: string, server name of the workload connection
The current workload connection server; if queried before the Commit, the value
indicates the server the transaction will be committed on. It may be queried as
the statement attribute as well. In that case, it indicates the server the next
statement will be executed on.
v SQL_ATTR_LOGIN_TIMEOUT_MS
IN/OUT: integer, login timeout in milliseconds

Note: There is also a standard attribute SQL_ATTR_LOGIN_TIMEOUT that can


be used to set the timeout in seconds.
v SQL_ATTR_CONNECTION_TIMEOUT_MS
IN/OUT: integer, connection timeout in milliseconds

Note: There is also a standard attribute SQL_ATTR_CONNECTION_TIMEOUT


that can be used to set the timeout in seconds.
v SQL_ATTR_QUERY_TIMEOUT_MS
IN/OUT: integer, query timeout in milliseconds

Note: There is also a standard attribute SQL_ATTR_QUERY_TIMEOUT that can


be used to set the timeout in seconds.
v SQL_ATTR_IDLE_TIMEOUT
IN/OUT: integer, connection idle timeout in minutes

30 IBM solidDB: Programmer Guide


Indicates the connection specific idle timeout to be used by the server. If there is
no activity on the connection for specified time period, the server automatically
shuts down the connection, effectively throwing out the user.
Special semantics:
– -1 (default) - the connection timeout is equal to the server default
– 0 - no idle timeout, connection is never closed
This property value can be set only before executing SQLConnect().
v SQL_ATTR_HANDLE_VALIDATION (environment handle attribute)
IN/OUT: integer, turns ODBC standard handle validation on (1) or off (0).
Default is 0.
This attribute is global; when set, it affects all the solidDB ODBC connections
initiated by the application. This ensures consistency by preventing the
application from allocating both validated and non-validated handles.
In certain systems, for example in Windows with ODBC driver manager
involved, the driver manager performs the handle validation and the solidDB
ODBC driver does not have to repeat the same validation procedures by itself.
Also, a carefully written ODBC application normally does not cause invalid
handles to be used; in that case, the handle validation in the ODBC driver is not
needed. In both cases, the applications may benefit from performance
improvements when skipping the handle validation in the driver. In the case the
handle validation is turned off, and invalid handle is used by the application,
the ODBC driver behavior is unpredictable and, most likely, it causes the
application to crash.
v SQL_ATTR_SET_CONNECTION_DEAD
IN/OUT: integer, should be set to 1 when needed
When this attribute is set on a connection, it causes the driver to abort the
connection forcibly, without a disconnecting handshake with the server. After the
attribute is set to 1, the connection becomes unusable.
v SQL_ATTR_PASSTHROUGH_READ
IN: string, SQL passthrough mode for read-type statements ("NONE",
"CONDITIONAL", "FORCE")
v SQL_ATTR_PASSTHROUGH_WRITE
IN: string, SQL passthrough mode for write-type statements ("NONE",
"CONDITIONAL", "FORCE")

Using cursors
The ODBC Driver uses a cursor concept to keep track of its position in the
resultset, that is, in the data rows retrieved from the database. A cursor is used for
tracking and indicating the current position, as the cursor on a computer screen
indicates current position.

Each time an application calls SQLFetch, the driver moves the cursor to the next
row and returns that row. An application can also call SQLFetchScroll or
SQLExtendedFetch (ODBC 2.x), which fetches more than one row with a single
fetch or call into the application buffer. This is known as "block cursor" support.
Note that the actual number of rows fetched depends upon the rowset size
specified by the application.

An application can call SQLSetPos to position a cursor within a fetched block of


data using the SQL_POSITION option. This allows an application to refresh data in

2 Using solidDB ODBC API 31


the rowset. SQLSetPos is also called to update data with the SQL_UPDATE option
or delete data in the resultset with the SQL_DELETE option.

The cursor supported by the core ODBC functions only scrolls forward, one row at
a time. (To re-retrieve a row of data that it has already retrieved from the resultset,
the application must close the cursor by calling SQLFreeStmt with the SQL_CLOSE
option, re-execute the SELECT statement, and fetch rows with SQLFetch, SQLFetch
Scroll, or SQLExtendedFetch (ODBC 2.x) until the target row is retrieved.) If you
need the ability to scroll backward as well as forward, use block cursors.

Assigning storage for rowsets (binding)


In addition to binding individual rows of data, an application can call SQLBindCol
to assign storage for a rowset (one or more rows of data). By default, rowsets are
bound in column-wise fashion. They can also be bound in row-wise fashion.

To specify how many rows of data are in a rowset, an application calls


SQLSetStmtAttr with the SQL_ROWSET_SIZE option.

Column-wise binding

To assign storage for column-wise bound results, an application performs the


following steps for each column to be bound:
1. Allocates an array of data storage buffers. The array has as many elements as
there are rows in the rowset.
2. Allocates an array of storage buffers to hold the number of bytes available to
return for each data value. The array has as many elements as there are rows in
the rowset.
3. Calls SQLBindCol and specifies the address of the data array, the size of one
element of the data array, the address of the number-of-bytes array, and the
type to which the data will be converted. When data is retrieved, the driver
will use the array element size to determine where to store successive rows of
data in the array.

Row-wise binding

To assign storage for row-wise bound results, an application performs the


following steps:
1. Declares a structure that can hold a single row of retrieved data and the
associated data lengths. (For each column to be bound, the structure contains
one field to contain data and one field to contain the number of bytes of data
available to return.)
2. Allocates an array of these structures. This array has as many elements as there
are rows in the rowset.
3. Calls SQLBindCol for each column to be bound. In each call, the application
specifies the address of the column's data field in the first array element, the
size of the data field, the address of the column's number-of-bytes field in the
first array element, and the type to which the data will be converted.
4. Calls SQLSetStmtAttr with the SQL_BIND_TYPE option and specifies the size
of the structure. When the data is retrieved, the driver will use the structure
size to determine where to store successive rows of data in the array.

32 IBM solidDB: Programmer Guide


Cursor support
Applications require different means to sense changes in the tables underlying a
resultset. Various cursor models are designed to meet these needs, each of which
requires different sensitivities to changes in the tables underlying the resultset.

For example, when balancing financial data, an accountant needs data that appears
static; it is impossible to balance books when the data is continually changing.
When selling concert tickets, a clerk needs up-to-the minute, or dynamic, data on
which tickets are still available.

solidDB cursors which are set with SQLSetStmtAttr as "dynamic" closely resemble
static cursors, with some dynamic behavior. solidDB dynamic cursor behavior is
static in the sense that changes made to the resultset by other users are not visible
to the user, as opposed to ODBC dynamic cursors in which changes are visible to
the user.

In solidDB, as long as the cursor scrolls forward from block to block and never
scrolls backward or the cursors move back and forth within the same block after
an update is done, then the user gets the dynamic cursor behavior. This means that
all changes are visible. Note, however that this behavior is affected by the solidDB
AUTOCOMMIT mode setting. For details, read “Cursors and autocommit” on page
34. For an example of cursor behavior when using SQLSetPos, read “Cursors and
positioned operations” on page 35.

Another characteristic of solidDB's cursor behavior is that transactions are able to


view their own data changes (with some limitations), but cannot view the changes
made by other transactions that overlap in time. (For more details about the
limitations on users seeing their own data changes, refer to “Cursors and
positioned operations” on page 35). For example, once Transaction_A starts, it will
not see any changes made by any other transaction that did not commit work
before Transaction_A started. The conditions in solidDB that cause a user's own
changes to be invisible to that user are:
v In a SELECT statement when an ORDER BY clause or a GROUP BY clause is
used, solidDB caches the resultset, which causes the user's own change to be
invisible to the user.
v In applications written using ADO or OLE DB, solidDB cursors are more like
dynamic ODBC cursors to enable functions such as a rowset update.

Specifying the cursor type


To specify the cursor type, an application calls SQLSetStmtAttr with the
SQL_CURSOR_TYPE option. The application can specify a cursor that only scrolls
forward, a static cursor, or a dynamic cursor.

Unless the cursor is a forward-only cursor, an application calls SQLExtendedFetch


(ODBC 2.x) or SQLFetchScroll (ODBC 3.x) to scroll the cursor backwards or
forwards.

Cursor support
This section describes the cursor type supported by solidDB.

Three types of cursors are defined in ODBC 3.51:


v Driver Manager supported cursors
v Server supported cursors
v Driver supported cursors

2 Using solidDB ODBC API 33


solidDB cursors are server supported cursors.

Cursors and autocommit


This section provides information about cursors and autocommit.

For solidDB-specific information about cursors and autocommit, read “Committing


Read-Only Transactions” on page 24.

There are also some limitations in using the solidDB Autocommit mode if your
application uses block cursors and positioned updates and deletes. For a brief
description of these cursor features, read “Using cursors” on page 31.

When using block cursors and positioned updates and deletes, you must:
v In the application, set commit mode to SQL_AUTOCOMMIT_OFF.
v Commit changes in the application only when all the fetch and positioned
operations are done.
v In between positioned operations, be sure not to commit the changes.

Attention:

If the application uses commit mode as SQL_AUTOCOMMIT_ON or commits the


changes before it is done with all the positioned operation, then the application
may experience unpredictable behavior while browsing through the resultset. Read
the section below for details.

Positioned Cursor Operations and SQL_AUTOCOMMIT_ON

The solidDB ODBC Driver keeps a row number/counter for every row in the
rowset, which is the data rows retrieved from the database. When an application
has the commit mode set to SQL_AUTOCOMMIT_ON and then executes a
positioned update or a delete on a row in the rowset, the row is immediately
updated in the database. Depending on the new value of the row, the row may be
moved from its original position in the resultset. Since the updated row has now
moved and its new position is unpredictable (since it is totally dependent on the
new value), the driver loses the counter for this row.

In addition, the counter for all other rows in the rowset may also become invalid
because of a change in position of the updated row. Hence the application may see
incorrect behavior when it does the next fetch or SQLSetPos operation.

Following is an example that explains this limitation.

Assume an application performs the following steps:


1. Sets the commit mode to SQL_AUTOCOMMIT_ON.
2. Sets the rowset size to 5.
3. Executes a query to generate a resultset containing n rows.
4. Fetches the first rowset of 5 rows with SQLFetchScroll.
A sample resultset is shown below. In the sample, the resultset has only 1
column (defined as varchar(32)). In the table below, the first column shows the
row number maintained by the driver internally. The second column shows the
actual row values.

34 IBM solidDB: Programmer Guide


Table 7. A Sample Resultset

Row Counter Stored Internally by the


Driver Row Value

1 Antony

2 Ben

3 Charlie

4 David

5 Edgar

Assume now that the application calls SQLSetPos to update the third row with a
new value of Gerard. To perform the update, the new row value is moved and
positioned as shown below:
Table 8. A sample resultset

Row Counter Stored Internally by the


Driver Row Value

1 Antony

2 Ben

Empty row

4 David

5 Edgar

New row Gerard

Now the row counter for "David" becomes 3 and not 4, while the counter for
"Edgar" becomes 4 and not 5. Since some row counters are now invalid, they will
give wrong results when used by the driver to do relative or absolute positioning
of the cursor.

If the commit mode had been set to SQL_AUTOCOMMIT_OFF, the database is not
updated until the SQLEndTran function is called to commit the changes.

For solidDB-specific information about cursors and autocommit, read “Committing


Read-Only Transactions” on page 24.

Cursors and positioned operations


When an application is performing positioned operations (such as updates and
deletes when calling SQLSetPos), there are limitations in resultset visibility.

Case 1 illustrates cursor behavior when using SQLSetPos. In Case 1, the cursor
scrolls back and forth within the same block after the update is applied.

2 Using solidDB ODBC API 35


Although Case 1 is intended to illustrate the visibility of updates in the resultset
when using cursors, the exact circumstances under which visibility occurs depends
on several factors. These include the size of the resultset relative to the size of the
memory buffer, the transaction isolation level, and the frequency with which you
commit data, and so on.

Case 2 shows how cursor behavior is limited using SQLSetPos when the cursor
scrolls backward within a rowset or the cursors move back and forth within a
different rowset after an update is applied.

Case 1

Following is an example that shows cursor behavior using positioned operations


and shows how positioned updates can be visible to users.

Assume an application performs the following steps:


1. Sets the commit mode to SQL_AUTOCOMMIT_OFF.
This is a requirement described in “Cursors and autocommit” on page 34.
2. Sets the rowset size to 5.
3. Executes a query to generate a resultset of n rows.
4. Fetches the first rowset of 5 rows with SQLFetchScroll.

A sample resultset is shown below. In the sample, the resultset has only 1 column
(defined as varchar(32)). In the table below, the first column shows the row
number maintained by the driver internally. The second column shows the actual
row values.
Table 9. A sample resultset

Row Counter Stored Internally by the


Driver Row Value

1 Antony

2 Ben

3 Charlie

4 David

5 Edgar

Assume now that the application calls SQLSetPos to update the third and fourth
rows of the resultset with the names Caroline and Debbie. After the updates, the
actual row values now contain Caroline and Debbie, as shown below:
Table 10. A Sample Resultset

Row Counter Stored Internally by the


Driver Row Value

1 Antony

2 Ben

36 IBM solidDB: Programmer Guide


Table 10. A Sample Resultset (continued)

Row Counter Stored Internally by the


Driver Row Value

3 Caroline

4 Debbie

5 Edgar

Note: In some cases, the resultset for a SELECT statement may be too large to fit
in memory. As the user scrolls back and forth within the resultset, the ODBC
Driver may discard some rows from memory and read in others. This can cause
unexpected results: in some situations, updates to data in the cursor may seem to
"disappear" and then "reappear" if the cursor re-reads (for example, from disk) the
original values for a row that it previously modified.

Case 2

Case 2 shows the limitations when using positioned operations. The following
example shows cursor behavior using positioned operations and shows when
position updates are not visible to users.

Assume an application performs the following steps:


1. Sets the commit mode to SQL_AUTOCOMMIT_OFF.
This is a requirement explained in “Cursors and autocommit” on page 34.
2. Sets the rowset size to 5.
3. Executes a query to generate a resultset of n rows.
4. Fetches the first rowset of 5 rows with SQLFetchScroll.
A sample resultset is shown below. In the sample, the first two rowsets are
shown. The resultset has only 1 column (defined as varchar(32)). In the table
below, the first column shows the row number maintained by the driver
internally. The second column shows the actual row values.
Table 11. A Sample Resultset

Row Counter Stored Internally by the


Driver Row Value

1 Antony

2 Ben

3 Charlie

4 David

5 Edgar

6 Fred

7 Gough

2 Using solidDB ODBC API 37


Table 11. A Sample Resultset (continued)

Row Counter Stored Internally by the


Driver Row Value

8 Harry

9 Ivor

10 John

Assume that after the first 4 steps above, the application calls SQLSetPos to
perform the following tasks:
5. Updates the third row of the resultset.
6. Scrolls to the next rowset by calling SQLFetchScroll. This will get rows 6 to 10
and the cursor will be pointing to row 6.
7. Scrolls backward one rowset to get to the first rowset. This is done by calling
SQLScrollFetch with the FETCH_PRIOR option.

After these tasks are performed, the value of the third row that was updated in
step 5 still has the old value rather than the updated value as in "Case 1". The
updated value is only visible in the Case 2 situation when the change is
committed. But due to the unpredictable behavior when setting
SQL_AUTOCOMMIT_ON as described in section “Positioned Cursor Operations
and SQL_AUTOCOMMIT_ON” on page 34, commits cannot be done until all work
related to block cursors and positioned operations is completed.

Using bookmarks
A bookmark is a 32-bit value that an application uses to return to a row. solidDB
provides no support for bookmarks.

Error text format


Error messages returned by SQLError come from two sources: data sources and
components in an ODBC connection. The error text must use a specific format
depending of where the error is issued.

Typically, data sources do not directly support ODBC. Consequently, if a


component in an ODBC connection receives an error message from a data source,
it must identify the data source as the source of the error. It must also identify
itself as the component that received the error.

If the source of an error is the component itself, the error message must explain
this. Therefore, the error text returned by SQLError has two different formats: one
for errors that occur in a data source and one for errors that occur in other
components in an ODBC connection.

For errors that do not occur in a data source, the error text must use the format:
[vendor_identifier][ODBC_component_identifier]
component_supplied_text

For errors that occur in a data source, the error text must use the format:
[vendor_identifier][ODBC_component_identifier]
[data_source_identifier] data_source_supplied_text

38 IBM solidDB: Programmer Guide


The following table shows the meaning of each element.
Table 12. Errors in a Data Source

Element Meaning

vendor_identifier Identifies the vendor of the component in which the error


occurred or that received the error directly from the data
source.

ODBC_component_identifier Identifies the component in which the error occurred or


that received the error directly from the data source.

data_source_identifier Identifies the data source. For single-tier drivers, this is


typically a file format. For multiple-tier drivers, this is the
DBMS product.

component_supplied_text Generated by the ODBC component.

data_source_supplied_text Generated by the data source.

Note: The brackets ([ ]) are included in the error text; they do not indicate optional
items.

Sample error messages

The following examples show how various components in an ODBC connection


might generate the text of error messages and how solidDB returns them to the
application with SQLError.
Table 13. Sample Error Messages

SQLSTATE Error Message

01000 General warning

01S00 Invalid connection string attribute

08001 Client unable to establish connection

SQLSTATE values are strings that contain five characters; the first two are a class
value, followed by a three-character subclass value. For example 01000 has 01 as its
class value and 000 as its subclass value. Note that a subclass value of 000 means
there is no subclass for that SQLSTATE. Class and subclass values are defined in
SQL-92.
Table 14. SQLSTATE values

Class value Meaning

01 Indicates a warning and includes a return code of


SQL_SUCCESS_WITH_INFO.
Note: Error class 01 returns both warnings and errors.

2 Using solidDB ODBC API 39


Table 14. SQLSTATE values (continued)

Class value Meaning

01, 07, 08, 21, 22, 23, 24, 25, Indicates an error that includes a return value of
28, 34, 3C, 3D, 3F, 40, 42, 44, SQL_ERROR.
HY Note: Error class 01 returns both warnings and errors.

IM Indicates warning and errors that are derived from ODBC.

Related reference:
Appendix C, “SQLSTATE error codes,” on page 195
This topic contains an error codes table that provides possible SQLSTATE values
that a driver returns for the SQLGetDiagRec function.

Processing error messages


Applications provide users with all the error information available through
SQLError: the ODBC SQLSTATE, the native error code, the error text, and the
source of the error.

The application may parse the error text to separate the text from the information
identifying the source of the error. It is the application's responsibility to take
appropriate action based on the error or provide the user with a choice of actions.

The ODBC interface provides functions that terminate statements, transactions, and
connections, and free statement, connection, and environment handles.

Terminating transactions and connections


The ODBC interface provides functions that terminate statements, transactions, and
connections, and free statement (hstmt), connection (hdbc), and environment
(henv) handles.

Terminating Statement Processing


To free resources associated with a statement handle, an application calls
SQLFreeStmt with the following options:
v SQL_CLOSE - Closes the cursor, if one exists, and discards pending results. The
application can use the statement handle again later. In ODBC 3.51,
SQLCloseCursor can also be used.
v SQL_UNBIND - Frees all return buffers bound by SQLBindCol for the statement
handle.
v SQL_RESET_PARAMS - Frees all parameter buffers requested by
SQLBindParameter for the statement handle.

SQLFreeHandle is used to close the cursor if one exists, discard pending results,
and free all resources associated with the statement handle.

Terminating transactions

An application calls SQLEndTran to commit or roll back the current transaction.

40 IBM solidDB: Programmer Guide


Terminating connections

To terminate a connection to a driver and data source, an application performs the


following steps:
1. Calls SQLDisconnect to close the connection. The application can then use the
handle to reconnect to the same data source or to a different data source.
2. Calls SQLFreeHandle to free the connection or environment handle and free all
resources associated with the handle.

Constructing an application
This section provides two examples of C-language source code for applications: an
example that uses static SQL functions to create a table, add data to it, and select
the inserted data; and another example of interactive, ad-hoc query processing.

Microsoft provides two types of header files, one for ASCII data and the other for
Unicode data. This example can use either of the Microsoft ODBC header files.

Static SQL example

The following example constructs SQL statements within the application.


/***************************************************************
Sample Name: Example1.c
Author : IBM

Location : CONSTRUCTING AN APPLICATION-


Programmer Guide
Purpose : Sample example that uses static SQL
functions to
create a table,
add data to it, and
select the inserted data.

***************************************************************/
#if (defined(SS_UNIX) || defined(SS_LINUX))
#include <solidodbc3.h>
#else
#include <windows.h>
#endif

#include <stdio.h>
#include <test_assert.h>

#define MAX_NAME_LEN 50
#define MAX_STMT_LEN 100

/**************************************************************
Function Name: PrintError
Purpose......: To Display the error associated with
the handle
***************************************************************/
SQLINTEGER PrintError(SQLSMALLINT handleType,SQLHANDLE handle)
{
SQLRETURN rc = SQL_ERROR;
SQLWCHAR sqlState[6];
SQLWCHAR eMsg[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER nError;

rc = SQLGetDiagRecW(handleType, handle, 1,
(SQLWCHAR *)&sqlState, (SQLINTEGER *)&nError,
(SQLWCHAR *)&eMsg, 255, NULL);

2 Using solidDB ODBC API 41


if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
printf("\n\t Error:%ls\n",eMsg);
}
return(SQL_ERROR);
}

/**************************************************************
Function Name: DrawLine
Purpose : To Draw a specified charcter (chr) for
specified number of times (len)
**************************************************************/
void DrawLine(SQLINTEGER len, SQLCHAR chr)
{
printf("\n");
while(len > 0) {
printf("%c",chr);
len--;
}
printf("\n");

/***************************************************************
Function Name: example1
Purpose : Connect to the specified data source and
execute the set of SQL Statements
***************************************************************/
SQLINTEGER example1(SQLCHAR *server, SQLCHAR *uid, SQLCHAR *pwd)
{
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
SQLRETURN rc;

SQLINTEGER id;
SQLWCHAR drop[MAX_STMT_LEN];
SQLCHAR name[MAX_NAME_LEN+1];
SQLWCHAR create[MAX_STMT_LEN];
SQLWCHAR insert[MAX_STMT_LEN];
SQLWCHAR select[MAX_STMT_LEN];
SQLINTEGER namelen;

/* Allocate environment and connection handles. */


/* Connect to the data source. */
/* Allocate a statement handle. */

rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE,
&henv);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV,henv));

rc = SQLSetEnvAttr(henv,SQL_ATTR_ODBC_VERSION,
(SQLPOINTER)SQL_OV_ODBC3,SQL_NTS);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV, henv));

rc = SQLAllocHandle(SQL_HANDLE_DBC,henv,&hdbc);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV, henv));

rc = SQLConnect(hdbc, server, SQL_NTS, uid, SQL_NTS,


pwd, SQL_NTS);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

42 IBM solidDB: Programmer Guide


rc = SQLAllocHandle(SQL_HANDLE_STMT,hdbc,&hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* drop table ’nameid’ if exists, else continue*/


wcscpy(drop, L"DROP TABLE NAMEID");
printf("\n%ls", drop);
DrawLine(wcslen(drop), ’-’);

rc = SQLExecDirectW(hstmt, drop, SQL_NTS);


if (rc == SQL_ERROR) {
PrintError(SQL_HANDLE_STMT, hstmt);
}

/* commit work*/
rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* create the table nameid(id integer,name varchar(50))*/


wcscpy(create,
L"CREATE TABLE NAMEID(ID INT,NAME VARCHAR(50))");
printf("\n%ls",create);
DrawLine(wcslen(create),’-’);

rc = SQLExecDirectW(hstmt,create,SQL_NTS);
if (rc == SQL_ERROR)
return(PrintError(SQL_HANDLE_STMT,hstmt));

/* commit work*/
rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* insert data through parameters*/


wcscpy(insert, L"INSERT INTO NAMEID VALUES(?,?)");
printf("\n%ls", insert);
DrawLine(wcslen(insert), ’-’);

rc = SQLPrepareW(hstmt, insert, SQL_NTS);


if (rc == SQL_ERROR)
return(PrintError(SQL_HANDLE_STMT,hstmt));

/* integer(id) data binding*/


rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT,
SQL_C_LONG, SQL_INTEGER, 0, 0, &id, 0, NULL);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* char(name) data binding*/


rc = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT,
SQL_C_CHAR, SQL_VARCHAR, 0, 0, &name,
sizeof(name), NULL);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

id = 100;
strcpy(name, "SOLID");

rc = SQLExecute(hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* commit work*/
rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT);

2 Using solidDB ODBC API 43


if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* free the statement buffers*/


rc = SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT, hstmt));

rc = SQLFreeStmt(hstmt, SQL_CLOSE);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT, hstmt));

/* select data from the table nameid*/


wcscpy(select, L"SELECT * FROM NAMEID");
printf("\n%ls", select);
DrawLine(wcslen(select), ’-’);

rc = SQLExecDirectW(hstmt, select, SQL_NTS);


if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* bind buffers for output data*/


id = 0;
strcpy(name, "");

rc = SQLBindCol(hstmt, 1, SQL_C_LONG, &id, 0, NULL);


if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

rc = SQLBindCol(hstmt, 2, SQL_C_CHAR, &name,


sizeof(name), &namelen);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

rc = SQLFetch(hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

printf("\n Data ID :%d", id);


printf("\n Data Name :%s(%d)\n", name, namelen);

rc = SQLFetch(hstmt);
assert(rc == SQL_NO_DATA);

/* free the statement buffers*/


rc = SQLFreeStmt(hstmt, SQL_UNBIND);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT, hstmt));

rc = SQLFreeStmt(hstmt, SQL_CLOSE);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT,hstmt));

/* Free the statement handle. */


rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT, hstmt));

/* Disconnect from the data source. */


rc = SQLDisconnect(hdbc);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* Free the connection handle. */


rc = SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)

44 IBM solidDB: Programmer Guide


return(PrintError(SQL_HANDLE_DBC, hdbc));

/* Free the environment handle. */


rc = SQLFreeHandle(SQL_HANDLE_ENV,henv);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV, henv));

return(0);
}

/***************************************************************
Function Name: main
Purpose : To Control all operations
***************************************************************/
void main(SQLINTEGER argc, SQLCHAR *argv[])
{
puts("\n\t SOLID ODBC Driver 3.51:");
puts("\n\t -Usage of static SQL functions");
puts("\n\t ==============================");

if (argc != 4){
puts("USAGE: Example1 <DSN name> <username> <passwd>");
exit(0);
}
else {
example1(argv[1], argv[2], argv[3]);
}
}

Interactive ad hoc query example

The following example illustrates how an application can determine the nature of
the resultset prior to retrieving results.
/***************************************************************
Sample Name : Example2.c(ad-hoc query processing)
Author : IBM

Location : CONSTRUCTING AN APPLICATION-


Programmer Guide
Purpose : To illustrate how an application determines
the nature of the result set prior to
retrieving results.

***************************************************************/
#if (defined(SS_UNIX) || defined(SS_LINUX))
#include <solidodbc3.h>
#else
#include <windows.h>
#endif

#include <stdio.h>

#ifndef TRUE
#define TRUE 1
#endif

#define MAXCOLS 100


#define MAX_DATA_LEN 255

SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;

/***************************************************************

2 Using solidDB ODBC API 45


Function Name: PrintError
Purpose : To Display the error associated with
the handle
***************************************************************/
SQLINTEGER PrintError(SQLSMALLINT handleType, SQLHANDLE handle)
{
SQLRETURN rc = SQL_ERROR;
SQLCHAR sqlState[6];
SQLCHAR eMsg[SQL_MAX_MESSAGE_LENGTH];
SQLINTEGER nError;

rc = SQLGetDiagRec(handleType, handle, 1,
(SQLCHAR *)&sqlState, (SQLINTEGER *)&nError,
(SQLCHAR *)&eMsg, 255, NULL);
if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
printf("\n\t Error:%s\n",eMsg);
}
return(SQL_ERROR);
}

/**************************************************************
Function Name: DrawLine
Purpose : To Draw a specified character (line) for
specified number of times (len)
**************************************************************/
void DrawLine(SQLINTEGER len, SQLCHAR line)
{
printf("\n");
while(len > 0) {
printf("%c",line);
len--;
}
printf("\n");

/***************************************************************
Function Name: example2
Purpose : Connect to the specified data source and
execute the given SQL statement.
***************************************************************/
SQLINTEGER example2(SQLCHAR *sqlstr)
{
SQLINTEGER i;

SQLCHAR colname[32];
SQLSMALLINT coltype;
SQLSMALLINT colnamelen;
SQLSMALLINT nullable;
SQLINTEGER collen[MAXCOLS];
SQLSMALLINT scale;
SQLINTEGER outlen[MAXCOLS];
SQLCHAR data[MAXCOLS][MAX_DATA_LEN];
SQLSMALLINT nresultcols;
SQLINTEGER rowcount, nRowCount=0, lineLength=0;
SQLRETURN rc;

printf("\n%s",sqlstr);
DrawLine(strlen(sqlstr),’=’);

/* Execute the SQL statement. */


rc = SQLExecDirect(hstmt, sqlstr, SQL_NTS);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT, hstmt));

46 IBM solidDB: Programmer Guide


/* See what kind of statement it was. If there are */
/* no result columns, the statement is not a SELECT */
/* statement. If the number of affected rows is */
/* greater than 0, the statement was probably an */
/* UPDATE, INSERT, or DELETE statement, so print */
/* the number of affected rows. If the number of */
/* affected rows is 0, the statement is probably a */
/* DDL statement, so print that the operation was */
/* successful and commit it. */

rc = SQLNumResultCols(hstmt, &nresultcols);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT, hstmt));

if (nresultcols == 0) {
rc = SQLRowCount(hstmt, &rowcount);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
return(PrintError(SQL_HANDLE_STMT, hstmt));
}
if (rowcount > 0 ) {
printf("%ld rows affected.\n", rowcount);
}
else {
printf("Operation successful.\n");
}

rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, SQL_COMMIT);


if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

}
/* Otherwise, display the column names of the result */
/* set and use the display_size() function to */
/* compute the length needed by each data type. */
/* Next, bind the columns and specify all data will */
/* be converted to char. Finally, fetch and print */
/* each row, printing truncation messages as */
/* necessary. */
else {
for (i = 0; i < nresultcols; i++) {
rc = SQLDescribeCol(hstmt, i + 1, colname,
(SQLSMALLINT)sizeof(colname),
&colnamelen, &coltype, &collen[i],
&scale, &nullable);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO){
return(PrintError(SQL_HANDLE_STMT, hstmt));
}
/* print column names */
printf("%s\t", colname);
rc = SQLBindCol(hstmt, i + 1, SQL_C_CHAR,
data[i], sizeof(data[i]), &outlen[i]);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO){
return(PrintError(SQL_HANDLE_STMT, hstmt));
}
lineLength += 6 + strlen(colname);
}

DrawLine(lineLength-6,’-’);

while (TRUE) {
rc = SQLFetch(hstmt);
if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO){
nRowCount++;
for (i = 0; i < nresultcols; i++) {
if (outlen[i] == SQL_NULL_DATA) {

2 Using solidDB ODBC API 47


strcpy((char *)data[i], "NULL");
}
printf("%s\t",data[i]);
}
printf("\n");
}

else {
if (rc == SQL_ERROR)
PrintError(SQL_HANDLE_STMT, hstmt);
break;
}
}
printf("\n\tTotal Rows:%d\n", nRowCount);
}

SQLFreeStmt(hstmt, SQL_UNBIND);
SQLFreeStmt(hstmt, SQL_CLOSE);
return(0);

/***************************************************************
Function Name: main
Purpose : To Control all operations
***************************************************************/
int __cdecl main(SQLINTEGER argc, SQLCHAR *argv[])
{
SQLRETURN rc;

printf("\n\t SOLID ODBC Driver 3.51-Interactive");


printf("\n\t ad-hoc Query Processing");
printf("\n\t ==================================\n");

if (argc != 4) {
puts("USAGE: Example2 <DSN name> <username> <passwd>");
exit(0);
}

/* Allocate environment and connection handles. */


/* Connect to the data source. */
/* Allocate a statement handle. */
rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV, henv));

rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
(SQLPOINTER)SQL_OV_ODBC3, SQL_NTS);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV, henv));

rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);


if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV, henv));

printf("\n Connecting to %s\n ", argv[1]);


rc = SQLConnect(hdbc, argv[1], SQL_NTS, argv[2], SQL_NTS,
argv[3], SQL_NTS);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);


if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

48 IBM solidDB: Programmer Guide


/* execute the following SQL statements */
example2("SELECT * FROM SYS_TABLES");
example2("DROP TABLE TEST_TAB");
example2("CREATE TABLE TEST_TAB(F1 INT, F2 VARCHAR)");
example2("INSERT INTO TEST_TAB VALUES(10, ’SOLID’)");
example2("INSERT INTO TEST_TAB VALUES(20, ’MVP’)");
example2("UPDATE TEST_TAB SET F2=’UPDATED’ WHERE F1 = 20");
example2("SELECT * FROM TEST_TAB");

/* Free the statement handle. */


rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_STMT, hstmt));

/* Disconnect from the data source. */


rc = SQLDisconnect(hdbc);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* Free the connection handle. */


rc = SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_DBC, hdbc));

/* Free the environment handle. */


rc = SQLFreeHandle(SQL_HANDLE_ENV, henv);
if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO)
return(PrintError(SQL_HANDLE_ENV, henv));

return(0);

Testing and debugging an application


The Microsoft ODBC SDK provides tools for application development.

The tools included are as follows:


v ODBC Test, an interactive utility that enables you to perform ad hoc and
automated testing on drivers. A sample test DLL (the Quick Test) is included,
which covers basic areas of ODBC driver conformance.
v ODBC Spy, a debugging tool with which you can capture data source
information, emulate drivers, and emulate applications.
v Sample applications, including source code and makefiles:
– A #define, ODBCVER, to specify which version of ODBC you want to
compile your application with. To use the ODBC 3.51 constants and
prototypes, add the following line to your application code before providing
the include files.
#define ODBCVER 0X0352
– For solidDB specific ODBC extensions, include the solidodbc3.h header file.

For additional information about the ODBC SDK tools, see the Microsoft ODBC
SDK Guide.

2 Using solidDB ODBC API 49


50 IBM solidDB: Programmer Guide
3 Using solidDB JDBC Driver
The solidDB JDBC Driver 2.0 is a JDBC type 4 driver. Type 4 means that it is a
100% Pure Java implementation of the Java Database Connectivity (JDBC) 2.0
standard.

The JDBC API defines Java classes to represent database connections, SQL
statements, result sets, database metadata, and so on. It allows a Java programmer
to issue SQL statements and process the results. JDBC is the primary API for
database access in Java. More information on the JDBC technology can be found at
the JDBC Technology Homepage ([Link]

The solidDB JDBC Driver is written entirely in Java and it communicates directly
with the solidDB server using the TCP/IP network protocol. The solidDB JDBC
Driver does not require any additional database access libraries. The driver
requires that a Java Runtime Environment (JRE) or Java Development Kit (JDK) is
available.

What is solidDB JDBC Driver


This topic provides information about the solidDB JDBC driver.

The JDBC API defines Java classes to represent database connections, SQL
statements, result sets, database metadata, and so on. It allows a Java programmer
to issue SQL statements and process the results. JDBC is the primary API for
database access in Java. More information about the JDBC technology can be found
at the JDBC Technology Homepage ([Link]

solidDB's JDBC driver is written entirely in Java and communicates directly with
the solidDB server using the TCP/IP network protocol. The solidDB driver does
not require any additional database access libraries, such as ODBC. The driver
requires that a JRE (Java Runtime Environment) or JDK (Java Development Kit) is
available.

The solidDB JDBC Driver is a solidDB implementation of the JDBC 2.0 standard. It
is usable in all Java environments supporting JDK 1.4.2 and above.

Getting started with solidDB JDBC Driver


The solidDB JDBC Driver ([Link]) is installed during solidDB
installation. You can verify the installation using a sample Java program that is
provided in the solidDB package. Depending on your environment, you may need
to set various configuration settings before using the solidDB JDBC Driver.

Default installation directory

The solidDB JDBC Driver is installed during the solidDB server installation into
the jdbc directory.

If your application is located on a different computer than the solidDB server, you
need to copy the JDBC driver file to the computer where the application is located.

Tip:

51
v The jdbc directory contains also the solidDB Data Store Helper Class
([Link]) for use with WebSphere®.
v The samples/jdbc directory in the solidDB installation directory contains Java
code samples that use the solidDB JDBC Driver. Instructions for running the
sample are available in the [Link] file, which located in the same directory.

Requirements for Java environment


v Ensure that you have a working Java runtime or development environment that
supports JDBC API specification release 2.0.
v Check from your Java environment documentation whether it can use
compressed bytecode. The [Link] contains the solidDB JDBC
Driver classes in compressed bytecode format usable by most Java Virtual
Machines. However, some environments (such as Microsoft J++) require
uncompressed bytecode. If your environment requires uncompressed bytecode,
you must extract the [Link] file using a tool that supports long
filenames.

Setting the CLASSPATH environmental variable

The CLASSPATH environment variable for your environment needs to include the
solidDB JDBC Driver .jar file installation path.
v Windows
The installation adds the default solidDB JDBC Driver installation path to the
System CLASSPATH environment variable automatically.
You can check and set the System CLASSPATH environment variable through
the Control Panel:
Control Panel > System > Advanced > Environment Variables
v Linux and UNIX
Set your CLASSPATH environment variable to include the solidDB JDBC Driver
([Link]) installation path.
For example, in Bourne shell, use the following command:
export CLASSPATH=<solidDB installation directory>/jdbc/[Link]:$CLASSPATH
If you are using another shell than the Bourne shell, modify this command to
make it appropriate for your shell.

Verifying the installation with [Link]

The [Link] sample application (available in the samples/jdbc directory) can


be used for validating the solidDB JDBC Driver installation.

The [Link] sample application performs the following actions:


1. Registers the solidDB JDBC Driver using JDBC Driver Manager services.
2. Asks for the connect string for a running solidDB process.
3. Connects to solidDB using the driver.
4. Creates the following statement for one query for retrieving data from one of
the solidDB system tables:
SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME,
TABLE_TYPE FROM TABLES
5. Executes the query.
6. Fetches all the rows of a result set.
An empty solidDB database dictionary contains approximately 86 rows.

52 IBM solidDB: Programmer Guide


Running the sample

Before running the sample, check the following:


v Your PATH environment variable contains the directories that hold the Java
compiler and JRE.
v The samples/jdbc directory contains a valid solidDB (evaluation) license.
1. If you do not already have a solidDB process running, start it now and create
an empty database.
2. Change your working directory to /samples/jdbc, which is the directory that
contains the sample Java program.
3. Compile the Java sample program:
javac [Link]
4. Start the sample application with the command:
java sample1
5. The application prompts for a valid connect string. The connect string format
is:
jdbc:solid://<hostname>:<port>/<username>/<password>
For example, the following string attempts to connect to a solidDB server at
host 'mymachine' which listens to TCP/IP protocol at port 2315.
jdbc:solid://localhost:2315/dba/dba
After entering the connect string, the sample application outputs the query
results.

Troubleshooting the [Link] sample application

Possible problems in running the [Link] sample application and solutions


for them are listed below:
1. The driver cannot be successfully registered.
v The Java environment does not support [Link] classes.
v [Link] is not in the CLASSPATH definition.
2. Unable to connect to solidDB process
v The version of the solidDB server should be 6.5 or later.
Older solidDB versions may refuse connections from the driver that is
provided with the current release.
v The connect string may be wrong or solidDB may not be listening to the
specified TCP/IP.
Check that solidDB is running and verify the listening information. You can
use, for example, solidDB SQL Editor (solsql) to ensure that a connection can
be established through the network.

Registering solidDB JDBC Driver


The JDBC driver manager handles loading and unloading drivers and interfacing
connection requests with the appropriate driver.

The driver can be registered as shown below. After execution of this code, the
driver registers itself in the DriverManager.
// registration using [Link] service
[Link]("[Link]");

3 Using solidDB JDBC Driver 53


Connecting to the database
Once the driver is successfully registered with the driver manager, a connection is
established by creating an instance of [Link].

The following code example creates an instance of [Link].


Connection conn = null;
// sCon is the JDBC connection string
(jdbc:solid://hostname:port/login/password)
String sCon = "jdbc:solid://fb9:1314/dba/dba";
try {
conn = [Link](sCon);
} catch (SQLException e) {
[Link]("Connect failed : " + [Link]());
}

The parameter required by the [Link] function is the JDBC


connection string. The JDBC connection string identifies which computer the
database server is running on; the string also contains other information required
to connect to the server.

The syntax of the JDBC URL (connection string) for solidDB is:
jdbc:solid://<hostname>:<port>/<username>/<password>[?<property-name>=<value>]...

For example, the following connect string attempts to connect to a solidDB server
in machine fb9 listening to the tcp/ip protocol at port 1314:
"jdbc:solid://fb9:1314/dba/dba"

The application can establish multiple connections to the database by using


multiple Connection objects. You should manage connection lifecycle in a very
accurate way, otherwise there may be conflicts between concurrent users and
applications trying to access the database. For details and instructions, see “Code
examples” on page 78.

Note: ThesolidDB JDBC Driver only supports a connection for administration


options, with no queries allowed. For this type of connection, set the
[Link] name ADMIN_ USER to true. After it is set to true and a
connection is established, only ADMIN commands are allowed.

Transactions and autocommit mode

As the JDBC specification defines, a connection to the solidDB database can be in


either autocommit or non-autocommit mode.
v When not in autocommit mode, each transaction needs to be explicitly
committed before the modifications it made can be seen by other database
connections.
v The autocommit state can be monitored by [Link]()
method.
v The state can be set by [Link](). An solidDB server's default
setting for autocommit state is true.
v If autocommit mode is off, then the transactions can be committed in two ways.
– calling the [Link]() method, or
– executing a statement for SQL 'COMMIT WORK'

54 IBM solidDB: Programmer Guide


Handling database errors

Database errors in JDBC are handled and managed by the exception mechanism.
Most of the methods specified in JDBC interfaces may throw an instance of
SQLException. As these errors may appear in the normal application workflow
(representing concurrency conflicts, for instance) your code should be tolerant to
such errors. Basically, you must not leave your connections in any other state than
"closed" regardless of the result of your code's execution. This approach allows
avoiding situations where all available connections remain open due to unhandled
exceptions.

You can get an exception's error code by calling [Link](). For listings of
solidDB error codes, see the Appendix Error codes in IBM solidDB Administrator
Guide.

The following code example shows a correct way of handling errors coming from
the database:
Public void listTablesExample() {
try {
[Link]("[Link]");
} catch (ClassNotFoundException e) {
[Link]("Solid JDBC driver is not registered
in the classpath");
return; //exit from the method
}
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = [Link]("jdbc:solid://
localhost:1313", "dba", "dba");
stmt = [Link]();
rs = [Link]("SELECT * FROM tables");
while ([Link]()) {
[Link]([Link](0));//printing
out results
}
} catch (SQLException e) {
[Link]();
} finally {
/* It’s a good idea to release
resources in a finally{} block
in reverse-order of their creation
if they are no-longer needed
*/
if (rs != null) {
try {
[Link]();
} catch (SQLException sqlEx) { // ignore
rs = null;
}
}
if (stmt != null) {
try {
[Link]();
} catch (SQLException sqlEx) { // ignore
stmt = null;
}
}
}
if (conn != null)
try {
[Link]();

3 Using solidDB JDBC Driver 55


} catch (SQLException e) {
[Link]();
} finally {
conn = null;
}
}

Special notes about solidDB and JDBC


JDBC does not specify what SQL dialect you can use; it simply passes the SQL on
to the driver and lets the driver either pass it on directly to the database, or parse
the SQL itself. Because of this, the solidDB JDBC Driver behavior is particular to
solidDB.

In some functions, the JDBC specification leaves some details open. For the details
particular to solidDB's implementation of the methods, check “JDBC driver
interfaces and methods”.

The solidDB JDBC Driver provides support for catalogs and schemas in solidDB.

Executing stored procedures

In solidDB databases, stored procedures can be called by executing statements CALL


proc_name [( parameter ...)]’ as in any other SQL statement. Procedures can
also be used in JDBC in the same way, through a standard CallableStatement
interface.

Note: solidDB stored procedures can return result sets. Calling procedures through
the JDBC CallableStatement interface is not necessary. For an example of calling
solidDB procedures using JDBC, see the source code for the Sample 3 application
in “Code examples” on page 78.

JDBC driver interfaces and methods


solidDB JDBC Driver 2.0 is compatible with the JDBC 2.0 standard, with support to
selected features of JDBC 2.0 Optional Package (known before as Standard
Extension).

This topic describes solidDB-specific differences from the standard API. You can
browse standard packages and interfaces in the [Link] and [Link] packages,
and see details of a particular implementation by checking the list of "All Known
Implementing Classes".

For a description of how different data types are supported by solidDB JDBC
Driver, see “solidDB JDBC Driver type conversion matrix” on page 90.

Array

The [Link] interface is not supported. This interface is used to map SQL
type Array in the Java programming language. It reflects the SQL-99 standard that
is currently unavailable in solidDB.

Blob

The [Link] interface is not supported. This interface is used to map SQL type
Blob in the Java programming language. It reflects the SQL-99 standard that is
currently unavailable in solidDB.

56 IBM solidDB: Programmer Guide


CallableStatement

A [Link] interface is intended to support calling database


stored procedures. Thus, solidDB stored procedures are used in JDBC in the same
way as any statement; the use of class CallableStatement is not necessary when
you are writing applications on a solidDB server only. However, for portability
reasons, using CallableStatement is a wise choice.

Note: The JDBC Driver allows for the creation of a Statement object that generates
ResultSet objects with the given type and concurrency. This differs from the
createStatement method in JDBC 1.0 because it allows the default result set type
and result set concurrency type to be overridden.

Differences with the standard API

Following are the differences from the standard CallableStatement interface defined
in the JDBC API.
Table 15. Differences to the Standard CallableStatement Interface

Method name Notes

getArray(int i) Not supported by solidDB.

getBlob(int i) Not supported by solidDB.

getClob(int i) Not supported by solidDB.

getDate(int parameterIndex, Calendar cal) Works as specified in Java API.


Note: Uses a given Calendar object to
specify time zone and locale, different from
default ones. The same rule corresponds to
other similar methods operating with
Calendar instances.

getObject (int i, Map map) Not supported by solidDB.

getRef(int i) Not supported by solidDB.

registerOutParameter(int parameterIndex, int Not supported by solidDB. This method


sqlType, String typeName) throws an exception with the following
message: "This method is not supported"

Clob

The [Link] interface is not supported. This interface is used to map SQL type
Clob in the Java programming language. It reflects the SQL-99 standard that is
currently unavailable in solidDB.

Connection

The [Link] interface is a public interface. It is used to establish a


connection (session) with a specified database. SQL statements are executed and
results are returned within the context of a connection.

3 Using solidDB JDBC Driver 57


Differences with the standard API

Following are the differences from the standard Connection interface defined in the
JDBC API.
Table 16. Differences to the Standard Connection Interface

Method name Notes

getTypeMap() solidDB provides this method, but it always


returns null.

isReadOnly() solidDB only supports read-only connections


and read-only transactions if the database is
declared as read-only. This method always
returns false.

nativeSQL(String sql) Works as specified in Java API. solidDB


JDBC Driver does not change the SQL
passed to the solidDB server. The SQL query
the user passes is returned.

prepareCall(String sql) Works as specified in Java API.


Note: Note that the escape call syntax is not
supported.

setReadOnly(boolean readOnly) solidDB only supports read-only database


and read-only transactions if the database is
declared as read-only. This method exists
but does not affect the connection behavior.

setTransactionIsolation(int level) Works as specified in Java API.

setTypeMap(Map map) Not supported by solidDB.

DatabaseMetaData

The [Link] interface is a public abstract interface. It provides


general, comprehensive information about the database.

All methods for this interface are supported by solidDB.

For a description of how different data types are supported by solidDB JDBC
Driver, see “solidDB JDBC Driver type conversion matrix” on page 90.

Driver

The [Link] interface is a public abstract interface. Every driver class


implements this interface and all methods for this interface are supported by
solidDB.

PreparedStatement

The [Link] interface is a public abstract interface. It extends


the statement interface. It provides an object that represents a precompiled SQL
statement.

58 IBM solidDB: Programmer Guide


Note: The JDBC Driver allows for the creation of a PreparedStatement object that
generates ResultSet objects with the given type and concurrency. This differs from
the prepareStatement method in JDBC 1.0 because it allows the default result set
type and result set concurrency type to be overridden.

Subinterfaces: CallableStatement

Differences with the standard API

Following are the differences from the standard PreparedStatement interface


defined in the JDBC API.
Table 17. Differences to the Standard PreparedStatement Interface

Method name Notes

setArray(int i, Array x) Not supported by solidDB.

setBlob(int I, Blob x) Not supported by solidDB.

setClob(int I, Clob x) Not supported by solidDB.

setObject(int parameterIndex, Object x) Works as specified in Java API.


Note: The following objects are not
supported by solidDB: BLOB, CLOB,
ARRAY, REF, and object (USING
[Link]).

setObject(int parameterIndex, Object x, int Not supported by solidDB. This method


targetSqlType)) throws an exception with the following
message: "This method is not supported"

setObject(int parameterIndex, Object x, int Not supported by solidDB. This method


targetSQLType, int scale) throws an exception with the following
message: "This method is not supported"

setRef(int I, Ref x) Not supported by solidDB.

Ref

The [Link] interface is a public abstract interface.

This interface is a reference to an SQL structured type value in the database. This
interface is not supported by solidDB.

ResultSet

The [Link] interface is a table of data that represents a database result


set from a query statement. This object includes a cursor that points to its current
row of data. The cursor's initial position is before the first row. It is moved to the
next row by the next method. When there are no more rows left in the result set,
the method returns false; this allows the use of a WHILE loop to iterate through
the result set.

Differences with the standard API

3 Using solidDB JDBC Driver 59


Following are the differences from the standard ResultSet interface defined in the
JDBC API.
Table 18. Differences to the Standard ResultSet Interface

Method name Notes

getArray(int i) Not supported by solidDB.

getArray(String ColName) Not supported by solidDB.

getBigDecimal(String columnName) Works as specified in Java API.

getCharacterStream(int columnIndex) Works as specified in Java API.

NOTE: The JDBC Driver sets the designated


parameter to the given Reader object at the
given character length. When a large
UNICODE value is input to a LONG
VARCHAR/LONG WVARCHR parameter,
for convenience, you can send it via a
[Link]. The JDBC Driver reads the
data from the stream as needed, until it
reaches end-of-file. The driver does all the
necessary conversion from UNICODE to the
database CHAR format.

getCharacterStream(String columnName) Works as specified in Java API. The note


above also applies to this method.

getFetchSize() Not supported by solidDB.

getObject(int columnIndex) Works as specified in Java API.

NOTE: following objects are not supported


by solidDB: BLOB, CLOB, ARRAY, REF, and
object (USING [Link]).

getObject(int i, Map map) Not supported by solidDB.

getObject(String colName, Map map) Not supported by solidDB. This method


throws an exception with the following
message: "This method is not supported"

getRef(int i) Not supported by solidDB.

getRef(String colName) Not supported by solidDB.

refreshRow() Not supported by solidDB.

setFetchSize(int rows) No operation in solidDB. Sets the value for


the number of rows to be fetched from the
database each time. The value a user sets
with this method is ignored.

60 IBM solidDB: Programmer Guide


ResultSetMetaData

The [Link] interface is a public abstract interface. This


interface is used to find out about the types and properties of the columns in a
ResultSet.

SQLData

The [Link] interface is not supported. This interface is used to custom


map SQL user-defined types. It reflects the SQL-99 standard that is currently
unavailable in solidDB.

SQLInput
The [Link] interface is not supported. This interface is an input stream
that represents an instance of an SQL structured or distinct type. It reflects the
SQL-99 standard that is currently unavailable in solidDB.

SQLOutput

The [Link] interface is not supported. This interface is an output


stream used to write the attributes of a user-defined type back to the database. It
reflects the SQL-99 standard that is currently unavailable in solidDB.

Statement

The [Link] interface is a public abstract interface. It is the object used to


execute a static SQL statement and obtain the results of the execution.

Note: The JDBC Driver allows for the creation of a Statement object that generates
ResultSet objects with the given type and concurrency. This differs from the
CreateStatement method in JDBC 1.0 because it allows the default result set type
and result set concurrency type to be overridden.

Subinterfaces:
v CallableStatement
v PreparedStatement

Differences with the standard API

Following are the differences from the standard Statement interface defined in the
JDBC API.
Table 19. Differences to the Standard Statement Interface

Method name Notes

getFetchSize() No operation in solidDB.

getMaxFieldSize() Maxfield size does not affect the solidDB


server's behavior.

getMoreResults() solidDB does not support multiple result


sets.

3 Using solidDB JDBC Driver 61


Table 19. Differences to the Standard Statement Interface (continued)

Method name Notes

getResultSetType() Not supported by solidDB.

setFetchSize(int rows) No operation in solidDB. Sets the value for


the number of rows to be fetched from the
database each time. The value a user sets
with this method is ignored.

setMaxFieldSize(int max) Maxfield size does not affect the solidDB


server's behavior.

Struct

The [Link] interface is not supported. This interface represents the standard
mapping in the Java programming language for an SQL structured type. It reflects
the SQL-99 standard that is currently unavailable in solidDB.

ResultSet (updateable)

The [Link] interface contains methods for producing ResultSet objects


that are updateable. A result set is updateable if its concurrency type is
CONCUR_UPDATABLE. Rows in the result set may be updated, deleted, or new
rows inserted using methods update xxx, where xxx refers to the datatype and
methods updateRow and deleteRow.

Differences with the standard API

Following are the differences from the standard ResultSet interface defined in the
JDBC API.
Table 20. Differences to the Standard ResultSet Interface

Method name Notes

getRef(int i) This method is not supported.

getRef(String colName) This method is not supported.

refreshRow() This method is not supported.

rowDeleted() This method is not supported.

rowInserted() This method is not supported.

setFetchSize(int rows) This method is not supported.

solidDB JDBC Driver extensions


This section describes the non-standard extensions included in the solidDB JDBC
Driver.

62 IBM solidDB: Programmer Guide


WebSphere compatibility
The solidDB JDBC Driver includes features that improve WebSphere compatibility.

Java Transaction API (JTA) support

solidDB server can participate in distributed transactions using the Java


Transaction API (JTA) interface. The following interfaces are supported, as
described in the Java Transaction API Specification 1.1:
v XAResource Interface ([Link])
v Xid Interface ([Link])

When using JTA with SQL passthrough in solidDB Universal Cache, only read
statements (SELECT) are supported.

solidDB Data Store Helper Class in WebSphere

WebSphere needs an adapter class for those JDBC data sources that are to be used
within WebSphere. The base class for these adapters is the
[Link] class; solidDB implements
its own version of this adapter inside a class
called:[Link].

This class is provided within the solidDB product as a separate archive file called
[Link] You can find this file in the jdbc directory in the
solidDB installation directory.

When you are configuring a new solidDB data source in WebSphere, you need to
v give the [Link] in the data
store helper field of the configuration, and
v specify the full path to the [Link] file in the data source
configuration of WebSphere.
See the WebSphere documentation for further details how to define new data
sources in WebSphere.

For an example of how to install a solidDB's WebSphere sample application in the


Websphere Studio Application Developer's workspace, see the samples/websphere
directory in your solidDB installation directory.

solidDB Data Source Properties and WebSphere

You need to define the following properties when configuring a new data source in
the WebSphere:

URL
v type: [Link]
v value should use syntax similar to the following syntax: 'jdbc:solid://
<hostname>:<port>'

user
v type: [Link]
v value should be a valid user name

password

3 Using solidDB JDBC Driver 63


v type: [Link]
v value should be a valid password

Connection timeout in JDBC


This topic describes features available in solidDB to set a connection timeout.

Connection timeout means response timeout of any JDBC call invoking data
transmission over a connection socket. If the response message is not received
within the time specified, an I/O exception is thrown. The JDBC standard (2.0/3.0)
does not support setting of the connection timeout. solidDB has introduced two
ways for doing that: one using a non-standard driver manager extension method
and the other one using the property mechanisms. The time unit in either case is
one millisecond.

Driver Manager Method get/setConnectionTimeout()

The following example illustrates the solution. The effect of the setting is
immediate. This allows to set the timeout to zero if you want to force-disconnect.
//Import Solid JDBC:
import [Link].*;

//Define the connection:


[Link] conn = null;

//Cast to SolidConnection in order to use Solid-specific methods:


conn = (SolidConnection)[Link](sCon);

//Set connection timeout in milliseconds:


[Link](3000);

Non-standard connection properties


The following non-standard connection properties can be used to attain
connection-specific behavior when using the solidDB JDBC driver.
v “Statement cache property”
v “Timeout properties” on page 65
v “Appinfo property” on page 66
v “Transparent connectivity (TC) properties” on page 66
v “Socket linger connection properties” on page 67
v “Shared memory access (SMA) connection property” on page 67
v “SQL passthrough properties” on page 68
v “Catalog and schema name properties” on page 68
v “Setting connection properties with the URL string” on page 68

Statement cache property


StatementCache
Sets the size of the statement cache for the connection.
The default value is 8. The valid value range is 1 to 512 (inclusive). If the
value exceeds the range, the driver forces the value either to 1 or 512.

The following example shows how to set the statement cache size using the use
the StatementCache property.

64 IBM solidDB: Programmer Guide


// create a Solid JDBC driver instance
[Link]("[Link]");

// create a new Properties instance and insert a value for


// StatementCache property
[Link] props = new [Link]();
[Link]("StatementCache","32");

// define the connection string to be used


String sCon="jdbc:solid://localhost:1315/uname1/pwd1";

// get the Connection object with a statement cache of 32


[Link] conn = [Link](sCon, props);

Timeout properties
solid_connection_timeout_ms – Connection timeout
Sets the connection timeout value in milliseconds. The property must be
set before getting a new connection. Once a connection object is created,
changing the property value has no effect.
solid_login_timeout_ms – Login timeout
Sets the timeout in milliseconds for opening of a connection.

Note: You can use also the standard method


[Link](seconds) to set the login timeout.
solid_idle_timeout_min – Idle timeout
Sets the continuous idle time in minutes after which a connection is
dropped.
The default value is 480 minutes. 0 means 'infinite timeout' (never expires).
If the property value is not set, the server-side setting of the
[Link] parameter applies.

The following example shows how to set a connect timeout using the
solid_connection_timeout_ms property.
// Set connection timeout with "solid_connection_timeout_ms" property //
public class Test {

public static void main( String args[] ){

// create property object


Properties props = new Properties();

// put username and password in the properties


[Link]("user", "MYUSERNAME");
[Link]("password", "MYPASSWORD");

//
// Put connection timeout in the property object
//
[Link]("solid_connection_timeout_ms", "10000");

try {

// create driver
Driver d = (Driver)(
[Link]("[Link]").newInstance());

// get connection with url and property info


Connection c = [Link](
"jdbc:solid://localhost:1313", props );

3 Using solidDB JDBC Driver 65


// close connection
[Link]();

} catch ( Exception e ) {
; // save the day
}
}
}

Appinfo property
solid_appinfo
Sets unique identifiers for applications running in the same computer and
under the same username for the purposes of tracing and management.
By default, the value (a string) is not set.
The value can be retrieved on the server side with the command ADMIN
COMMAND ’userlist’.

Tip: In ODBC applications, the value equivalent to solid_appinfo is set


with the environmental variable SOLAPPINFO.

Transparent connectivity (TC) properties

Transparent connectivity (TC) is a connection mode that can be used with solidDB
High Availability configurations. The following connection properties are available
with TC.
solid_tf_level – Failure transparency level
Sets the transparent failover level for the connection.
Three levels are available:
v NONE | 0 – failure transparency is disabled. This is the default value.
v CONNECTION | 1 – the server connection is preserved, that is, it is
unnecessary to reconnect in the case of failover or switchover.
v SESSION | 3 – certain session attributes that have non-default values are
preserved. Additionally, prepared statements are preserved. However,
open cursors are closed, and ongoing transactions are aborted.

Note: The value is a string; you can specify it as a mnemonic (for example,
NONE) or as a number (0 for NONE). For clarity, use of mnemonics is
preferable.
solid_preferred_access – Load balancing mode
Sets the preferred access mode for the connection to define whether
read-only loads are distributed.
The following levels are available:
v WRITE_MOSTLY | 0 – the workload is directed to Primary. This is the
default value. WRITE_MOSTLY also sets the connection to the WRITE MOSTLY
mode. It is not possible to do that by specifying a numeric value.
v READ_MOSTLY | 1 – the workload is directed by default to Secondary. The
write transactions are handed over to the Primary.

Note: The value is a string; you can specify it as a mnemonic or as a


number. For clarity, use of mnemonics is preferable.

66 IBM solidDB: Programmer Guide


solid_tf1_reconnect_timeout – Reconnect timeout after transparent failover
Sets the timeout for how long the driver should wait until it tries to
reconnect to the primary in case of switchover or failover.
The unit is millisecond. The default value is 10000 (10 seconds).
solid_tf_wait_timeout – State switch wait timeout after transparent failover
Sets the timeout for how long the driver should wait for the server to
switch state. The unit is millisecond.
The default value is 10000 (10 seconds).

For more information about using the TC connection properties, see section Using
the Transparent Connectivity in the IBM solidDB High Availability User Guide.

Socket linger connection properties


solid_socket_linger
Controls the TCP socket linger behavior after a close on the socket
connection is issued. Possible values are 1 and 0 (default).
v 1 means that the system attempts to deliver any buffered data when a
[Link]() method on the socket connection is invoked.
v 0 means that the system discards any buffered data when a
[Link]() method on the socket connection is invoked.
The solid_socket_linger connection property does not have any effect on
the server-side setting defined with the [Link] parameter.
solid_socket_linger_time
Defines the length of the time interval (in seconds) the socket lingers after
a close is issued. If the time interval expires before the graceful shutdown
sequence completes, an abortive shutdown sequence occurs (the data is
discarded).
The default value is 10 (seconds).
The solid_socket_linger_time connection property does not have any effect
on the server-side setting defined with the [Link]
parameter.

Shared memory access (SMA) connection property


solid_shared_memory
Defines that the connection is a local (non RPC-based) JDBC connection to
a SMA server.
The only valid value is yes.
In addition, when using a SMA connection, the connect string must specify
a local server at a given port (localhost:<port_number>).

For example:
Properties props = new Properties();
// enable the direct access property
[Link]("solid_shared_memory", "yes");
// get connection
Connection c = [Link]
("jdbc:solid://localhost:1315", props);

For more details, see Making JDBC connections for SMA in the IBM solidDB Shared
Memory Access and Linked Library Access User Guide.

3 Using solidDB JDBC Driver 67


SQL passthrough properties

The SQL passthrough mode can be set with the following connection properties:
solid_passthrough_read
Sets the SQL passthrough mode for read-type statements to NONE,
CONDITIONAL, or FORCE.
solid_passthrough_write
Sets the SQL passthrough mode for write-type statements to NONE,
CONDITIONAL, or FORCE.

For more information about the SQL passthrough and the passthrough modes, see
section Setting SQL passthrough mode in the IBM solidDB Universal Cache User Guide.

Catalog and schema name properties

The catalog name and schema name can be set with the following connection
properties:
solid_catalog
Sets the solidDB catalog name.
solid_schema
Sets the solidDB schema name.

Setting connection properties with the URL string

Any connection property can also be set at connect time within the JDBC URL
passed to the JDBC method [Link](). The syntax of solidDB
JDBC URL is the following:
"jdbc:solid://<hostname>:<port>/>username>/<password>[?<property-name>=<value>]..."

Examples
"jdbc:solid://locahost:1964/dba/dba"
"jdbc:solid://[Link]/dba/dba?solid_login_timeout_ms=100"
"jdbc:solid://[Link]/dba/dba?solid_login_timeout_ms=100?solid_idle_timeout_min=5"

JDBC 2.0 optional package API support


The solidDB JDBC Driver 2.0 supports selected features of the JDBC 2.0
specification Optional Package (known before as Standard Extension).

JDBC connection pooling


The JDBC 2.0 Standard Extension API specifies that users can implement a pooling
technique by using specific caching or pooling algorithms that best suit their
needs. solidDBprovides classes that implement the standard
ConnectionPoolDataSource and PooledConnection interfaces.

solidDB implements these classes as follows:


v ConnectionPoolDataSource
A [Link] interface serves as a resource manager
connection factory for pooled [Link] objects. solidDB provides the
implementation for that interface in class SolidConnectionPoolDataSource. For
API functions, see “ConnectionPoolDataSource API Functions” on page 69.
v PooledConnection

68 IBM solidDB: Programmer Guide


A [Link] interface encapsulates the physical connection to a
database. solidDB provides the implementation for that interface in class
SolidPooledConnection. For API functions, see “PooledConnection API
Functions” on page 75.

Note: solidDB does not provide an implementation for the actual connection pool;
the data structure and the logic to actually pool the PooledConnection instances
are not available. You must implement your own connection pooling logic, that is,
a class that actually pools the connections.

ConnectionPoolDataSource API Functions

The public class SolidConnectionPoolDataSource implements


[Link]. The API functions for
[Link] interface are described as follows:
Table 21. Constructor

Description type Description

Function Name Constructor

Function Type solidDB proprietary API

Description Initializes class variables

Parameters None

Return value None

Syntax and exceptions public SolidConnectionPoolDataSource()

Table 22. Constructor

Description type Description

Function Name Constructor

Function Type solidDB proprietary API

Description Initializes class variables

Parameters url As String which identifies the DB server

Return value None

Syntax and exceptions public SolidConnectionPoolDataSource(String urlStr)

Table 23. setDescription

Description type Description

Function Name setDescription

3 Using solidDB JDBC Driver 69


Table 23. setDescription (continued)

Description type Description

Function Type solidDB proprietary API

Description This function sets the description string.

Parameters description string (descString)

Return value None

Syntax and exceptions public void setDescription(String descString)

Table 24. getDescription

Description type Description

Function Name getDescription

Function Type solidDB proprietary API

Description This function returns the description string.

Parameters None

Return value returns a String (description)

Syntax and exceptions public String getDescription()

Table 25. setURL

Description type Description

Function Name setURL

Function Type solidDB proprietary API

Description This function sets the url string which points to an solidDB
server.

Parameters url string (urlStr)

Return value None

Syntax and exceptions public void setURL(String urlStr)

Table 26. getURL

Description type Description

Function Name getURL

70 IBM solidDB: Programmer Guide


Table 26. getURL (continued)

Description type Description

Function Type solidDB proprietary API

Description This function returns the DB url string.

Parameters None

Return value returns a String (url)

Syntax and exceptions public String getURL()

Table 27. setUser

Description type Description

Function Name setUser

Function Type solidDB proprietary API

Description This function sets the username string. (WebSphere


compatibility)

Parameters username string

Return value None

Syntax and exceptions public void setUser(String newUser)

Table 28. getUser

Description type Description

Function Name getUser

Function Type solidDB proprietary API

Description This function returns the username string. (WebSphere


compatibility)

Parameters None

Return value returns a String (username)

Syntax and exceptions public String getUser()

3 Using solidDB JDBC Driver 71


Table 29. setPassword

Description type Description

Function Name setPassword

Function Type solidDB proprietary API

Description This function sets the password string. (WebSphere


compatibility)

Parameters password string

Return value None

Syntax and exceptions public void setPassword(String newPassword)

Table 30. getPassword

Description type Description

Function Name getPassword

Function Type solidDB proprietary API

Description This function returns the password string. (WebSphere


compatibility)

Parameters None

Return value returns a String (password)

Syntax and exceptions public String getPassword()

Table 31. setConnectionURL

Description type Description

Function Name setConnectionURL

Function Type solidDB proprietary API

Description This function sets the url string which points to an solidDB
server.

Parameters url string

Return value None

Syntax and exceptions public void setConnectionURL(String newUrl)

72 IBM solidDB: Programmer Guide


Table 32. getConnectionURL

Description type Description

Function Name getConnectionURL

Function Type solidDB proprietary API

Description This function returns the url string.

Parameters None

Return value returns a String (url)

Syntax and exceptions public String getConnectionURL()

Table 33. getLoginTimeout

Description type Description

Function Name getLoginTimeout

Function Type [Link] API

Description This function returns the login timeout value.

Parameters None

Return value returns a timeout value as an integer (seconds)

Syntax and exceptions public int getLoginTimeout() throws [Link]

Table 34. getLogWriter

Description type Description

Function Name getLogWriter

Function Type [Link] API

Description This function returns the handle to a writer used for


printing debugging messages.

Parameters None

Return value returns a handle to [Link]

Syntax and exceptions public [Link] getLogWriter() throws


[Link]

3 Using solidDB JDBC Driver 73


Table 35. getPooledConnection

Description type Description

Function Name getPooledConnection

Function Type [Link] API

Description This function returns a PooledConnection object from the


connection pool. This object has a valid connection to the
database server.

Parameters None

Return value returns a PooledConnection object.

Syntax and exceptions public [Link] getPooledConnection()

throws [Link]

Table 36. getPooledConnection

Description type Description

Function Name getPooledConnection

Function Type [Link] API

Description This function returns a PooledConnection object from the


connection pool. This object has a valid connection to the
database server.

Parameters user (username as String), password (password as String)

Return value returns a PooledConnection object.

Syntax and exceptions public [Link]


getPooledConnection(String user, String password )

throws [Link]

Table 37. setLoginTimeout

Description type Description

Function Name setLoginTimeout

Function Type [Link] API

Description This function sets the login timeout value in seconds

Parameters seconds ( as integer )

Return value None

74 IBM solidDB: Programmer Guide


Table 37. setLoginTimeout (continued)

Description type Description

Syntax and exceptions public void setLoginTimeout(int seconds)

Table 38. setLogWriter

Description type Description

Function Name setLogWriter

Function Type [Link] API

Description This function sets the handle to a writer object that will be
used to print/log debug messages.

Parameters handle to [Link]

Return value None

Syntax and exceptions public void setLogWriter([Link] out)

throws [Link]

PooledConnection API Functions

The public class SolidPooledConnection implements [Link].


The API functions for [Link] interface are:
Table 39. addConnectionEventListener

Description type Description

Function Name addConnectionEventListener

Function Type [Link] API

Description Adds an event listener to whom this object should notify


when it wants to release the connection. This listener is
generally the connection pooling module.

Parameters listener (handle to [Link])

Return value None

Syntax and exceptions public void addConnectionEventListener(

[Link] listener)

3 Using solidDB JDBC Driver 75


Table 40. close

Description type Description

Function Name close

Function Type [Link] API

Description This function closes the physical connection.

Parameters None

Return value None

Syntax and exceptions public void close()

throws [Link]

Table 41. getConnection

Description type Description

Function Name getConnection

Function Type [Link] API

Description returns a handle to [Link]

Parameters None

Return value [Link]

Syntax and exceptions public [Link] getConnection()

throws [Link]

Table 42. removeConnectionEventListener

Description type Description

Function Name removeConnectionEventListener

Function Type [Link] API

Description This function removes the reference to the listener

Parameters listener

Return value None

Syntax and exceptions public void removeConnectionEventListener(

[Link] listener)

76 IBM solidDB: Programmer Guide


solidDB Connected RowSet Class: SolidJDBCRowSet
The RowSet described in this topic, extends [Link] (which
implements [Link]) constructors.
/**
* Create a SolidJDBCRowSet with an existing Connection handle */
public SolidJDBCRowSet([Link] conn)

/**
* Create a SolidJDBCRowSet with an existing ResultSet handle */
public SolidJDBCRowSet([Link] rset)

/**
* Create a new SolidJDBCRowSet with given url, username and
* password.
*/
public SolidJDBCRowSet(String url, String uname, String pwd)

/**
* Create a new SolidJDBCRowSet with given url, username,
* password and JNDI naming context.
*/
public SolidJDBCRowSet(String dsname,
String username,
String password,
Context namingcontext)

For examples, see the method interface description in the Java 2 Platform, Standard
Edition, v 1.4.2 API Specification: [Link]
sql/[Link]

Considerations about the usage of SolidJDBCRowSet

There are certain methods that you can call (usually for setting parameters for
commands to be executed or setting the properties of the RowSet instance) before a
connection to the database has been made. However, most of the RowSet interface
methods can be called only after a connection to the database has been made. This
means that method a command has been set with method setCommand(String)
and method execute() has been called. If the SolidJDBCRowSet instance has no
previous [Link] handle, the connection will be established during
execute() call. After the execute() call, the row set instance contains a
[Link] object, a [Link] object, and if the command
execute was a query statement, it contains also a [Link] handle. It also
contains all parameter setting methods: setString, setObject, and so on.

The following example describes the proper use of SolidJDBCRowSet class.


/**
* A simple example on how to use SolidJDBCRowSet
* First: create an instance of a connected RowSet class.
* You can give the url, username and password
* right away in the constructor below, but null parameters
* for the corresponding values have bee given in the example
* just to show how to use setUrl, setUsername (and so on) methods of the
* RowSet class.
*/
SolidJDBCRowSet rs = new SolidJDBCRowSet(null, null, null);

// Set the url for the connection


[Link]("jdbc:solid://localhost:1313");

// set the username


[Link]("user1");

3 Using solidDB JDBC Driver 77


// set the passwd
[Link]("pwd1");

/**
* Note! You can set command parameters and other properties
* in any order you like, for example, you can set the parameters
* before you have defined the command to be executed. You can
* also define the command parameters in any order, since the
* command statement as well as the given parameters will not be
* parsed until a connection to the database has been made in
* the execute() method call.
*/

// set parameter #2 for the command


[Link](2,"’SYS_SYNC%’");

// set the command string


[Link]("select table_name from tables where table_name like ?
and table_name not like ?;");

// set the parameter #1


[Link](1,"’SYS_%’");

// execute the command. The connection to the database is not


// established before this call.
[Link]();

// now you can browse the ResultSet


while( [Link]() ){
// do stuff
}

// close the result set. This method call closes the connection
// to the database as well.
[Link]()

Java Naming and Directory Interface (JNDI)


The solidDB JDBC Driver supports the Java Naming and Directory Interface
(JNDI).

JNDI allows applications to access naming and directory services through a


common interface. JNDI is not a service, but a set of interfaces. These interfaces
allow applications to access many different directory services including: file
systems, directory services such as Lightweight Directory Access Protocol (LDAP),
Network Information System (NIS), and distributed object systems such as the
Common Object Request Broker Architecture (CORBA), Java Remote Method
Invocation (RMI), and Enterprise JavaBeans (EJB).

Code examples
This topic contains four Java code samples that use the solidDB JDBC driver.

Java Code Example 1: [Link]


/**
* sample1 JDBC sample application
*
*
* This simple JDBC application does the following using
* Solid JDBC driver.
*

78 IBM solidDB: Programmer Guide


* 1. Registers the driver using JDBC driver manager services
* 2. Prompts the user for a valid JDBC connect string
* 3. Connects to Solid using the driver
* 4. Creates a statement for one query,
* ’SELECT TABLE_SCHEMA,TABLE_NAME,TABLE_TYPE FROM TABLES’
* for reading data from one of the Solid system tables.
* 5. Executes the query
* 6. Fetches and dumps all the rows of a result set.
* 7. Closes connection
*
* To build and run the application
*
* 1. Make sure you have a working Java Development environment
* 2. Install and start Solid to connect. Ensure that the
* server is up and running.
* 3. Append [Link] into the CLASSPATH definition used
* by your development/running environment.
* 4. Create a java project based on the file [Link].
* 5. Build and run the application.
*
* For more information read the [Link] file contained in the
* solidDB package.
*
*/

import [Link].*;

public class sample1 {

public static void main (String args[]) throws Exception


{
[Link] conn;
[Link] meta;
[Link] stmt;
[Link] result;
int i;

[Link]("JDBC sample application starts...");


[Link]("Application tries to register the driver.");

// this is the recommended way for registering Drivers


[Link] d =
([Link])[Link]("[Link]").newInstance();

[Link]("Driver succesfully registered.");

// the user is asked for a connect string


[Link](
"Now sample application needs a connectstring in format:\n"
);
[Link](
"jdbc:solid://<host>:<port>/<user name>/<password>\n"
);
[Link]("\nEnter the connect string >");
BufferedReader reader =
new BufferedReader(new InputStreamReader([Link]));
String sCon = [Link]();

// next, the connection is attempted


[Link]("Attempting to connect :" + sCon);
conn = [Link](sCon);

[Link]("SolidDriver succesfully connected.");

String sQuery = "SELECT TABLE_SCHEMA,TABLE_NAME,TABLE_TYPE FROM TABLES";

stmt= [Link]();

3 Using solidDB JDBC Driver 79


result = [Link](sQuery);
[Link]("Query executed and result set obtained.");

// we get a metadataobject containing information about the


// obtained result set
[Link]("Obtaining metadata information.");
meta = [Link]();
int cols = [Link]();

[Link]("Metadata information for columns is as follows:");


// we dump the column information about the result set
for (i=1; i <= cols; i++)
{
[Link]("Column i:"+i+" "+[Link](i)+ "," +
[Link](i) + "," + [Link](i));
}

// and finally, we dump the result set


[Link]("Starting to dump result set.");
int cnt = 1;
while([Link]())
{
[Link]("\nRow "+cnt+" : ");
for (i=1; i <= cols; i++) {
[Link]([Link](i)+"\t");
}
cnt++;
}

[Link]();

[Link]();
// and not it is all over
[Link]("\nResult set dumped. Sample application finishes.");
}
}

Java Code Example 1 Output


Solid\DatabaseEngine4.1\jdbc\samples>java [Link]
JDBC sample application starts...
Application tries to register the driver.
Driver succesfully registered.
Now sample application needs a connectstring in format:

jdbc:solid://<host>:<port>/<user name>/<password>

Enter the connect string >jdbc:solid://localhost:1313/dba/dba


Attempting to connect :jdbc:solid://localhost:1313/dba/dba
SolidDriver succesfully connected.
Query executed and result set obtained.
Obtaining metadata information.
Metadata information for columns is as follows:
Column i:1 TABLE_SCHEMA,12,VARCHAR
Column i:2 TABLE_NAME,12,VARCHAR
Column i:3 TABLE_TYPE,12,VARCHAR
Starting to dump result set.

Row 1 : _SYSTEM SYS_TABLES BASE TABLE


Row 2 : _SYSTEM SYS_COLUMNS BASE TABLE
Row 3 : _SYSTEM SYS_USERS BASE TABLE
Row 4 : _SYSTEM SYS_UROLE BASE TABLE
Row 5 : _SYSTEM SYS_RELAUTH BASE TABLE
Row 6 : _SYSTEM SYS_ATTAUTH BASE TABLE
Row 7 : _SYSTEM SYS_VIEWS BASE TABLE
Row 8 : _SYSTEM SYS_KEYPARTS BASE TABLE

80 IBM solidDB: Programmer Guide


Row 9 : _SYSTEM SYS_KEYS BASE TABLE
Row 10 : _SYSTEM SYS_CARDINAL BASE TABLE
Row 11 : _SYSTEM SYS_INFO BASE TABLE
Row 12 : _SYSTEM SYS_SYNONYM BASE TABLE
Row 13 : _SYSTEM TABLES VIEW
Row 14 : _SYSTEM COLUMNS VIEW
Row 15 : _SYSTEM SQL_LANGUAGES BASE TABLE
Row 16 : _SYSTEM SERVER_INFO VIEW
Row 17 : _SYSTEM SYS_TYPES BASE TABLE
Row 18 : _SYSTEM SYS_FORKEYS BASE TABLE
Row 19 : _SYSTEM SYS_FORKEYPARTS BASE TABLE
Row 20 : _SYSTEM SYS_PROCEDURES BASE TABLE
Row 21 : _SYSTEM SYS_TABLEMODES BASE TABLE
Row 22 : _SYSTEM SYS_EVENTS BASE TABLE
Row 23 : _SYSTEM SYS_SEQUENCES BASE TABLE
Row 24 : _SYSTEM SYS_TMP_HOTSTANDBY BASE TABLE
Result set dumped. Sample application finishes.

Java Code Example 2: [Link]


/**
* sample2 JDBC sample applet
*
*
* This simple JDBC applet does the following using
* Solid native JDBC driver.
*
* 1. Registers the driver using JDBC driver manager services
* 2. Connects to Solid using the driver.
* Used url is read from [Link]
* 3. Executes given SQL statements
*
* To build and run the application
*
* 1. Make sure you have a working Java Development environment
* 2. Install and start Solid to connect. Ensure that
* the server is up and running.
* 3. Append [Link] into the CLASSPATH definition used
* by your development/running environment.
* 4. Create a java project based on the file [Link].
* 5. Build and run the application. Check that [Link]
* defines valid url to your environment.
*
* For more information read the [Link] file contained
* in the IBM SolidDB Development Kit package.
*
*/

import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link].*;

public class sample2 extends Applet {


TextField textField;
static TextArea textArea;

String url = null;


Connection con = null;

public void init() {


// a valid value for url could be
// url = "jdbc:solid://localhost:1313/dba/dba";

url = getParameter("url");

3 Using solidDB JDBC Driver 81


textField = new TextField(40);
textArea = new TextArea(10, 40);
[Link](false);

Font font = [Link]();


Font newfont = new Font("Monospaced", [Link], 12);
[Link](newfont);

// Add Components to the Applet.


GridBagLayout gridBag = new GridBagLayout();
setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
[Link] = [Link];

[Link] = [Link];
[Link](textField, c);
add(textField);

[Link] = [Link];
[Link] = 1.0;
[Link] = 1.0;
[Link](textArea, c);
add(textArea);

validate();

try {
// Load the Solid JDBC Driver
Driver d =
(Driver)[Link] ("[Link]").newInstance();

// Attempt to connect to a driver.


con = [Link] (url);

// If we were unable to connect, an exception


// would have been thrown. So, if we get here,
// we are successfully connected to the url

// Check for, and display and warnings generated


// by the connect.
checkForWarning ([Link] ());

// Get the DatabaseMetaData object and display


// some information about the connection
DatabaseMetaData dma = [Link] ();

[Link]("Connected to " + [Link]() + "\n");


[Link]("Driver " + [Link]() + "\n");
[Link]("Version " + [Link]() + "\n");
}
catch (SQLException ex) {
printSQLException(ex);
}
catch (Exception e) {
[Link]("Exception: " + e + "\n");
}
}

public void destroy() {


if (con != null) {
try {
[Link]();
}
catch (SQLException ex) {
printSQLException(ex);
}
catch (Exception e) {

82 IBM solidDB: Programmer Guide


[Link]("Exception: " + e + "\n");
}
}
}

public boolean action(Event evt, Object arg) {


if (con != null) {
String sqlstmt = [Link]();
[Link]("");
try {
// Create a Statement object so we can submit
// SQL statements to the driver
Statement stmt = [Link] ();
// set row limit
[Link](50);
// Submit a query, creating a ResultSet object
ResultSet rs = [Link] (sqlstmt);

// Display all columns and rows from the result set


[Link](false);
dispResultSet (stmt,rs);
[Link](true);

// Close the result set


[Link]();

// Close the statement


[Link]();
}
catch (SQLException ex) {
printSQLException(ex);
}
catch (Exception e) {
[Link]("Exception: " + e + "\n");
}
[Link]();
}
return true;
}

//------------------------------------------------------------------
// checkForWarning
// Checks for and displays warnings. Returns true if a warning
// existed
//------------------------------------------------------------------

private static boolean checkForWarning (SQLWarning warn)


throws SQLException
{
boolean rc = false;

// If a SQLWarning object was given, display the


// warning messages. Note that there could be
// multiple warnings chained together

if (warn != null) {
[Link]("\n*** Warning ***\n");
rc = true;
while (warn != null) {
[Link]("SQLState: " +
[Link] () + "\n");
[Link]("Message: " +
[Link] () + "\n");
[Link]("Vendor: " +
[Link] () + "\n");
[Link]("\n");
warn = [Link] ();

3 Using solidDB JDBC Driver 83


}
}
return rc;
}

//------------------------------------------------------------------
// dispResultSet
// Displays all columns and rows in the given result set
//------------------------------------------------------------------

private static void dispResultSet (Statement sta, ResultSet rs)


throws SQLException
{
int i;

// Get the ResultSetMetaData. This will be used for


// the column headings
ResultSetMetaData rsmd = [Link] ();

// Get the number of columns in the result set


int numCols = [Link] ();
if (numCols == 0) {
[Link]("Updatecount is "+[Link]());
return;
}

// Display column headings


for (i=1; i<=numCols; i++) {
if (i > 1) {
[Link]("\t");
}
try {
[Link]([Link](i));
}
catch(NullPointerException ex) {
[Link]("null");
}
}
[Link]("\n");

// Display data, fetching until end of the result set


boolean more = [Link] ();
while (more) {

// Loop through each column, get the


// column datza and display it
for (i=1; i<=numCols; i++) {
if (i > 1) {
[Link]("\t");
}
try {
[Link]([Link](i));
}
catch(NullPointerException ex) {
[Link]("null");
}
}
[Link]("\n");

// Fetch the next result set row


more = [Link] ();
}
}

private static void printSQLException(SQLException ex)


{
// A SQLException was generated. Catch it and

84 IBM solidDB: Programmer Guide


// display the error information. Note that there
// could be multiple error objects chained
// together

[Link]("\n*** SQLException caught ***\n");

while (ex != null) {


[Link]("SQLState: " +
[Link] () + "\n");
[Link]("Message: " +
[Link] () + "\n");
[Link]("Vendor: " +
[Link] () + "\n");
[Link]("\n");
ex = [Link] ();
}
}
}

Java Code Example 3: [Link]


/**
* sample3 JDBC sample application
*
*
* This simple JDBC application does the following using
* Solid JDBC driver.
*
* 1. Registers the driver using JDBC driver manager services
* 2. Prompts the user for a valid JDBC connect string
* 3. Connects to Solid using the driver
* 4. Drops and creates a procedure sample3. If the procedure
* does not exist dumps the related exception.
* 5. Calls that procedure using [Link]
* 6. Fetches and dumps all the rows of a result set.
* 7. Closes connection
*
* To build and run the application
*
* 1. Make sure you have a working Java Development environment
* 2. Install and start Solid to connect. Ensure that the
* server is up and running.
* 3. Append [Link] into the CLASSPATH definition used
* by your development/running environment.
* 4. Create a java project based on the file [Link].
* 5. Build and run the application.
*
* For more information read the [Link]
* file contained in the solidDB Development Kit package.
*/

import [Link].*;
import [Link].*;

public class sample3 {

static Connection conn;


public static void main (String args[]) throws Exception
{
[Link]("JDBC sample application starts...");
[Link]("Application tries to register the driver.");

// this is the recommended way for registering Drivers


Driver d = (Driver)[Link]("[Link]").newInstance();

[Link]("Driver succesfully registered.");

3 Using solidDB JDBC Driver 85


// the user is asked for a connect string
[Link](
"Now sample application needs a connectstring in format:\n"
);
[Link](
"jdbc:solid://<host>:<port>/<user name>/<password>\n"
);
[Link]("\nEnter the connect string >");
BufferedReader reader =
new BufferedReader(new InputStreamReader([Link]));
String sCon = [Link]();

// next, the connection is attempted


[Link]("Attempting to connect :" + sCon);
conn = [Link](sCon);

[Link]("SolidDriver succesfully connected.");

DoIt();

[Link]();
// and now it is all over
[Link](
"\nResult set dumped. Sample application finishes."
);
}

static void DoIt() {


try {
createprocs();
PreparedStatement pstmt = [Link]("call sample3(?)");
// set parameter value
[Link](1,10);

ResultSet rs = [Link]();
if (rs != null) {
ResultSetMetaData md = [Link]();
int cols = [Link]();
int row = 0;
while ([Link]()) {
row++;
String ret = "row "+row+": ";
for (int i=1;i<=cols;i++) {
ret = ret + [Link](i) + " ";
}
[Link](ret);
}
}
[Link]();
}
catch (SQLException ex) {
printexp(ex);
}
catch ([Link] ex) {
[Link] ();
}

static void createprocs() {


Statement stmt = null;
String proc = "create procedure sample3 (limit integer)" +
"returns (c1 integer, c2 integer) " +
"begin " +
" c1 := 0;" +
" while c1 < limit loop " +

86 IBM solidDB: Programmer Guide


" c2 := 5 * c1;" +
" return row;" +
" c1 := c1 + 1;" +
" end loop;" +
"end";

try {
stmt = [Link]();
[Link]("drop procedure sample3");
} catch (SQLException ex) {
printexp(ex);
}

try {
[Link](proc);
} catch (SQLException ex) {
printexp(ex);
[Link](-1);
}
}

public static void printexp(SQLException ex) {


[Link]("\n*** SQLException caught ***");
while (ex != null) {
[Link]("SQLState: " + [Link]());
[Link]("Message: " + [Link]());
[Link]("Vendor: " + [Link]());
ex = [Link] ();
}
}

Java Code Example 4: [Link]


/**
* sample4 JDBC sample application
*
*
* This simple JDBC application does the following using
* Solid JDBC driver.
*
* 1. Registers the driver using JDBC driver manager services
* 2. Prompts the user for a valid JDBC connect string
* 3. Connects to Solid using the driver
* 4. Drops and creates a table sample4. If the table
* does not exist dumps the related exception.
* 5. Inserts file given as an argument to database (method Store)
* 6. Reads this ’blob’ back to file [Link] (method Restore)
* 7. Closes connection
*
* To build and run the application
*
* 1. Make sure you have a working Java Development environment
* 2. Install and start Solid to connect. Ensure that
* the server is up and running.
* 3. Append [Link] into the CLASSPATH definition used
* by your development/running environment.
* 4. Create a java project based on the file [Link].
* 5. Build and run the application.
*
* For more information read the [Link] file
* contained in the solidDB Development Kit package.
*
*/

import [Link].*;

3 Using solidDB JDBC Driver 87


import [Link].*;

public class sample4 {

static Connection conn;


public static void main (String args[]) throws Exception
{
String filename = null;
String tmpfilename = null;

if ([Link] < 1) {
[Link]("usage: java sample4 <infile>");
[Link](0);
}
filename = args[0];
tmpfilename = "[Link]";
[Link]("JDBC sample application starts...");
[Link]("Application tries to register the driver.");

// this is the recommended way for registering Drivers


Driver d = (Driver)[Link]("[Link]").newInstance();

[Link]("Driver succesfully registered.");

// the user is asked for a connect string


[Link](
"Now sample application needs a connectstring in format:\n"
);
[Link](
"jdbc:solid://<host>:<port>/<user name>/<password>\n"
);
[Link]("\nEnter the connect string >");
BufferedReader reader =
new BufferedReader(new InputStreamReader([Link]));
String sCon = [Link]();

// next, the connection is attempted


[Link]("Attempting to connect :" + sCon);
conn = [Link](sCon);

[Link]("SolidDriver succesfully connected.");

// drop and create table sample4


createsample4();
// insert data into it
Store(filename);
// and restore it
Restore(tmpfilename);

[Link]();
// and it is all over
[Link]("\nSample application finishes.");
}

static void Store(String filename) {


String sql = "insert into sample4 values(?,?)";
FileInputStream inFileStream ;
try {
File f1 = new File(filename);
int blobsize = (int)[Link]();
[Link]("Inputfile size is "+blobsize);
inFileStream = new FileInputStream(f1);

PreparedStatement stmt = [Link](sql);


[Link](1, [Link]());
[Link](2, inFileStream, blobsize);

88 IBM solidDB: Programmer Guide


int rows = [Link]();
[Link]();
[Link](""+rows+" inserted.");
[Link]();
}
catch (SQLException ex) {
printexp(ex);
}
catch ([Link] ex) {
[Link] ();
}

static void Restore(String filename) {


String sql = "select id,blob from sample4";
FileOutputStream outFileStream ;
try {
File f1 = new File(filename);
outFileStream = new FileOutputStream(f1);

PreparedStatement stmt = [Link](sql);


ResultSet rs = [Link]();
int readsize = 0;
while ([Link]()) {
InputStream in = [Link](2);
byte bytes[] = new byte[8*1024];
int nRead = [Link](bytes);
while (nRead != -1) {
readsize = readsize + nRead;
[Link](bytes,0,nRead);
nRead = [Link](bytes);
}

}
[Link]();
[Link]("Read "+readsize+" bytes from database");
}
catch (SQLException ex) {
printexp(ex);
}
catch ([Link] ex) {
[Link] ();
}

static void createsample4() {


Statement stmt = null;
String proc = "create table sample4 (" +
"id numeric not null primary key,"+
"blob long varbinary)";

try {
stmt = [Link]();
[Link]("drop table sample4");
} catch (SQLException ex) {
printexp(ex);
}

try {
[Link](proc);
} catch (SQLException ex) {
printexp(ex);
[Link](-1);
}

3 Using solidDB JDBC Driver 89


}

static void printexp(SQLException ex) {


[Link]("\n*** SQLException caught ***");
while (ex != null) {
[Link]("SQLState: " + [Link]());
[Link]("Message: " + [Link]());
[Link]("Vendor: " + [Link]());
ex = [Link] ();
}
}

solidDB JDBC Driver type conversion matrix


The conversion matrix included in this topic shows how the Java data type to SQL
data type conversion is supported by solidDB JDBC Driver.

This matrix applies to both [Link] and [Link] methods for


getting and setting data. An X indicates that the method is supported by solidDB
JDBC Driver.
Table 43. Java data type to SQL data type conversion
L
L O
L O N
O N V G
N G A V T
S G W W R A I
T M I D N V V V V B R M
I A N D E U A A A A B I B E
N L T F O C M R R W R R I N I S
Y L E R L U I E C C C C C C N A N D T T
Java Data Type I I G E O B M R H H H H H H A R A A I A
N N E A A L A I A A A A A A R Y R T M M
applies to getting and setting data T T R L T E L C R R R R R R Y R Y E E P

getArray/setArray

getBlob/setBlob

getByte/setByte X X X X X X X X X X X X X X

getCharacterStream/ setCharacterStream X X X X X X X X X X X X

getClob/setClob

getShort/setShort X X X X X X X X X X X

getInt/setInt X X X X X X X X X X X

getlong/setLong X X X X X X X X X X X

getfloat/setfloat X X X X X X X X X X X

getDouble/setDouble X X X X X X X X X X X

getBigDecimal/setBigDecimal X X X X X X X X X X X

getRef/setRef

90 IBM solidDB: Programmer Guide


Table 43. Java data type to SQL data type conversion (continued)
L
L O
L O N
O N V G
N G A V T
S G W W R A I
T M I D N V V V V B R M
I A N D E U A A A A B I B E
N L T F O C M R R W R R I N I S
Y L E R L U I E C C C C C C N A N D T T
Java Data Type I I G E O B M R H H H H H H A R A A I A
N N E A A L A I A A A A A A R Y R T M M
applies to getting and setting data T T R L T E L C R R R R R R Y R Y E E P

getBoolean/setBoolean X X X X X X X X X X X

getString/setString X X X X X X X X X X X X X X X X X X X X

getBytes/setBytes X X X X X X X X X

getDate/setDate X X X X X X X X

getTime/setTime X X X X X X X X

getTimestamp/setTimestamp X X X X X X X X

getAsciiStream/setAsciiStream X X X X X X X X X

getUnicodeStream/setUnicodeStream X X X X X X X X X

getBinaryStream/setBinaryStream X X X X X X X X X

getObject/setObject X X X X X X X X X X X X X X X X X X X X

3 Using solidDB JDBC Driver 91


92 IBM solidDB: Programmer Guide
4 Using solidDB SA
This section describes how to use the solidDB Application Programming Interface
(API) also known as solidDB SA

solidDB SA is a low level C-language client library to access solidDB database


management products. solidDB SA is a layer that resides internally in solidDB
products. Normally, the use of an industry standards based interface, such as
ODBC or JDBC, is recommended. However, in environments with heavy write load
(BATCH INSERTS AND UPDATES), solidDB SA can provide a significant
performance advantage.

What is solidDB SA?


solidDB SA is a C-language client library to connect solidDB database products.
This library is used internally in solidDB products and provides access to data in
solidDB database tables. The library contains 90 functions providing low-level
mechanisms for connecting the database and running cursor-based operations.

Compared to industry standard interfaces, such as ODBC or JDBC, solidDB SA


offers better flexibility in constructing network messages that are sent to the
database server. In applications whose read or write performance (for example,
batch inserts or primary key lookups) needs to be optimized, using solidDB SA can
provide a significant performance advantage. For example, if your site experiences
performance bottlenecks during batch inserts, solidDB SA can reduce the
bottleneck because solidDB SA lets you pass several rows for insertion inside a
single network message or remote procedure call.

Note: If the performance bottleneck is in read operations, using solidDB SA will


provide only minor improvement in performance.

The solidDB SA interface bypasses the SQL parser, interpreter, and optimizer. With
solidDB SA you can access result sets, as long as you are not using SQL through
solidDB SA. If retrieval of result sets is necessary through SQL, then you must use
industry standard APIs such as ODBC or the solidDB Light Client based on ODBC.

To use solidDB SA requires that you convert your existing interface. This is why
we recommend that you use solidDB SA only after you have already attempted
(with little success) to use other means for improving performance, which include:
v Writing or indexing columns by primary key for the most appropriate row order.
solidDB, otherwise, stores rows on disk in the order they are inserted into the
database.
v Eliminating unnecessary indexes. For example, a query that selects more than
15% of a table's rows may be performed faster by a full table scan.
v Optimizing the transaction size by committing transactions after every 100-200
rows inserted.
v Using stored procedures.

93
Getting started with solidDB SA
The solidDB SA can be used with shared memory access (SMA) and linked library
access (LLA). This topic describes the steps that you should take before using
solidDB SA.

Before getting started with solidDB SA, be sure you have:


1. If you are building a local application, you need the SMA or LLA library file.
The SMA and LLA library files are installed during solidDB installation. The
libraries include the solidDB SA functions as well as full server functionality.
2. If you are building a remote user application, you need the solidDB SA library
so that you can link it into your application, for example [Link] for
Windows operating systems.
3. Started solidDB. If necessary, create a new database before using solidDB SA.

Setting up the development environment and building a sample


program

Building an application program using the solidDB SA library in the linked library
access or the SA client library is identical to building any normal C/C++ program:
1. Insert the linked library access library file or SA client library into your project.
Refer to section Creating and running LLA applications in the IBM solidDB Shared
Memory Access and Linked Library Access User Guide for the correct filenames.
2. Include the following solidDB SA header file, which is required in applications
using solidDB SA library in the linked library access or the solidDB SA client
library:
#include "sa.h"
Insert the directory containing all the other necessary solidDB SA headers into
your development environment's include directories setting.
3. Compile the source code.
4. Link the program.

Verifying the development environment setup

You can verify the development setup with the solidDB SA sample program. This
enables you to verify your development environment without writing any code.

Verify the following in your development environment:


v In the Windows environment, the TCP/IP services are provided by standard
DLL [Link]. To link these services into your project, add [Link] into
linker's lib file list.

Connecting to a database by using the sample application

In solidDB SA, a connection to a database is represented by the SaConnectT


structure. This structure is established by calling the function SaConnect. The
following sample code establishes a connection to a database listening TCP/IP
protocol at local machine port 1313. User account DBA with password DBA has
been defined in the database.
SaConnectT* scon;

scon = SaConnect("tcp localhost 1313", "dba", "dba");


if (scon == NULL)
{

94 IBM solidDB: Programmer Guide


/* Connect failed, display connect error text. */
char* errstr;
SaErrorInfo(NULL, &errstr, NULL);
printf("%s\n", errstr);
return(1);
}

Writing data by using solidDB SA without SQL


With solidDB SA, data is written using cursors.

For delete and update operations, after the cursor is created, a search is performed
so that the cursor points to the row that is to be updated and deleted. For insert
operations, after the cursor is created, the insertion row(s) are immediately written
to the cursor. solidDB SA also enables passing several rows for insertion inside a
single network message.

Performing insert operations

solidDB SA functions required for insert operations are listed in the table below.

After solidDB creates a cursor to a certain table, variables are bound to columns,
rows are written to the cursor, and then the cursor is closed.

Note: If you use SaArrayInsert to insert more than one row in a single message,
then you must perform an explicit flush to send the rows to the database.
Table 44. Insert operation steps

Steps SA Function(s) Comment

1. Create a cursor SaCursorCreate

2. Binding variables SaCursorColData, SaCursorColDate,


to cursor SaCursorColDateFormat,
SaCursorColDFloat, SaCursorColDouble,
SaCursorColDynData, SaCursorColDynstr,
SaCursorColFloat, SaCursorColInt,
SaCursorColLong, SaCursorColStr,
SaCursorColTime, SaCursorColTimestamp

3. Open the cursor SaCursorOpen

4. Write a row(s) to SaArrayInsert for more than one row or Perform this in a loop
the cursor SaCursorInsert for a single row if necessary

5. Free the cursor SaCursorFree

6. Flush the network SaArrayFlush Necessary only if


message to the server using SaArrayInsert.

The following code sample excerpt demonstrates how to write four rows of data in
a single network message using the SaArrayInsert function. In the code, a call to
SaArrayFlush flushes all rows to the server so they are passed in the same network
message.

4 Using solidDB SA 95
scur = SaCursorCreate(scon, "SAEXAMPLE");

/* Bind variables to columns. */


SaCursorColInt(scur, "INTC", &intc);
SaCursorColStr(scur, "CHARC", &str);

/* Open the cursor. */


SaCursorOpen(scur);

/* Insert values to the table. The column values are taken


* from the user variables that are bound to columns.
*/
for (intc = 2; intc <= 5; intc++) {
switch (intc) {
case 2:
str = "B";
break;
case 3:
str = "C";
break;
case 4:
str = "D";
break;
case 5:
str = "E";
break;
}
SaArrayInsert(scur);
}

/* Close the cursor. */


SaCursorFree(scur);

/* Flush the inserts to the server. */


SaArrayFlush(scon, NULL);

Performing update and delete operations

solidDB SA functions required for basic update and delete operations are listed in
the table below.

After solidDB creates a cursor to a specific table, variables are bound to columns of
the table, and the cursor is opened. Before the actual search begins, the constraints
for finding the row for deletion are set. If there are more rows to be updated, each
of the rows requires a separate fetch before they are updated or deleted. After the
operation, the cursor is freed.
Table 45. Update and delete operation steps

Steps SA Function(s) Comment

1. Create a cursor SaCursorCreate

2. Binding variables SaCursorColData, SaCursorColDate,


to cursor SaCursorColDateFormat,
SaCursorColDFloat, SaCursorColDouble,
SaCursorColDynData, SaCursorColDynstr,
SaCursorColFloat, SaCursorColInt,
SaCursorColLong, SaCursorColStr,
SaCursorColTime, SaCursorColTimestamp

3. Open the cursor SaCursorOpen

96 IBM solidDB: Programmer Guide


Table 45. Update and delete operation steps (continued)

Steps SA Function(s) Comment

4. Set the search SaCursorEqual, SaCursorAtleast,


constraint for the row SaCursorAtmost
to be updated or
deleted

5. Start a search for SaCursorSearch


the row to be
updated or deleted

6. Fetch the row to be SaCursorNext


updated or deleted

7. Perform actual SaCursorUpdate or SaCursorDelete For updates, the new


update or delete values need to be in
variables bound in
step 2.

8. Free the cursor SaCursorFree

The following code sample excerpt demonstrates how to update a row in a table
using SaCursorUpdate. Note that in the code, the new values for the update are in
variables which are bound to the columns of the table using SaCursorColInt and
SaCursorColStr after the cursor is created.
scur = SaCursorCreate(scon, "SAEXAMPLE");

/* Bind variables to columns INTC and CHARC of test table. */


SaCursorColInt(scur, "INTC", &intc);
SaCursorColStr(scur, "CHARC", &str);

/* Open the cursor. */


SaCursorOpen(scur);

/* Set search constraint. */


str = "D";
SaCursorEqual(scur, "CHARC");

/* Start a search. */
SaCursorSearch(scur);

/* Fetch the column. */


SaCursorNext(scur);

/* Update the current row in the cursor. */


intc = 1000;
str = "D Updated";
SaCursorUpdate(scur);

/* Close the cursor. */


SaCursorFree(scur);

Reading data by using solidDB SA without SQL


solidDB SA functions required for query operations are listed in this topic.

4 Using solidDB SA 97
With solidDB SA, data is queried using cursors. The query data is found in a way
similar to update and delete operations. A cursor is created to a specific table,
variables are bound to columns of the table, and the cursor is then opened. The
constraints for finding the rows for the query are set before starting the actual
search. If more than one row is found, each row must be fetched separately. After
all the rows are fetched, the cursor needs to be freed.

Basically, all solidDB SA queries use the solidDB optimizer in a way similar to
SQL-based queries. The index selection strategy is the same as in SQL. The only
exception is that the solidDB SA search uses ORDER BY for selecting an index.
This means that an index that best fits ORDER BY is the one selected. If two
indices are equally good, then the one with a smaller cost is selected. The query is
optimized each time SaCursorSearch is called.

Note: There is no way to use optimizer hints functionality when solidDB SA is


used.
Table 46. Query Operation Steps

Steps SA Function(s) Comment

1. Create a cursor SaCursorCreate

2. Bind variables to SaCursorColInt, SACursorColStr and others


cursor for other data types

3. Open the cursor SaCursorOpen

4. Set the search SaCursorEqual, SaCursorAtleast,


constraint for the row SaCursorAtmost
to be queried

5. Start a search for SaCursorSearch


the row to be queried

6. Fetch the row(s) SaCursorNext Perform this in a loop


that match the given if necessary
criteria

7. Free the cursor SaCursorFree

Example
/* Create cursor to a database table. */
scur = SaCursorCreate(scon, "SAEXAMPLE");

/* Bind variables to columns of test table. */


rc = SaCursorColInt(scur, "INTC", &intc);
rc = SaCursorColStr(scur, "CHARC", &str);

/* Open the cursor. */


rc = SaCursorOpen(scur);
assert(rc == SA_RC_SUCC);

/* Set search constraints. */


str = "A";
rc = SaCursorAtleast(scur, "CHARC");
str = "C";
rc = SaCursorAtmost(scur, "CHARC");

98 IBM solidDB: Programmer Guide


/* Set ordering criteria. */
rc = SaCursorAscending(scur, "CHARC");

/* Start a search. */
rc = SaCursorSearch(scur);

/* Fetch the rows. */


for (i = 1; i <= 3; i++) {
rc = SaCursorNext(scur);
switch (intc) {
case 1:
assert(strcmp(str, "A") == 0);
break;
case 2:
assert(strcmp(str, "B") == 0);
break;
case 3:
assert(strcmp(str, "C") == 0);
break;
}

/* Close the cursor. */


SaCursorFree(scur);
}

Running SQL Statements by Using solidDB SA


In addition to bypassing SQL Parser and SQL interpretation, solidDB SA also
allows limited execution of SQL statements directly using function
SaSQLExecDirect.

This function is designed to execute simple SQL statements, such as CREATE


TABLE. If you need to retrieve SQL result sets, you must use another
programming interface such as ODBC or solidDB Light Client.

Example
/* Create test table and index. */
SaSQLExecDirect(scon,
"CREATE TABLE SAEXAMPLE(INTC INTEGER, CHARC VARCHAR)");
SaSQLExecDirect(scon,
"CREATE INDEX SAEXAMPLE_I1 ON SAEXAMPLE (CHARC)");

Transactions and autocommit mode


By default, solidDB SA runs in autocommit mode.

Autocommit mode is switched off by calling the function SaTransBegin, which


explicitly begins a transaction. In this mode, the transaction is committed using the
SaTransCommit function or rolled back using SaTransRollback.

Note: After the transaction is committed, solidDB SA returns to its autocommit


mode setting.

In autocommit mode, the transaction is committed immediately after an insert


(SaCursorInsert), update (SaCursorUpdate), or delete (SaCursorDelete). Note that
even when using SaArrayInsert, each individual record is inserted in a separate
transaction if autocommit is used (see “SaArrayInsert” on page 106 for more

4 Using solidDB SA 99
details). To improve performance when inserting multiple rows with the
SaArrayInsert function, put multiple inserts into a single transaction by using
SaTransBegin and SaTransCommit.

Handling database errors


This section contains information about database error handling.

solidDB SA does not provide ODBC-like error processing capability. Generally,


solidDB SA functions return SA_RC_SUCC or a pointer to the requested object if
successful. If not successful, then the return value is either one of the solidDB SA
error codes (see the table in the following section) or NULL. If the error is a
database error, the error text is returned by the SaErrorInfo function.
if (scon == NULL) {
/* Connect failed, display connect error text. */
char* errstr;
SaErrorInfo(NULL, &errstr, NULL);
printf("%s\n", errstr);
return(1);
}

The function SaCursorErrorInfo returns error text if the last cursor operation failed.
Note that SaErrorInfo has a connection parameter and thus returns the last error
applicable to that connection, while SaCursorErrorInfo has a cursor parameter and
thus returns the last error of that cursor.

Error Code and Messages for solidDB SA Functions

Following are the possible return codes for solidDB SA functions. All of these error
codes are defined in the sa.h file.
Table 47. solidDB SA Function Return Codes

Error Code Meaning

SA_RC_SUCC Operation was successful

SA_RC_END Operation has completed

SA_ERR_FAILED Operation failed

SA_ERR_CURNOTOPENED Cursor is not open

SA_ERR_CUROPENED Cursor is open

SA_ERR_CURNOSEARCH No active search in cursor

SA_ERR_CURSEARCH There is active search in cursor

SA_ERR_ORDERBYILL Illegal "order by" specification

SA_ERR_COLNAMEILL Illegal column name

SA_ERR_CONSTRILL Illegal constraint

SA_ERR_TYPECONVILL Illegal type conversion

100 IBM solidDB: Programmer Guide


Table 47. solidDB SA Function Return Codes (continued)

Error Code Meaning

SA_ERR_UNIQUE Unique constraint violation

SA_ERR_LOSTUPDATE Concurrency conflict, two transactions


updated or deleted the same row

SA_ERR_SORTFAILED Failed to sort the search result set

SA_ERR_CHSETUNSUPP Unsupported character set

SA_ERR_CURNOROW No current row in cursor

SA_ERR_COLISNOTNULL NULL value given for a NOT NULL column

SA_ERR_LOCALSORT Result set is sorted locally, cannot update or


delete the row

SA_ERR_COMERROR Communication error, connection is lost

SA_ERR_NOSTRCONSTR String for constraint is missing.

SA_ERR_ILLENUMVAL Illegal numeric value

SA_ERR_COLNOTBOUND Column is not bound

SA_ERR_CALLNOSUP Operation is not supported*

SA_ERR_RPCPARAM RPC parameter error

SA_ERR_TABLENOTFOUND Table not found

SA_ERR_READONLY Connection is read only

SA_ERR_ILLPARAMCOUNT Wrong number of parameters

SA_ERR_INVARG Invalid argument

SA_ERR_INVCALLSEQ Invalid call sequence

Note: SaArray* functions are not supported in linked library access; they work
only with the network client library. They return SA_ERR_CALLNOSUP with
linked library access.

Special notes about solidDB SA


This topic contains important information and restrictions about solidDB SA.

4 Using solidDB SA 101


solidDB SA and Binary Large Objects (BLOBs)

Currently, solidDB SA does not support BLOB streams and the maximum size of
an attribute value is limited to 32K.

SaCursorCol* Functions and solidDB SQL Supported Datatypes

The SaCursorColXXX() functions bind a variable of type XXX to a specified


column. For example, the SaCursorColInt function binds a variable of type int to a
specified column. When you bind a variable to a column, the variable and column
usually have corresponding types; for example, you usually bind an int C variable
to an INT SQL column. However, it is not absolutely required that the data type of
the column and the data type of the bound variable be equivalent. For example,
you could bind a C int variable to an SQL FLOAT, but you would risk losing
precision (or even overflowing or underflowing) as data was transferred back and
forth.

The SaCursorCol* functions support the SQL datatypes listed in the following
table.
Table 48. Supported SQL Datatype
L
O
L N
O V G
N L A V T
S G W O R A I
T M I D N V V V N B R M
I A N D E U A A A G B I B E
N L T F O C M R R W R W I N I S
Y L E R L U I E C C C C C V N A N D T T
SaCursolCol* I I G E O B M R H H H H H A A R A A I A
N N E A A L A I A A A A A R R Y R T M M
Function T T R L T E L C R R R R R C Y R Y E E P

SaCursorColInt X X X X X X X X X X X X X X

SaCursor ColLong X X X X X X X X X X X X X X

SaCursor ColFloat X X X X X X X X X X X X X X

SaCursor ColDouble X X X X X X X X X X X X X X

SaCursorColStr X X X

SaCursorCol Date X X X X X X X X

SaCursor ColTime X X X X X X X X

SaCursor ColTimestamp X X X X X X X X

SaCursor ColData X X X

SaCursor ColDynData X X X X X X X X X X X X X

SaCursor ColFixStr X X X X X X X X X X X X X X X X

102 IBM solidDB: Programmer Guide


Table 48. Supported SQL Datatype (continued)
L
O
L N
O V G
N L A V T
S G W O R A I
T M I D N V V V N B R M
I A N D E U A A A G B I B E
N L T F O C M R R W R W I N I S
Y L E R L U I E C C C C C V N A N D T T
SaCursolCol* I I G E O B M R H H H H H A A R A A I A
N N E A A L A I A A A A A R R Y R T M M
Function T T R L T E L C R R R R R C Y R Y E E P

SaCursor ColDynStr X X X X X X X X X X X X

Note: Keep in mind that, as in other APIs, the success of some conversions in
solidDB SA depend on declared values. For example, SaCursorCollInt is only able
to handle the SQL datatype CHAR (as in 'foo') if the actual value of the field is an
integer (as in '123').

solidDB SA Function Reference


This topic contains the list of the solidDB SA functions in alphabetic order.

Each description includes the purpose, synopsis, parameters, return value, and
comments.

Function Synopsis

The declaration synopsis for the function is:


SA_EXPORT_H function(modifier parameter [,...]);

where modifier can be:


SaConnectT*
SaColSearchT*
SaCursorT*
SaDataTypeT*
SaDateT*
SaDfloatT*
SaDynDataT*
SaDynStrT*
SaChSetT
char*
char**
double*
long*
float*
int
int*
unsigned*
void

Parameters are in italics and are described below.

4 Using solidDB SA 103


Parameter Description

In each function description, parameters are described in a table format. Included


in the table is the general usage type of the parameter (described in the next
section), as well as the use of the parameter variable in the specific function.

Parameter Usage Type

The table below shows the possible usage type for solidDB SA parameters. Note
that if a parameter is used as a pointer, it contains a second category of usage to
specify the ownership of the parameter variable after the call.
Table 49. solidDB SA Parameter Usage Types

Usage Type Meaning

in Indicates the parameter is input.

output Indicates the parameter is output.

in out Indicates the parameter is input/output.

take Applies only to a pointer parameter. It means that the parameter


value is taken by the function. The caller cannot reference to the
parameter after the function call. The function or an object created
in the function is responsible for releasing the parameter when it
is no longer needed.

hold Applies only to a pointer parameter. It means that the function


holds the parameter value even after the function call. The caller
can reference to the parameter value after the function call and is
responsible for releasing the parameter. Typically, this kind of
parameter is passed to the constructor of some object which holds
the pointer value inside a local data structure. The caller cannot
release the parameter until the object that holds the parameter is
deleted.

use Applies only to a pointer parameter. It means that the parameter


is just used during the function call. The caller can do whatever it
wants with the parameter after the function call. This is the most
common type of parameter passing.

ref Applies only to out parameters. See "Return Value" below for
details.

give Applies only to out parameters. See "Return Value" below for
details.

Return value

Each function description indicates if the function returns a value and the type of
value that is returned. Return Values can be one of the following values:
v Boolean (TRUE, FALSE),
v int (such as 1, 0),

104 IBM solidDB: Programmer Guide


v SaRetT (error return codes) such as SA_RC_SUCC. For a list of valid error codes,
refer to“Handling database errors” on page 100.
v Pointer (out parameter)

The possible return usage types for pointers are:


Table 50. Return Usage Types for Pointers

Usage Type Meaning

ref Indicates the caller can only reference the returned value, but
cannot release it. Ensure that the returned value is not used after
it is released by the object that returned it.

give Indicates the function gives the returned value to the caller. The
caller is responsible for releasing the returned value.

SaArrayFlush
SaArrayFlush flushes the array operation buffer (that is, it sends the data to the
server) after a series of calls to SaArrayInsert fills that buffer.

By default, all SA operations, even SaArrayFlush operations, are done in


autocommit mode. In autocommit mode, theSaArrayFlush function does not
automatically insert all of the array's records in a single transaction; instead, when
SaArrayFlush is called, each record's insertion is treated as a separate transaction.
To maximize performance, you may want to do an explicit SaTransBegin before
you call SaArrayFlush, and do an explicit SaTransCommit after you call
SaArrayFlush

SaArray* functions are not supported in linked library access; they work only with
the network client library. They return SA_ERR_CALLNOSUP with linked library
access.

Synopsis
SaRetT SA_EXPORT_H SaArrayFlush(SaConnectT* scon, SaRetT* rctab)

The SaArrayFlush function accepts the following parameters:


Table 51. SaArrayFlush Parameters

Parameters Usage Type Description

scon use Pointer to a connection object

rctab use Array of return codes for each array operation

If this parameter is non-NULL, the return code of each


array operation is returned in rctab[i], wherei is the order
number of the array operation since the last
SaArrayFlush.

Return Value

SA_RC_SUCC or error code of first failed array operation.

4 Using solidDB SA 105


See also

“SaArrayInsert.”

SaArrayInsert
SaArrayInsert inserts an array of values on one network message. This function
places the inserted value in the array insert buffer. You can flush the buffer (that is,
send the data to the server) using function SaArrayFlush.

SaArrayInsert may also perform an implicit flush if the internal cache becomes full.
However, to ensure that all rows are sent to the server, you should call
SaArrayFlush after you insert the last record using SaArrayInsert.

Note:
1. By default, all SA operations, even SaArrayInsert and SaArrayFlush operations,
are done in autocommit mode. See “SaArrayFlush” on page 105 for an
important note about performance.
2. SaArray* functions are not supported in linked library access; they work only
with the network client library. They return SA_ERR_CALLNOSUP with linked
library access.

Synopsis
SaRetT SA_EXPORT_H SaArrayInsert(SaCursorT* scur)

The SaArrayInsert function accepts the following parameters:


Table 52. SaArrayInsert Parameters

Parameters Usage Type Description

scur use Pointer to a cursor object

Return Value

SA_RC_SUCC or error code

See Also

“SaArrayFlush” on page 105.

SaColSearchCreate
SaColSearchCreate starts a column information search for a specified table.

Synopsis
SaColSearchT* SA_EXPORT_H SaColSearchCreate(
SaConnectT* scon,
char* tablename)

The SaColSearchCreate function accepts the following parameters:

106 IBM solidDB: Programmer Guide


Table 53. SaColSearchCreate Parameters

Parameters Usage Type Description

scon In Pointer to a connection object

tablename In Table name

Return Value

Pointer to the column search object, or NULL if table does not exist.

SaColSearchFree
SaColSearchFree releases the column search object.

Synopsis
void SA_EXPORT_H SaColSearchFree(SaColSearchT* colsearch)

The SaColSearchCreate function accepts the following parameters:


Table 54. SaColSearchCreate Parameters

Parameters Usage Type Description

colsearch In, take Column search pointer

Return Value

None

SaColSearchNext
SaColSearchNext returns information about the next column in the table.

Synopsis
int SA_EXPORT_H SaColSearchNext(
SaColSearchT* colsearch,
char** p_colname,
SaDataTypeT* p_coltype)

The SaColSearchNext function accepts the following parameters:


Table 55. SaColSearchNext Parameters

Parameters Usage Type Description

colsearch in, use Column search pointer

p_colname out, ref Pointer to the local copy of the column name is stored
into * p_colname

p_coltype out Type of column is stored into * p_coltype. See the sa.h
file for a description of the SaDataTypeT data type and
the valid values that it can hold.

4 Using solidDB SA 107


Return Value
Table 56. SaColSearchNext Return Value

Value Description

1 Next column found, parameters updated.

0 0 No more columns, parameters not


updated. The function also will return 0 if
the input parameters are invalid.

SaConnect
SaConnect creates a connection to the solidDB server. Several connections can be
active at the same time, but operations in different connections are executed in
separate transactions.

Synopsis
SaConnectT* SA_EXPORT_H SaConnect(
char* servername,
char* username,
char* password)

The SaConnect function accepts the following parameters:


Table 57. SaConnect Parameters

Parameters Usage Type Description

servername in, use Server name. An empty


servername connects to the
linked server.

username in, use User name

password in, use Password

Return Value
Table 58. SaConnect Return Value

Return Usage Type Description

give Connect pointer, or if connection failed,


NULL.

SaCursorAscending
SaCursorAscending specifies ascending order criteria for a column.

To sort by more than one column, you must call this function once for each
column. If there is no key (primary key or index) on the column, then the rows are
sorted locally (on the client) rather than on the server side.

108 IBM solidDB: Programmer Guide


Synopsis
SaRetT SA_EXPORT_H SaCursorAscending(
SaCursorT* scur,
char* colname)

The SaCursorAscending function accepts the following parameters:


Table 59. SaCursorAscending parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

Return Value

SA_RC_SUCC or error code

SaCursorAtleast
SaCursorAtleast specifies the Atleast criterion for a column. Atleast criterion means
that the column value must be greater than or equal to the Atleast value. The
Atleast value is taken from the user variable currently bound to the column.

Synopsis
SaRetT SA_EXPORT_H SaCursorAtleast(
SaCursorT* scur,
char* colname)

The SaCursorAtleast function accepts the following parameters:


Table 60. SaCursorAtleast Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

Return Value

SA_RC_SUCC or error code

SaCursorAtmost
SaCursorAtmost specifies the Atmost criterion for a column. Atmost criterion
means that the column value must be less than or equal to the Atmost value. The
Atmost value is taken from the user variable currently bound to the column.

Synopsis
SaRetT SA_EXPORT_H SaCursorAtmost(
SaCursorT* scur,
char* colname)

The SaCursorAtmost function accepts the following parameters:

4 Using solidDB SA 109


Table 61. SaCursorAtmost Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

Return Value

SA_RC_SUCC or error code

SaCursorBegin
SaCursorBegin positions the cursor to the beginning of the set. The subsequent call
to the SaCursorNext function returns the first row.

Synopsis
SaRetT SA_EXPORT_H SaCursorBegin(
SaCursorT* scur)

The SaCursorBegin function accepts the following parameters:


Table 62. SaCursorBegin Parameters

Parameters Usage Type Description

scur use Pointer to a cursor object

Return Value

SA_RC_SUCC or error code

SaCursorClearConstr
SaCursorClearConstr clears all search constraints from a cursor.

Synopsis
SaRetT SA_EXPORT_H SaCursorClearConstr(
SaCursorT* scur)

The SaCursorClearConstr function accepts the following parameters:


Table 63. SaCursorClearConstr Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

Return Value

SA_RC_SUCC or error code

110 IBM solidDB: Programmer Guide


SaCursorColData
SaCursorColData binds a user variable to a database column.

The bound variable may be used either as an "input" parameter or an "output"


parameter. An "input" parameter passes data values from the client to the server
for operations such as inserts and updates, and for search constraints. An "output"
parameter holds values read by the server during searches. For example, to
INSERT data, the user first binds the variables, then stores values into the bound
variables before the actual INSERT; those values are then copied into the database
when the INSERT is performed. Similarly, during a fetch operation, when the next
row is retrieved, the values in the columns of that row are copied into bound
variables so that the client program can see them.

A variable may be used multiple times after a single binding. For example, if you
wanted to insert multiple rows, you might create a loop in which you store
appropriate values in the bound variable and then invoke the INSERT operation.
The "bind" operation would only need to be done once before the loop; it would
not need to be executed inside the loop for each INSERT operation. Similarly, after
binding the variables once, you could retrieve many rows (one at a time) using the
SaCursorNext function. Each time that you retrieved a row, its values would be
copied into the bound variables. Note that the address of the data buffer does not
change; only the value stored there changes each time what you call SaCursorNext.

If the column has been set as a search constraint (rather like using a WHERE
clause in a SELECT statement), then the value for this constraint is set to the value
pointed to by the user data variable whose address is passed as dataptr. For
example, if the function SaCursorEquals has been called for the column, then the
server retrieves only the rows whose value exactly matches the current value of the
bound variable. Note that the search constraints are set up for the search
operations (SaCursorSearch, followed by calls to SaCursorNext) but may actually
be used to set the cursor to the correct position for other operations (such as
SaCursorUpdate or SaCursorDelete).Typically, updates are combined with searches
to update only some of the rows. This means that the values for columns which
have search constraints are used to define the affected rows (in effect the "WHERE"
clause in SQL) and other bound variables are used to define the new values for the
rest of the columns. Note that the same bound variable can be used in both the
search constraint and in the update/insert operation (just as the same column may
be used in both the WHERE clause and the "UPDATE ... SET col = value" clause of
an SQL UPDATE statement). If the same bound variable is used in both the search
constraint and to convey data back and forth between the client and the server, the
search constraint does not change each time that the data in the bound variable is
updated; the server uses the value that was in the bound variable at the time that
the search constraint was created (for example, when functions like
SaCursortAtmost() were called).

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations the new value for the column is
taken from the user variable.

When the bound variable is used as an "in" parameter (for example, in INSERT or
UPDATE operations), the user is responsible for the allocation and freeing of the
buffer. When a bound variable is used as an "out" parameter, the SA layer allocates
and frees the buffers. When the variable is used as an "out" parameter, the value
stored to the user variable is a pointer to a buffer that contains a local copy of the

4 Using solidDB SA 111


column data. After each row is retrieved, that row's value will be copied to this
buffer. The pointer to this buffer is valid until the next SaCursorOpen or
SaCursorFree call, after which the pointer should not be referenced.

Synopsis
SaRetT SA_EXPORT_H SaCursorColData(
SaCursorT* scur,
char* colname,
char** dataptr,
unsigned* lenptr)

The SaCursorColData function accepts the following parameters:


Table 64. SaCursorColData Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

dataptr in, hold Pointer to the user variable

lenptr in, hold Pointer to variable used to


hold length of data

Return Value

SA_RC_SUCC or error code.

SaCursorColDate
SaCursorColDate binds a user variable of type SaDateT to a database column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations the new value for the column is
taken from the user variable.

Synopsis
SaRetT SA_EXPORT_H SaCursorColDate(
SaCursorT* scur,
char* colname,
SaDateT* dateptr)

The SaCursorColDate function accepts the following parameters:


Table 65. SaCursorColDate Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

dateptr in, hold Pointer to the user variable

112 IBM solidDB: Programmer Guide


Return Value

SA_RC_SUCC or error code.

See Also

See “SaCursorColData” on page 111 for a more detailed discussion of binding


variables.

SaCursorColDateFormat
SaCursorColDateFormat binds date format string to a database column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. Depending on the column data type, the format string should be
date, time, or timestamp format.

Synopsis
SaRetT SA_EXPORT_H SaCursorColDateFormat(
SaCursorT* scur,
char* colname,
char* dtformat)

The SaCursorColDateFormat function accepts the following parameters:


Table 66. SaCursorColDateFormat parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

dtformat in, hold Date/time/timestamp format


string

Return Value

SA_RC_SUCC or error code.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables. For explanation of possible date/time/timestamp formats, see
“SaDateSetAsciiz” on page 135.

SaCursorColDfloat
SaCursorColDfloat binds a user variable of type SaDfloatT to a database column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations, the new value for the column is
taken from the user variable.

Note: SaDFloatT corresponds to the SQL data type DECIMAL (not FLOAT).
4 Using solidDB SA 113
Synopsis
SaRetT SA_EXPORT_H SaCursorColDfloat(
SaCursorT* scur,
char* colname,
SaDfloatT* dfloatptr)

The SaCursorColDfloat function accepts the following parameters:


Table 67. SaCursorColDfloat Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

dtfloatptr in, hold Pointer to the user variable

Return Value

SA_RC_SUCC or error code.

See Also

“SaCursorColDouble.”

“SaCursorColFloat” on page 117.

See “SaCursorColData” on page 111 for a more detailed discussion of binding


variables.

SaCursorColDouble
SaCursorColDouble binds a user variable of type double to a database column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations the new value for the column is
taken from the user variable.

Note: The C-language data type "double" is equivalent to SQL data type "FLOAT".

Synopsis
SaRetT SA_EXPORT_H SaCursorColDouble(
SaCursorT* scur,
char* colname,
double* doubleptr)

The SaCursorColDouble function accepts the following parameters:


Table 68. SaCursorColDouble Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

114 IBM solidDB: Programmer Guide


Table 68. SaCursorColDouble Parameters (continued)

Parameters Usage Type Description

colname in, use Column name

doubleptr in, hold Pointer to the user variable

Return Value

SA_RC_SUCC or error code.

See Also

“SaCursorColFloat” on page 117.

“SaCursorColDfloat” on page 113.

See “SaCursorColDynData” for a more detailed discussion of binding variables.

SaCursorColDynData
SaCursorColDynData binds a user variable of type SaDynDataT to a database
column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations, the new value for the column is
taken from the user variable.

In search operations, the column data is stored to the SaDynDataT variable using
function SaDynDataMove, which overwrites the old data. The user is responsible
for releasing the SaDynDataT variable after the search ends using function
SaDynDataFree.

Dynamic data objects (SaDynDataT) are an abstraction that simplifies the handling
of variable length data. Although dynamic data can be used with all types of data,
it is best fit for variable length data (VARBINARY, LONG VARBINARY,
VARCHAR, LONG VARCHAR, and so on).

The memory management of the data object is hidden inside the object. Dynamic
data objects have two externally-visible attributes: the data and the length.
Typically, the functions SaDynDataMove and SaDynDataAppend are used to set
and modify the data value inside the dynamic data object. More memory will be
automatically allocated when necessary and all the associated memory will be
automatically deallocated when the dynamic data object is disposed of using
SaDynDataFree. The user can access the data or the length using the respective
functions SaDynDataGetData and SaDynDataGetLen.

The use of SaDynDataMove and SaDynDataAppend may not be feasible when the
data already exists completely in a memory buffer. In addition to increasing the
memory usage by keeping two copies of the same data, the overhead of the
memory copy may be significant if the buffers are large. Therefore, it may be wise
to directly assign the data pointer by using SaDynDataMoveRef (rather than

4 Using solidDB SA 115


copying by using SaDynDataMove). In this case, the user may modify or deallocate
the memory buffer only after the dynamic data object itself has been freed.

Synopsis
SaRetT SA_EXPORT_H SaCursorColDynData(
SaCursorT* scur,
char* colname,
SaDynDataT* dd)

The SaCursorColDynData function accepts the following parameters:


Table 69. SaCursorColDynData Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

dd in, hold Pointer to the user variable

Return Value

SA_RC_SUCC or error code.

SaCursorColDynStr
SaCursorColDynStr binds a user variable of type SaDynStrT to a database column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations, the new value for the column is
taken from the user variable.

In search operations, the column data is stored to the SaDynStrT variable using
function SaDynStrMove, which overwrites the old data. The user is responsible for
releasing the SaDynStrT variable after the search ends using function
SaDynStrFree.

The user may bind an SaDynStrT variable to any type of column (not just character
columns) and the data will be converted back and forth between the column type
and the Dynamic String type.

Dynamic String objects (SaDynStrT) are an abstraction that simplifies the handling
of variable length strings. Typically, the functions SaDynStrMove and
SaDynStrAppend are used to set and modify the data value inside the dynamic
string object. More memory will be automatically allocated when necessary and all
the associated memory will be automatically deallocated when the dynamic data
object is disposed of using SaDynStrFree.

Synopsis
SaRetT SA_EXPORT_H SaCursorColDynStr(
SaCursorT* scur,
char* colname,
SaDynStrT* ds)

116 IBM solidDB: Programmer Guide


The SaCursorColDynStr function accepts the following parameters:
Table 70. SaCursorColDynStr Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

ds in, hold Pointer to the user variable

Return Value

SA_RC_SUCC or error code.

See Also
See “SaCursorColDynData” on page 115 for a more detailed discussion of binding
variables.

SaCursorColFloat
SaCursorColFloat binds a user variable of type float to a database column.

After the variable has been bound, it can be used to hold a value that will be
written to or read from a column, or that will be used to constrain a search
operation (for example, as part of the equivalent of a WHERE clause in SQL). In
search operations, the user variable is updated to contain the value read from the
current row that has been retrieved. Also, if search criteria are involved, this
function can be used to pass the values for them. In update and insert operations,
the new value is taken from the bound user variable and then written to the
column in the database.

Note: The C-language "float" data type corresponds to the SQL "SMALLFLOAT"
data type, not the SQL "FLOAT" data type.

Synopsis
SaRetT SA_EXPORT_H SaCursorColFloat(
SaCursorT* scur,
char* colname,
float* floatptr)

The SaCursorColFloat function accepts the following parameters:


Table 71. SaCursorColFloat Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

floatptr in, hold Pointer to the user variable

4 Using solidDB SA 117


Return Value

SA_RC_SUCC or error code.

See Also

“SaCursorColDouble” on page 114.

“SaCursorColDfloat” on page 113.

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaCursorColInt
SaCursorColInt binds a user variable of type int to a database column.

After the variable has been bound, it can be used to hold a value that will be
written to or read from a column, or that will be used to constrain a search
operation (for example, as part of the equivalent of a WHERE clause in SQL). In
search operations, the user variable is updated to contain the value read from the
current row that has been retrieved. Also, if search criteria are involved, this
function can be used to pass the values for them. In update and insert operations,
the new value is taken from the bound user variable and then written to the
column in the database.

Note: The C-language "int" data type is platform-dependent, while the SQL data
types (TINYINT, SMALLINT, INT, and BIGINT) are platform-independent. You
must be careful to map the appropriate C-language data type and value to the
corresponding SQL data type.

Synopsis
SaRetT SA_EXPORT_H SaCursorColInt(
SaCursorT* scur,
char* colname,
int* intptr)

The SaCursorColInt function accepts the following parameters:


Table 72. SaCursorColInt Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

intptr in, hold Pointer to the user variable

Return Value

SA_RC_SUCC or error code.

118 IBM solidDB: Programmer Guide


See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaCursorColLong
SaCursorColLong binds a user variable to a database column.

After the variable has been bound, it can be used to hold a value that will be
written to or read from a column, or that will be used to constrain a search
operation (for example, as part of the equivalent of a WHERE clause in SQL). In
search operations, the user variable is updated to contain the value read from the
current row that has been retrieved. Also, if search criteria are involved, this
function can be used to pass the values for them. In update and insert operations,
the new value is taken from the bound user variable and then written to the
column in the database.

Note: The C-language "long" data type is platform-dependent, while the SQL data
types (TINYINT, SMALLINT, INT, and BIGINT) are platform-independent. You
must be careful to map the appropriate C-language data type and value to the
corresponding SQL data type.

Synopsis
SaRetT SA_EXPORT_H SaCursorColLong(
SaCursorT* scur,
char* colname,
long* longptr)

The SaCursorColLong function accepts the following parameters:


Table 73. SaCursorColLong Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

longptr in, hold Pointer to the user variable

Return Value

SA_RC_SUCC or error code.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaCursorColNullFlag
SaCursorColNullFlag binds a NULL value flag to a column.

If the column value is NULL, then * p_isnullflag has a value 1,otherwise the value
is 0. The * p_isnullflag value is updated automatically during fetch operations. In

4 Using solidDB SA 119


search operations, the user variable is updated to contain the value of the current
row. Also, if search criteria are involved, this function is used to pass the values for
them. During insert and update, a NULL value is inserted to the database if *p
_isnullflag is not zero.

Synopsis
SaRetT SA_EXPORT_H SaCursorColNullFlag(
SaCursorT* scur,
char* colname,
int* p_isnullflag)

The SaCursorColNullFlag function accepts the following parameters:


Table 74. SaCursorColNullFlag Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

p_isnullflag in, hold Pointer to an integer variable into where the NULL status
is stored during fetch operations, and from where the
NULL status is taken during insert and update operations.

Return Value

SA_RC_SUCC or error code.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaCursorColStr
SaCursorColStr binds a user variable to a database column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations the new value for the column is
taken from the user variable.

In search operations, the value stored to the user variable is a pointer to a local
copy of the column data. The data pointer is valid until the next SaCursorOpen or
SaCursorFree call, after which the pointer should not be referenced.

Synopsis
SaRetT SA_EXPORT_H SaCursorColStr(
SaCursorT* scur,
char* colname,
char** strptr)

The SaCursorColStr function accepts the following parameters:

120 IBM solidDB: Programmer Guide


Table 75. SaCursorColStr Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

strptr in, hold Pointer to the user variable.

Return Value

SA_RC_SUCC or error code.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaCursorColTime
SaCursorColTime binds a user variable of type SaDateT to a database column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations, the new value for the column is
taken from the user variable.

Synopsis
SaRetT SA_EXPORT_H SaCursorColTime(
SaCursorT* scur,
char* colname,
SaDateT* timeptr)

Note: The data type of timeptr is indeed SaDateT; there is no separate SaTimeT for
time data.

The SaCursorColTime function accepts the following parameters:


Table 76. SaCursorColTime parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

timeptr in, hold Pointer to the user variable.

Return Value

SA_RC_SUCC or error code.

4 Using solidDB SA 121


See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaCursorColTimestamp
SaCursorColTimestamp binds a user variable of type SaDateT to a database
column.

In search operations, the user variable is updated to contain the value of the
current row. Also, if search criteria are involved, this function is used to pass the
values for them. In insert and update operations the new value for the column is
taken from the user variable.

Synopsis
SaRetT SA_EXPORT_H SaCursorColTimestamp(
SaCursorT* scur,
char* colname,
SaDateT* timestampptr)

Note: The data type of timeptr is indeed SaDateT; there is no separate


SaTimestampT for timestamp data.

The SaCursorColTimestamp function accepts the following parameters:


Table 77. SaCursorColTimestamp parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

timestampptr in, hold Pointer to the user variable.

Return Value

SA_RC_SUCC or error code.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaCursorCreate
SaCursorCreate creates a cursor to a table specified by table name. The operation
fails if the table does not exist.

Synopsis
SaCursorT* SA_EXPORT_H SaCursorCreate(
SaConnectT* scon,
char* tablename)

The SaCursorCreate function accepts the following parameters:

122 IBM solidDB: Programmer Guide


Table 78. SaCursorCreate Parameters

Parameters Usage Type Description

scon in, hold Pointer to a connection object

tablename in, use Table name

Return Value

The parameter scon has the Usage Type "hold" because the created cursor object
keeps referencing the scon object even after the function call has returned.
Table 79. Return Value

Return Usage Type Description

give Pointer to the cursor object, or NULL if table


does not exist.

SaCursorDelete
SaCursorDelete deletes the current row in a cursor from the database. The cursor
must be positioned to a row.

Synopsis
SaRetT SA_EXPORT_H SaCursorDelete(SaCursorT* scur)

The SaCursorDelete function accepts the following parameters:


Table 80. SaCursorDelete parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

Return value

SA_RC_SUCC or error code.

SaCursorDescending
SaCursorDescending specifies descending sorting criterion for a column.

To sort by more than one column, you must call this function once for each
column.

If there is no key (primary key, or index) on the column, then the rows are sorted
locally (on the client) rather than on the server side.

Synopsis
SaRetT SA_EXPORT_H SaCursorDescending(
SaCursorT* scur,
char* colname)

4 Using solidDB SA 123


The SaCursorDescending function accepts the following parameters:
Table 81. SaCursorDescending parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

Return value

SA_RC_SUCC or error code.

SaCursorEnd
SaCursorEnd positions the cursor to the end of the set. A subsequent call to
SaCursorPrev will position the cursor to the last row in the set.

Synopsis
SaRetT SA_EXPORT_H SaCursorEnd(
SaCursorT* scur)

The SaCursorEnd function accepts the following parameters:


Table 82. SaCursorEnd parameters

Parameters Usage Type Description

scur use Pointer to a cursor object

Return value

SA_RC_SUCC or error code.

SaCursorEqual
SaCursorEqual specifies an equal search criterion for a column.

Synopsis
SaRetT SA_EXPORT_H SaCursorEqual(
SaCursorT* scur,
char* colname)

The SaCursorEqual function accepts the following parameters:


Table 83. SaCursorEqual parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

124 IBM solidDB: Programmer Guide


Return value

SA_RC_SUCC or error code.

SaCursorErrorInfo
SaCursorErrorInfo returns error information from the last operation in the cursor.

Synopsis
bool SA_EXPORT_H SaCursorErrorInfo(
SaCursorT* scur,
char** errstr,
int* errcode)

The SaCursorErrorInfo function accepts the following parameters:


Table 84. SaCursorErrorInfo parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

errstr out, ref If non-NULL, pointer to a


local copy of an error string
is stored into * errstr.

errcode out If non-NULL, error code is


stored into * errcode.

Return value

TRUE If there are errors, errstr and errcode are updated.

FALSE If there are no errors, errstr and errcode are not updated.

SaCursorFree
SaCursorFree releases a cursor. After this call the cursor pointer is invalid.

Synopsis
void SA_EXPORT_H SaCursorFree(SaCursorT* scur)

The SaCursorFree function accepts the following parameters:


Table 85. SaCursorFree parameters

Parameters Usage Type Description

scur in, take Pointer to a cursor object

Return value

None.

4 Using solidDB SA 125


SaCursorInsert
SaCursorInsert inserts a new row into the database. Column values for the new
row are taken from the user variables bound to columns. The cursor must be
opened before new rows can be inserted.

Synopsis
SaRetT SA_EXPORT_H SaCursorInsert(SaCursorT* scur)

The SaCursorInsert function accepts the following parameters:


Table 86. SaCursorInsert parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

Return value

SA_RC_SUCC or error code.

SaCursorLike
SaCursorLike specifies a like criterion for a column.

The value cannot contain any wild card characters like '_' or '%' in SQL. If such
characters exist in the column value, they are quoted with escape characters by the
system. Thus, the like value is effectively the same as the SQL like with no wild
card characters ending with a '%' character. For example, if you specify that the
engine should search for "MARK" in the column, then the engine will find all
values that start with "MARK", such as "MARK", "MARK SMITH", and
"MARKETING".

The like value is taken from the user variable bound to the column.

Synopsis
SaRetT SA_EXPORT_H SaCursorLike(
SaCursorT* scur,
char* colname,
int likelen)

The SaCursorLike function accepts the following parameters:


Table 87. SaCursorLike parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

likelen in Length of like part


(excluding the string
terminator)

126 IBM solidDB: Programmer Guide


Return value

SA_RC_SUCC or error code.

SaCursorNext
SaCursorNext fetches the next row from the database. All user variables bound to
columns are updated.

Synopsis
SaRetT SA_EXPORT_H SaCursorNext(SaCursorT* scur)

The SaCursorNext function accepts the following parameters:


Table 88. SaCursorNext parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

Return value

SA_RC_SUCC Next row found

SA_RC_END End of search

SaCursorOpen
SaCursorOpen opens a cursor.

All SaCursorColXXX operations must be done before the cursor is opened. When
the cursor is opened, possible existing search is terminated. Also, all search criteria
specified for the cursor are cleared.

After the cursor is opened, user can insert new rows to the cursor or specify search
criteria. Cursor must be opened before a search can be started.

Synopsis
SaRetT SA_EXPORT_H SaCursorOpen(SaCursorT* scur)

The SaCursorOpen function accepts the following parameters:


Table 89. SaCursorOpen parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

Return value

SA_RC_SUCC or error code.

SaCursorOrderbyVector
SaCursorOrderbyVector is used to specify the order of columns used in a search.

4 Using solidDB SA 127


The initial values are used as a vector of values to specify the starting position for
the search in the key. The initial value is used only for the starting point selection
in the key; after that, the initial values are not checked against the column values.
If several criteria are given, they are solved in the given order. A proper key must
exist for the ordering.

The initial value is taken from the user variable bound to the column.

Synopsis
SaRetT SA_EXPORT_H SaCursorOrderbyVector(
SaCursorT* scur,
char* colname)

The SaCursorOrderbyVector function accepts the following parameters:


Table 90. SaCursorOrderbyVector parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

colname in, use Column name

Return Value
SA_RC_SUCC or error code.

SaCursorOrderbyVector example
/* These variables will be bound to the columns named "I" and "J" */
int i, j;
/* Bind variables to columns in this cursor. */
SaCursorColStr(scur, "I", ’i);
SaCursorColStr(scur, "J", ’j);
/* Set the values that we want to use in the search. */
i = 2;
j = 1;
/* Specify the order of the columns. */
SaCursorOrderByVector(scur, "I");
SaCursorOrderByVector(scur, "J");
/* Search the cursor for matching values. */
SaCursorSearch(scur);

The preceding would be the equivalent of the following SQL WHERE clause:
...WHERE (i,j) >= (2,1)

SaCursorPrev
SaCursorPrev fetches the previous row from the database. All user variables
currently bound to columns are updated.

Synopsis
SaRetT SA_EXPORT_H SaCursorPrev(SaCursorT* scur)

The SaCursorPrev function accepts the following parameters:

128 IBM solidDB: Programmer Guide


Table 91. SaCursorPrev parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

Return value

SA_RC_SUCC Previous row found

SA_RC_END Beginning of search (we are already at the first row, so there is no
previous row).

Note: SA_RC_END can apply to either end (start or finish) of the cursor.

SaCursorReSearch
SaCursorReSearch starts a new search using old search criteria.

Synopsis
SaRetT SA_EXPORT_H SaCursorReSearch(SaCursorT* scur)
The SaCursorReSearch function accepts the following
parameters:
Table 92. SaCursorReSearch Parameters

Parameters Usage Type Description

scur use Pointer to a cursor object

Return value

SA_RC_SUCC, SA_RC_END, or error code. See “Handling database errors” on


page 100 for a list of error codes.

SaCursorSearch
SaCursorSearch starts a search in a cursor. After the search is started, the user can
fetch rows from the database. Every search is executed as a separate transaction
and it does not see any changes made by the current user or any other user after
the search is started.

Synopsis
SaRetT SA_EXPORT_H SaCursorSearch(SaCursorT* scur)

The SaCursorSearch function accepts the following parameters:


Table 93. SaCursorSearch parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

4 Using solidDB SA 129


Return value

SA_RC_SUCC, SA_RC_END or error code

SaCursorSearchByRowid
SaCursorSearchByRowid starts a new search where the row specified by rowid
belongs to the search set.

SaCursorSearchByRowid searches only according to rowid, so it returns one row or


zero rows. Previous search constraints are not removed, and they become effective
in the next SaCursorReSearch call.

To get the rowid for a particular record, read the value of the rowid column. Every
table has a rowid column; you do not need to explicitly create a rowid column
within a CREATE TABLE or ALTER TABLE statement.

Synopsis
SaRetT SA_EXPORT_H SaCursorSearchByRowid(
SaCursorT* scur,
void* rowid,
int rowidlen)

The SaCursorSearchByRowid function accepts the following parameters:


Table 94. SaCursorSearchByRowid parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

rowid in, use Pointer to a data area containing rowid. The rowid should
be in the form of a string (char *) despite the fact that it is
declared as "void *".

rowidlen in Length of data (string) pointed to by the rowid parameter

Return Value

SA_RC_SUCC, SA_RC_END, or error code.

SaCursorSearchReset
SaCursorSearchReset resets a search cursor.

The old search constraints are used, but their values are read again from the user
buffers (i.e. the parameters). This allows you to increase performance in situations
where you want to repeat a search using a query that is identical except for the
specific values used.

For example, suppose that a particular user or connection always searches a


particular table based on the ID column in that table, but uses a different ID value
in each search. Instead of creating a "new" query to search for the next ID, you can
reset the existing query and use a new value.

As an example, suppose that your existing code looks similar to the following:

130 IBM solidDB: Programmer Guide


...
/* Bind variable(s) to column(s). */
SaCursorColInt(scur, "MY_COL_NAME", &search_parameter1);

/* Repeat a query using different values each time. */


while (there_are_more_values_to_look_for) {
/* Set the parameter to the value that you want to search for. */
search_parameter1 = some_value;
/* Specify the search criterion. */
rc = SaCursorEqual(scur, "MY_COL_NAME");
/* Create new query that uses that search criterion and param value*/
rc = SaCursorSearch(scur);
/* Get the row (or rows) that match the search criteria. */
rc = SaCursorNext(scur);
/* Process the retrieved data... */
foo();
...
/* Get rid of the old query before the next loop iteration. */
rc = SaCursorClearConstr(scur);
}
...

You can improve performance in most cases by changing your code to look like
the following example:
...
/* Bind variable(s) to column(s). */
SaCursorColInt(scur, "MY_COL_NAME", &search_parameter1);

/* Create a new query. */


rc = SaCursorEqual(scur, "MY_COL_NAME");
rc = SaCursorSearch(scur);
/* Set the parameter to the value that you want to search for. */
search_parameter1 = some_value;

/* Repeat a query using different values each time. */


while (there_are_more_values_to_look_for) {
/* Get the row (or rows) that match the search criteria. */
rc = SaCursorNext(scur);
/* Process the retrieved data... */
foo();
...
/* Set the param to the next value that you want to search for. */
search_parameter1 = some_value;
/* Reset the existing query to use the latest value in the param. */
rc = SaCursorSearchReset(scur);
}
...

When you use SaCursorSearchReset(), you no longer have to re-specify the


constraint condition ("Equal", in the example above) and call SaCursorSearch() each
time.

SaCursorSearchReset resets the cursor to the beginning of the new result set. For
example, if you reset a search with no constraints at all, it will reposition the
cursor to the beginning of the table.

Note: Ensure that you update the values of the search parameters in the buffers
before you call this function; the new values are read during this function call.

Limitations
1. SaCursorSearchReset() can not be used in the following scenarios:

4 Using solidDB SA 131


v The search has a local sort, i.e. not all sorting criteria could be solved by the
index used for the search
v The search is done by rowid with SaCursorSearchByRowid
In these cases, SaCursorSearchReset returns SA_ERR_NORESETSEARCH.
2. Each "like" value that you use in constraints must be the same length. The
reason for this is that SaCursorLike() takes the length of the "like" constraint as
an argument, but it is not possible to change this length when
SaCursorSearchReset() is called. For example, the function will work correctly if
you use the following sequence of "like" values, because they are all the same
length:
"SMITH"
"JONES"
However, the function will not work correctly if you use the following
sequence of "like" values:
"SMITH"
"JOHNSON"
3. Using SaCursorSearchReset is usually impractical if you set multiple constraints
using the same column binding. For example, suppose that you want to search
for values of "col" in the range between 1 and 10 (inclusive). Your code would
look like the following example::
SaCursorColInt(scur, "col", &i);
i = 1;
SaCursorAtleast(scur, "col");
i = 10;
SaCursorAtmost(scur, "col");
If you reset a search like this, the new value for the column is read from the
variable i only once. Therefore, the server reads one value and uses it as both
the upper and lower bound. For example, suppose that you use the following
code:
i = 5;
SaCursorSearchReset(scur);
This code makes the search 5 <= i <= 5, which is not the desired result.

Synopsis
SaRetT SA_EXPORT_H SaCursorSearchReset(
SaCursorT* scur

The SaCursorSearchReset function accepts the following parameters:


Table 95. SaCursorSearchReset Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

Return Value

SA_RC_SUCC or error code.

SaCursorSetLockMode
SaCursorSetLockMode sets the cursor search mode.

132 IBM solidDB: Programmer Guide


This setting affects the possible locking modes in the server. If a search is already
active, the setting will affect only the next search done in the same cursor. By
default the search mode is SA_LOCK_SHARE.

Synopsis
SaRetT SA_EXPORT_H SaCursorSetLockMode(
SaCursorT* scur,
sa_lockmode_t lockmode)

The SaCursorSetLockMode function accepts the following parameters:


Table 96. SaCursorSetLockMode Parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

lockmode in Search mode that can be one of the following mode:


v SA_LOCK_SHARE
v SA_LOCK_FORUPDATE
v SA_LOCK_EXCLUSIVE

The meanings of the various modes are as follows:


v SA_LOCK_SHARE: default optimistic concurrency control.
v SA_LOCK_FORUPDATE: locks the row for update; others can only read, not
write.
v SA_LOCK_EXCLUSIVE: locks the row exclusively; others cannot read or write
this record.

Note: This function applies to any table; the table does not need to have a
particular lock mode for this function to apply.

Return Value

SA_RC_SUCC

SA_ERR_ILLENUMVAL

SaCursorSetPosition
SaCursorSetPosition positions the cursor to a row specified by a key value. The
key value is taken from user bound column variables which have a constraint
specification.

Synopsis
SaRetT SA_EXPORT_H SaCursorSetPosition(
SaCursorT* scur)

The SaCursorSetPosition function accepts the following parameters:


Table 97. SaCursorSetPosition parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

4 Using solidDB SA 133


Return value

SA_RC_SUCC or error code.

SaCursorSetRowsPerMessage
SaCursorSetRowsPerMessage sets the number of rows to be sent in one network
message from the server to the client.

The setting has no effect after the search has been started by function
SaCursorSearch.

Synopsis
SaRetT SA_EXPORT_H
SaCursorSetRowsPerMessage(
SaCursorT* scur,
int rows_per_message)

The SaCursorSetRowsPerMessage function accepts the following parameters:


Table 98. SaCursorSetRowsPerMessage parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

rows_per_message in Number of rows to send in


one network message

Return value

SA_RC_SUCC Success

SA_ERR_FAILED Error, rows_per_message < 1

SaCursorUpdate
SaCursorUpdate updates the current row in a cursor in the database.

The cursor must be positioned to a row. Column values for the new row are taken
from the user variables bound to columns.

Synopsis
SaRetT SA_EXPORT_H SaCursorUpdate(SaCursorT* scur)

The SaCursorUpdate function accepts the following parameters:


Table 99. SaCursorUpdate parameters

Parameters Usage Type Description

scur in, use Pointer to a cursor object

134 IBM solidDB: Programmer Guide


Return value

SA_RC_SUCC or error code.

SaDateCreate
SaDateCreate creates a new date object.

The date stored in the date object is undefined.

Synopsis
SaDateT* SA_EXPORT_H SaDateCreate(void)

The SaDateCreate function accepts no parameters.

Return value
Table 100. SaDateCreate Return Values

Return Usage Type Description

give A new date object

SaDateFree
SaDateFree releases a date object.

After this call, the date object is invalid and cannot be used.

Synopsis
void SA_EXPORT_H SaDateFree(SaDateT* date)

The SaDateFree function accepts the following parameters:


Table 101. SaDateFree parameters

Parameters Usage Type Description

date in, take Date object

Return value

None.

SaDateSetAsciiz
SaDateSetAsciiz sets ASCII zero string date to a date object.

The following special characters are recognized in the format string:


YYYY year including century
YY year with default century 1900
MM month
M month
DD day of month
D day of month
HH hours
H hours

4 Using solidDB SA 135


NN minutes
N minutes
SS seconds
S seconds
FFF fractions of a second, 1/1000 seconds

All fields are optional. The fields are scanned from the format string, and when a
match is found, the field is replaced with the proper value. All other characters in
the format are treated literally.

Double letters (for example, "MM", "DD", and so on) indicate that the values
should be expressed with two digits (values 1-9 will be preceded with the 0
character, for example, 01). Single letters indicate that the value should be
expressed with one digit if possible. For example, if you define the date format as
"YY-M-D" then the date January 2, 1999 will look like "99-1-2". If you define the
date format as "YY-MM-DD", then the date will look like "99-01-02"

The following examples show the usage of date formats:


SaDateSetAsciiz(date, "YY-MM-DD", "94-09-13");
SaDateSetAsciiz(date, "MM/DD/YY [Link]", "09/13/94 19.20");

The default date format is YYYY-MM-DD HH:NN:SS, where time fields are
optional.

Synopsis
SaRetT SA_EXPORT_H SaDateSetAsciiz(
SaDateT* date,
char* format,
char* asciiz)

The SaDateSetAsciiz function accepts the following parameters:


Table 102. SaDateSetAsciiz Parameters

Parameters Usage Type Description

date in, out Date object

format in, use Format of date in asciiz (zero-terminated ASCII) buffer,


or NULL if default format is used

asciiz in, use Buffer containing the data in asciiz (zero-terminated


ASCII) string format

Return Value

SA_RC_SUCC

SA_ERR_FAILED

SaDateSetTimet
SaDateSetTimet copies the input value from the variable named "timet" to the
variable named "date". The value is automatically converted from the format
time_t (the format returned by C-library function time()) to the format SaDateT.

136 IBM solidDB: Programmer Guide


Synopsis
SaRetT SA_EXPORT_H SaDateSetTimet(
SaDateT* date,
long timet)

The SaDateSetTimet function accepts the following parameters:


Table 103. SaDateSetTimet parameters

Parameters Usage Type Description

date use Date object

timet in New date value in time_t


format

Return value
SA_RC_SUCC

SA_ERR_FAILED

SaDateToAsciiz
SaDateToAsciiz stores the date in an ASCII zero-terminated string format.

For an explanation of different date formats, see “SaDateSetAsciiz” on page 135.

Synopsis
SaRetT SA_EXPORT_H SaDateToAsciiz(
SaDateT* date,
char* format,
char* asciiz)

The SaDateToAsciiz function accepts the following parameters:


Table 104. SaDateToAsciiz parameters

Parameters Usage Type Description

date in, use Date object

format in, use Format of date in asciiz (zero-terminated ASCII) buffer,


or NULL if default format is used

asciiz out Buffer where date is stored.


Note: Note that the caller must allocate a sufficiently
large buffer before calling this function, and is also
responsible for deallocating the buffer when done with it.

Return Value

SA_RC_SUCC

SA_ERR_FAILED

4 Using solidDB SA 137


SaDateToTimet
SaDateToTimet stores the date in a time_t format. The time_t date is the same
value as returned by C-library function time().

Synopsis
SaRetT SA_EXPORT_H SaDateToTimet(
SaDateT* date,
long* p_timet)

The SaDateToTimet function accepts the following parameters:


Table 105. SaDateToTimet parameters

Parameters Usage Type Description

date in, use Date object

timet out Pointer to a long variable


into where the date is stored
in time_t format.

Return value

SA_RC_SUCC

SA_ERR_FAILED

SaDefineChSet
SaDefineChSet defines the client character set.

Synopsis
SaRetT SA_EXPORT_H SaDefineChSet(
SaConnectT* scon,
SaChSetT chset)

The SaDefineChSet function accepts the following parameters:


Table 106. SaDefineChSet parameters

Parameters Usage Type Description

scon in out Pointer to a connection object

chset in Enumerated charset specification. The valid character sets


are listed in the sa.h file and include
SA_CHSET_DEFAULT, SA_CHSET_ANSI, and so on.

Note: The usage type of scon includes "out" because the scon parameter is
modified by this function call.

Return value

SA_RC_SUCC when OK or SA_ERR_CHSETUNSUPP when specified character set


is not supported.

138 IBM solidDB: Programmer Guide


SaDfloatCmp
SaDfloatCmp compares two dfloat values.

Synopsis
int SA_EXPORT_H SaDfloatCmp(
SaDfloatT* p_dfl1,
SaDfloatT* p_dfl2)

The SaDfloatCmp function accepts the following parameters:


Table 107. SaDfloatCmp parameters

Parameters Usage Type Description

p_dfl1 in, use Pointer to dfloat variable

p_dfl2 in, use Pointer to dfloat variable

Return value
< -1 if p_dfl1 < p_dfl2
= 0 if p_dfl1 = p_dfl2
> 1 if p_dfl1 > p_dfl2

This parallels the strcmp() function in C, which returns a negative number if the
first parameter is less than the second, zero if the two are equal, and a positive
number (greater than zero) if the first parameter is greater than the second.

SaDfloatDiff
SaDfloatDiff calculates the difference of two dfloat values (that is, p_dfl1 - p_dfl2).
The result is stored into * p_result_dfl.

Synopsis
SaRetT SA_EXPORT_H SaDfloatDiff(
SaDfloatT* p_result_dfl,
SaDfloatT* p_dfl1,
SaDfloatT* p_dfl2)

The SaDfloatDiff function accepts the following parameters:


Table 108. SaDfloatDiff parameters

Parameters Usage Type Description

p_result_dfl out Pointer to dfloat variable


where the result is stored.

p_dfl1 in, use Pointer to dfloat variable

p_dfl2 in, use Pointer to dfloat variable

4 Using solidDB SA 139


Return value

SA_RC_SUCC

SA_ERR_FAILED

SaDfloatOverflow
SaDfloatOverflow checks if the dfloat contains an overflow value.

Synopsis
int SA_EXPORT_H SaDfloatOverflow(
SaDfloatT* p_dfl)

The SaDfloatOverflow function accepts the following parameters:


Table 109. SaDfloatOverflow parameters

Parameters Usage Type Description

p_dfl in, use Pointer to dfloat variable

Return value

1: dfloat value is an overflow value

0: dfloat value is not an overflow value

SaDfloatProd
SaDfloatProd calculates the product of two dfloat values. The result is stored into *
p_result_dfl.

Synopsis
SaRetT SA_EXPORT_H SaDfloatProd(
SaDfloatT* p_result_dfl,
SaDfloatT* p_dfl1,
SaDfloatT* p_dfl2)

The SaDfloatProd function accepts the following parameters:


Table 110. SaDfloatProd Parameters

Parameters Usage Type Description

p_result_dfl out Pointer to dfloat variable


where the result is stored.

p_dfl1 in Pointer to dfloat variable.

p_dfl2 in Pointer to dfloat variable.

140 IBM solidDB: Programmer Guide


Return Value

SA_RC_SUCC

SA_ERR_FAILED

SaDfloatQuot
SaDfloatQuot calculates the quotient of two dfloat values (that is, p_dfl1 / p_dfl2 ).
The result is stored into * p_result_dfl.

Synopsis
SaRetT SA_EXPORT_H SaDfloatQuot(
SaDfloatT* p_result_dfl,
SaDfloatT* p_dfl1,
SaDfloatT* p_dfl2)

The SaDfloatQuot function accepts the following parameters:


Table 111. SaDfloatQuot parameters

Parameters Usage Type Description

p_result_dfl out Pointer to dfloat variable


where the result is stored

p_dfl1 in Pointer to dfloat variable.

p_dfl2 in Pointer to dfloat variable.

Return value

SA_RC_SUCC

SA_ERR_FAILED

SaDfloatSetAsciiz
SaDfloatSetAsciiz sets the value of the dfloat from a zero-terminated ASCII string.

Synopsis
SaRetT SA_EXPORT_H SaDfloatSetAsciiz(
SaDfloatT* p_dfl,
char* asciiz)

The SaDfloatSetAsciiz function accepts the following parameters:


Table 112. SaDfloatSetAsciiz parameters

Parameters Usage Type Description

p_dfl1 out Pointer to dfloat variable


where the result is stored.

asciiz in Buffer where the dfloat value


is read as a zero-terminated
ASCII string.

4 Using solidDB SA 141


Return value

SA_RC_SUCC

SA_ERR_FAILED

SaDfloatSum
SaDfloatSum calculates the sum of two dfloat values. The result is stored into *
p_result_dfl.

Synopsis
SaRetT SA_EXPORT_H SaDfloatSum(
SaDfloatT* p_result_dfl,
SaDfloatT* p_dfl1,
SaDfloatT* p_dfl2)

The SaDfloatSum function accepts the following parameters:


Table 113. SaDfloatSum parameters

Parameters Usage Type Description

p_result_dfl out Pointer to dfloat variable


where the result is stored

p_dfl1 in Pointer to dfloat variable.

p_dfl2 in Pointer to dfloat variable.

Return value

SA_RC_SUCC or error code.

SaDfloatToAsciiz
SaDfloatToAsciiz stores the dfloat value as an asciiz (zero-terminated ASCII) string.

Synopsis
SaRetT SA_EXPORT_H SaDfloatToAsciiz(
SaDfloatT* p_dfl,
char* asciiz)

The SaDfloatToAsciiz function accepts the following parameters:


Table 114. SaDfloatToAsciiz parameters

Parameters Usage Type Description

p_dfl in Pointer to dfloat variable.

asciiz out Buffer where the dfloat is stored in asciiz (zero-terminated


ASCII) string format. The memory for this must already be
allocated by the caller.

142 IBM solidDB: Programmer Guide


Return value

SA_RC_SUCC

SA_ERR_FAILED

SaDfloatUnderflow
SaDfloatUnderflow checks if the dfloat contains an underflow value.

Synopsis
int SA_EXPORT_H SaDfloatUnderflow(
SaDfloatT* p_dfl)

The SaDfloatUnderflow function accepts the following parameters:


Table 115. SaDfloatUnderflow parameters

Parameters Usage Type Description

p_dfl in, use Pointer to dfloat variable.

Return value

1: dfloat value is an underflow value

0: dfloat value is not an underflow value

SaDisconnect
SaDisconnect disconnects the user from the solidDB server.

Synopsis
void SA_EXPORT_H SaDisconnect(SaConnectT* scon)

The SaDisconnect function accepts the following parameters:


Table 116. SaDisconnect Parameters

Parameters Usage Type Description

scon in, take Pointer to a connection


object.

Return Value

None.

SaDynDataAppend
SaDynDataAppend appends data to the dynamic data object.

4 Using solidDB SA 143


Synopsis
void SA_EXPORT_H SaDynDataAppend(
SaDynDataT* dd,
char* data,
unsigned len)

The SaDynDataAppend function accepts the following parameters:


Table 117. SaDynDataAppend parameters

Parameters Usage Type Description

dd use Dynamic data object.

data in out, use Data that is appended to the


dd.

len in Length of the data to be


appended.

Return Value

None.

See also

See “SaCursorColDynData” on page 115 for a more detailed discussion of binding


variables.

SaDynDataChLen
SaDynDataChLen changes the data area length of dynamic data object. It allocates
and deallocates memory as necessary.

If the new length is smaller than the current length, the data area is truncated. If
the new length is greater than the current length, the new data area content is
initialized with space characters.

Synopsis
void SA_EXPORT_H SaDynDataChLen(
SaDynDataT* dd,
unsigned len)

The SaDynDataChLen function accepts the following parameters:


Table 118. SaDynDataChLen Parameters

Parameters Usage Type Description

dd in out, use Dynamic data object.

len in New data area length of


dynamic data object.

144 IBM solidDB: Programmer Guide


Return Value

None.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of


"Dynamic Data" (SaDynDataT).

SaDynDataClear
SaDynDataClear deallocates the memory allocations from an SaDynDataT object.

SaDynDataClear deallocates the data; it does not deallocate the SaDynDataT object
itself. The result of SaDynDataClear leaves an "empty" dynamic data object
returned by SaDynDataCreate. The SaDynDataT object itself must be deallocated
separately using the SaDynDataFree function.

Synopsis
void SA_EXPORT_H SaDynDataClear(
SaDynDataT* dd)

The SaDynDataClear function accepts the following parameters:


Table 119. SaDynDataClear Parameters

Parameters Usage Type Description

dd in out, use Dynamic data object.

Return Value

None.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of


"Dynamic Data" (SaDynDataT).

SaDynDataCreate
SaDynDataCreate creates a new dynamic data object. A dynamic data object is an
object that can hold variable amounts of any type of data.

Dynamic data objects can be manipulated using other SaDynDataXXX functions.

Synopsis
SaDynDataT* SA_EXPORT_H SaDynDataCreate(void)

SaDynDataCreate accepts no parameters.

4 Using solidDB SA 145


Return Value
Table 120. SaDynDataCreate Return Value

Return Usage Type Description

give A new empty dynamic data object. Returns


NULL in case of an error.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of


"Dynamic Data" (SaDynDataT).

SaDynDataFree
SaDynDataFree releases a dynamic data object. After this call, the dynamic data
object pointer is invalid and cannot be used.

Synopsis
void SA_EXPORT_H SaDynDataFree(
SaDynDataT* dd)

The SaDynDataFree function accepts the following parameters:


Table 121. SaDynDataFree parameters

Parameters Usage Type Description

dd in, take Dynamic data object.

Return Value

None

See also

See “SaCursorColDynData” on page 115 for a more detailed discussion of


"Dynamic Data" (SaDynDataT).

SaDynDataGetData
SaDynDataGetData returns the pointer to the data area of the dynamic data object.

Synopsis
char* SA_EXPORT_H SaDynDataGetData(
SaDynDataT* dd)

The SaDynDataGetData function accepts the following parameters:


Table 122. SaDynDataGetData parameters

Parameters Usage Type Description

dd in, use Dynamic data object.

146 IBM solidDB: Programmer Guide


Return Value

A reference to the local data area of dynamic data object.

See also

See “SaCursorColDynData” on page 115 for a more detailed discussion of


"Dynamic Data" (SaDynDataT).

SaDynDataGetLen
SaDynDataGetLen returns the length of the data area of the dynamic data object.

Synopsis
unsigned SA_EXPORT_H SaDynDataGetLen(
SaDynDataT* dd)

The SaDynDataGetData function accepts the following parameters:


Table 123. SaDynDataGetData Parameters

Parameters Usage Type Description

dd in, use Dynamic data object.

Return Value

Data area length. The function returns 0 if there is an error, or if the actual length
of the data area is 0.

See Also

See “SaCursorColDynData” on page 115 for a more detailed discussion of


"Dynamic Data" (SaDynDataT).

SaDynDataMove
SaDynDataMove copies data from the parameter named "data" to a dynamic data
object (named dd). This function overwrites possible existing data.

The parameter dd must point to a Dynamic Data Object previously created with
the SaDynDataCreate function.

Note: SaDynDataMove copies the data. To copy just the reference rather than the
data, see “SaDynDataMoveRef” on page 148.

Typically, the functions SaDynDataMove and SaDynDataAppend are used to set


and modify the data value inside the dynamic data object. More memory will be
automatically allocated when necessary and all the associated memory will be
automatically deallocated when the dynamic data object is disposed of using
SaDynDataFree. The user can access the data or the length using the respective
functions SaDynDataGetData and SaDynDataGetLen.

The use of SaDynDataMove and SaDynDataAppend may not be feasible when the
data already exists completely in a memory buffer. In addition to increasing the
memory usage by keeping two copies of the same data, the overhead of the

4 Using solidDB SA 147


memory copy may be significant if the buffers are large. Therefore, it may be wise
to directly assign the data pointer by using SaDynDataMoveRef (rather than
copying by using SaDynDataMove). In this case, the user may modify or deallocate
the memory buffer only after the dynamic data object itself has been freed.

Synopsis
void SA_EXPORT_H SaDynDataMove(
SaDynDataT* dd,
char* data,
unsigned len)

The SaDynDataMove function accepts the following parameters:


Table 124. SaDynDataMove Parameters

Parameters Usage Type Description

dd in out, use Dynamic data object.

data in, use New data

len in Length of data (if the data is a


string, this length should include
the string terminator)

Return Value

None.

See Also

“SaDynDataMoveRef.”

See “SaCursorColDynData” on page 115 for more information about "Dynamic


Data" (SaDynDataT).

SaDynDataMoveRef
SaDynDataMoveRef moves a data reference to a dynamic dataobject.

SaDynDataMoveRef copies the pointer (address) from the parameter named "data"
to the appropriate field of the parameter named "dd". The caller must guarantee
that the input data is alive as long as the dynamic data object refers to that data.

Note: This function copies only the reference, not the data. To copy the data rather
than just the reference, see “SaDynDataMove” on page 147.

Typically, the functions SaDynDataMove and SaDynDataAppend are used to set


and modify the data value inside the dynamic data object. More memory will be
automatically allocated when necessary and all the associated memory will be
automatically deallocated when the dynamic data object is disposed of using
SaDynDataFree. The user can access the data or the length using the respective
functions SaDynDataGetData and SaDynDataGetLen.

The use of SaDynDataMove and SaDynDataAppend may not be feasible when the
data already exists completely in a memory buffer. In addition to increasing the

148 IBM solidDB: Programmer Guide


memory usage by keeping two copies of the same data, the overhead of the
memory copy may be significant if the buffers are large. Therefore, it may be better
to directly assign the data pointer by using SaDynDataMoveRef (rather than
copying by using SaDynDataMove). In this case, the user may modify or deallocate
the memory buffer only after the dynamic data object itself has been freed.

Synopsis
void SA_EXPORT_H SaDynDataMoveRef(
SaDynDataT* dd,
char* data,
unsigned len)

The SaDynDataMoveRef function accepts the following parameters:


Table 125. SaDynDataMoveRef Parameters

Parameters Usage Type Description

dd in out, use Dynamic data object

data in, hold Data

len in Length of data (if the data is a


string, this length should include
the string terminator)

Return Value

None

See Also

“SaDynDataMove” on page 147.

See “SaCursorColDynData” on page 115 for a more detailed discussion of


"Dynamic Data" (SaDynDataT).

SaDynStrAppend
SaDynStrAppend appends another string at the end of a dynamic string.

Synopsis
void SA_EXPORT_H SaDynStrAppend(
SaDynStrT* p_ds,
char* str)

The SaDynStrAppend function accepts the following parameters:


Table 126. SaDynStrAppend parameters

Parameters Usage Type Description

p_ds out Dynamic string

str in, use String that is appended at


p_ds

4 Using solidDB SA 149


Return Value

None.

SaDynStrCreate
SaDynStrCreate creates (initializes) a new dynamic string object.

Synopsis
SaDynStrT SA_EXPORT_H SaDynStrCreate(void)

SaDynDataGetData accepts no parameters.

Return Value
Table 127. SaDynStrCreate Return Value

Return Usage Type Description

give Dynamic string object initialized with empty


data. Returns NULL if running out of
memory.

SaDynStrFree
SaDynStrFree frees the SaDynStrT variable.

In search operations, the column data is stored to the SaDynStrT variable using
function SaDynStrMove, which overwrites the old data. The user is responsible for
releasing the SaDynStrT variable after the search ends using function
SaDynStrFree.

Synopsis
void SA_EXPORT_H SaDynStrFree(
SaDynStrT* p_ds)

The SaDynStrFree function accepts the following parameters:


Table 128. SaDynStrFree parameters

Parameters Usage Type Description

p_ds in, take Dynamic string.

Note: Because the function deallocates the memory, the pointer p_ds is no longer
valid after the function call and thus the usage type is "take".

Return Value

None.

SaDynStrMove
SaDynStrMove copies the value of the string (the second parameter) to the
SaDynStrT (the first parameter).

150 IBM solidDB: Programmer Guide


SaDynStrMove copies the string, not the pointer.

The SaDynStrT must be initialized with SaDynStrCreate before SaDynStrT is set


with SaDynStrMove.

CAUTION:
Do not copy a SaDynStrT to another SaDynStrT (for example with memcpy).
This would result in two SaDynStrT pointers pointing at the same allocated
area.

Synopsis
void SA_EXPORT_H SaDynStrMove(
SaDynStrT* p_ds,
char* str)

The SaDynStrMove function accepts the following parameters:


Table 129. SaDynStrMove Parameters

Parameters Usage Type Description

p_ds out Pointer to a dynamic string


variable.

str in, use New value of a dynamic string.

Return Value

None.

SaErrorInfo
SaErrorInfo returns error information from the last operation in a server
connection.

Cursor errors cannot be checked with this function; instead function


SaCursorErrorInfo must be used.

Synopsis
bool SA_EXPORT_H SaErrorInfo(
SaConnectT* scon,
char** errstr,
int* errcode)

The SaErrorInfo function accepts the following parameters:


Table 130. SaErrorInfo Parameters

Parameters Usage Type Description

scon use Pointer to a connection object.

errstr out, ref If there was an error, and if this parameter is non-NULL,
then a pointer to a local copy of an error string is stored
into *errstr.

4 Using solidDB SA 151


Table 130. SaErrorInfo Parameters (continued)

Parameters Usage Type Description

errcode out If there was an error, and if this parameter is non-NULL,


then an error code is stored into *errcode.

Return Value

TRUE There was an error, so errstr and errcode were updated.

FALSE There were no errors, so errstr and errcode were not updated.

SaGlobalInit
SaGlobalInit performs some global initialization in the SA system.

This function must be called before any other SA function except SaConnect. If the
SaConnect function is called before any other SA function, then you do not need to
call SaGlobalInit because SaConnect will call it for you.

Synopsis
void SA_EXPORT_H SaGlobalInit(void)

SaGlobalInit accepts no parameters.

Return Value

None.

SaSetDateFormat
SaSetDateFormat defines default date format.

For explanation of the possible date formats, see “SaDateToAsciiz” on page 137.

Synopsis
SaRetT SA_EXPORT_H SaSetDateFormat(
SaConnectT* scon,
char* dateformat)

The SaSetDateFormat function accepts the following parameters:


Table 131. SaSetDateFormat Parameters

Parameters Usage Type Description

scon in, out, use Pointer to a connection


object.

dateformat in, use Default date format for


connection.

Note: The usage type includes "out" because the scon parameter is modified by
this function call.

152 IBM solidDB: Programmer Guide


Return Value

SA_RC_SUCC if success.

SA_ERR_COMERROR if the connection to the server is broken.

See Also

For explanation of the possible date, time, and timestamp formats, see
“SaDateToAsciiz” on page 137.

SaSetSortBufSize
SaSetSortBufSize sets the amount of memory that a connection uses for local sorts
(sorts that are done on the client side by the SA library).

Synopsis
SaRetT SA_EXPORT_H SaSetSortBufSize(
SaConnectT* scon,
unsigned long size)

The SaSetSortBufSize function accepts the following parameters:


Table 132. SaSetSortBufSize Parameters

Parameters Usage Type Description

scon in, out, use Pointer to a connection


object.

size in Memory buffer size in bytes.

Note: The usage type includes "out" because the scon parameter is modified by
this function call.

Return Value

SA_RC_SUCC when OK or SA_ERR_FAILED when specified memory size was too


small (< 10KB)

SaSetSortMaxFiles
SaSetSortMaxFiles sets the maximum number of files that the connection uses for
local sorts (sorts that are done on the client side by the SA library).

Synopsis
SaRetT SA_EXPORT_H SaSetSortMaxFiles(
SaConnectT* scon,
unsigned int nfiles)

The SaSetSortMaxFiles function accepts the following parameters:

4 Using solidDB SA 153


Table 133. SaSetSortMaxFiles parameters

Parameters Usage Type Description

scon in, out, use Pointer to a connection


object.

nfiles in Maximum number of files

Note: The usage type includes "out" because the scon parameter is modified by
this function call.

Return Value

SA_RC_SUCC when OK or SA_ERR_FAILED when specified number of files is too


small (< 3).

SaSetTimeFormat
SaSetTimeFormat defines the default time format.

For an explanation of the possible formats, see the time portion documentation of
SaDateSetAsciiz in “SaDateSetAsciiz” on page 135.

Synopsis
SaRetT SA_EXPORT_H SaSetTimeFormat(
SaConnectT* scon,
char* timeformat)

The SaSetTimeFormat function accepts the following parameters:


Table 134. SaSetTimeFormat Parameters

Parameters Usage Type Description

scon in, out, use Pointer to a connection


object.

timeformat in Default time format for


connection.

Note: The usage type of scon includes "out" because the scon parameter is
modified by this function call.

Return Value

SA_RC_SUCC

SA_ERR_COMERROR if the connection to the server is broken.

See Also

For an explanation of the possible date, time, and timestamp formats, see
“SaDateSetAsciiz” on page 135.

154 IBM solidDB: Programmer Guide


SaSetTimestampFormat
SaSetTimestampFormat defines the default timestamp format.

For an explanation of the possible date, time, and timestamp formats, see
“SaDateSetAsciiz” on page 135.

Synopsis
SaRetT SA_EXPORT_H SaSetTimestampFormat(
SaConnectT* scon,
char* timestampformat)

The SaSetTimestampFormat function accepts the following parameters:


Table 135. SaSetTimestampFormat parameters

Parameters Usage Type Description

scon in, out, use Pointer to a connection


object.

timestampformat in Default timestamp format for


connection.

Return Value

SA_RC_SUCC

See Also

For an explanation of the possible date, time, and timestamp formats, see
“SaDateSetAsciiz” on page 135.

SaSQLExecDirect
SaSQLExecDirect allows you to execute simple SQL statements such as CREATE
TABLE, DROP TABLE, INSERT, and DELETE.

You cannot do SELECT operations because it is not possible to fetch the data.

Synopsis
SaRetT SA_EXPORT_H SaSQLExecDirect(SaConnectT* scon,
char *sqlstr)

The SaSQLExecDirect function accepts the following parameters:


Table 136. SaSQLExecDirect Parameters

Parameters Usage Type Description

scon in, use Pointer to a connection


object.

sqlstr in, use Pointer to a string containing


the SQL statement to
execute.

4 Using solidDB SA 155


Return Value

SA_RC_SUCC

The possible error codes are as follows:


v 15001: SAP_ERR_SYNTAXERROR_SD. Syntax error: <error>, <line>.
v 15002: SAP_ERR_ILLCOLNAME_S. Illegal column name <name>.
v 15003: SAP_ERR_TOOMANYPARAMS. Too many parameters for string
constraints.
v 15004: SAP_ERR_TOOFEWPARAMS. Too few parameters for string constraints.

SaTransBegin
SaTransBegin starts a new transaction. After this call, all select, insert, update and
delete operations are executed in the same transaction, and the changes are not
visible in the database until SaTransCommit is called.

Without the SaTransBegin call, the server is in autocommit mode by default and
therefore each select, insert, update, and delete operation is executed in a separate
transaction. No explicit commit (SaTransCommit) is required when in autocommit
mode.

The transaction is run in a mode where write operations are validated for lost
updates and unique errors.

Synopsis
void SA_EXPORT_H SaTransBegin(SaConnectT* scon)

The SaTransBegin function accepts the following parameters:


Table 137. SaTransBegin parameters

Parameters Usage Type Description

scon in, use Pointer to a connection


object.

Return Value

None.

SaTransCommit
SaTransCommit commits the current transaction started by SaTransBegin.

After calling this function, all changes are made persistent in the database. After
the current transaction is completed, the database server returns to autocommit
mode until the next call to SaTransBegin.

Synopsis
SaRetT SA_EXPORT_H SaTransCommit(SaConnectT* scon)

The SaTransCommit function accepts the following parameters:

156 IBM solidDB: Programmer Guide


Table 138. SaTransCommit Parameters

Parameters Usage Type Description

scon in, use Pointer to a connection object

Return Value

SA_RC_SUCC or error code.

SaTransRollback
SaTransRollback rolls back the current transaction started by SaTransBegin. No
changes are made to the database.

After the current transaction is completed, the database server returns to


autocommit mode until the next call to SaTransBegin.

Synopsis
SaRetT SA_EXPORT_H SaTransRollback(SaConnectT* scon)

The SaTransRollback function accepts the following parameters:


Table 139. SaTransRollback Parameters

Parameters Usage Type Description

scon in, use Pointer to a connection object

Return Value

SA_RC_SUCC or error code.

SaUserId
SaUserID returns current user id of a connection.

Synopsis
int SA_EXPORT_H SaUserId(SaConnectT* scon)

The SaUserId function accepts the following parameters:


Table 140. SaUserId Parameters

Parameters Usage Type Description

scon in, use Pointer to a connection object

Return Value

User id in the server.

4 Using solidDB SA 157


158 IBM solidDB: Programmer Guide
5 Using Unicode
solidDB supports the Unicode standard, providing the capability to encode
characters used in the major languages of the world. To use Unicode encoded data,
you do not need to use any non-standard or solidDB-specific implementations for
application development; standard ODBC API or JDBC API can be used, as well as
solidDB tools. solidDB also supports heterogeneous multi-client environments
where each application can be set to use different encoding.

Unicode database modes

Starting from version 6.5, the solidDB databases can be created in two modes:
Unicode mode or partial Unicode mode. This database mode is based on the
encoding of character data types (CHAR, VARCHAR and so on) in the solidDB
server. Wide character data types (WCHAR, WVARCHAR and so on) are Unicode
encoded in both modes.
v Unicode mode
In the Unicode mode, the internal representation for character data types is
UTF-8.
The internal representation for wide character data types is UTF-16.
v partial Unicode mode
In the partial Unicode mode, the internal representation for character data types
uses no particular encoding; instead, the data is stored in byte strings with the
assumption that user applications are aware of this and handle the conversion as
necessary.
The internal representation for wide character data types is UTF-16.
The databases created with solidDB version 6.3 or earlier are of the partial
Unicode type.

Important: The default database mode in 6.5 is partial Unicode.

Note: Unicode applications can be built on both Unicode and partial Unicode
databases. However, the instructions in this section assume that the Unicode
support is based on the Unicode database mode.

Key features of solidDB Unicode databases


v Storing and retrieving of Unicode data
The internal of representation of Unicode data is based on UTF-8 and UTF-16
encoding. Data in wide character column types is represented internally in
UTF-16 and data in character column types is represented in UTF-8.
This means that both single and multi-byte data can be stored in character
column types; if mainly multi-byte data is expected, you can optimize
space-efficiency by choosing to store the multi-byte data into wide character
column types.
v No restrictions on the encoding used in the applications
solidDB ODBC/JDBC drivers handle the conversion of data between the
application encoding and the UTF-8/UTF-16 format in the solidDB server.
v Standard ODBC API and JDBC API available for application development

159
There are no non-standard or solidDB-specific requirements for application
development; standard ODBC API or JDBC API can be used.

What is Unicode?
The Unicode Standard is the universal character representation standard for text in
computer processing. Unicode provides a consistent way of encoding multilingual
plain text making it easier to exchange text files internationally.

The Unicode Standard defines code points (unique numbers) for characters used in
the major languages written today. This includes punctuation marks, diacritics,
mathematical symbols, technical symbols, arrows, dingbats, and so on. In all, the
Unicode Standard provides codes for over 100,000 characters from the world's
alphabets, ideograph sets, and symbol collections, including classical and historical
texts of many written languages. The characters can be represented in different
encoding forms, such as UTF-8 and UTF-16.

The Unicode Standard is fully compatible with the International Standard ISO/IEC
10646; it contains all the same characters and code points as ISO/IEC 10646. This
code-for-code identity is true for all encoded characters in the two standards,
including the East Asian (Han) ideographic characters. The Unicode Standard also
provides additional information about the characters and their use. Any
implementation that conforms to Unicode also conforms to ISO/IEC 10646.

Encoding forms

Unicode characters are represented in one of three encoding forms: a 32-bit form
(UTF-32), a 16-bit form (UTF-16), and an 8-bit form (UTF-8). These character
encoding standards define not only the identity of each character and its numeric
value (code position), but also how this value is represented in bits.

Starting from version 6.5, solidDB can be configured to use the UTF-8 encoding for
representing character data and UTF-16 encoding for wide character data. The
database mode is controlled with the parameter [Link].

If a database is created in Unicode mode ([Link]=UTF8),


the following applies:
v Data in wide character column types is represented internally in UTF-16.
v Data in character column types is represented in UTF-8.

If a database is created in the partial Unicode mode


([Link]=Raw), the following applies
v Data in wide character column types is represented internally in UTF-16.
v Data in character column types is not encoded in any particular encoding;
instead, the data is stored in byte strings, with the assumption that user
applications are aware of this and handle the conversion as necessary.

The UTF-8 and UTF-16 encodings are essentially ways of turning the encoding into
the actual bits that are used in implementation; UTF-8 and UTF-16 encodings share
the same character set, but the data size of each character differs.
v UTF-16
UTF-16 assumes 16-bit characters and allows for a certain range of characters to
be used as an extension mechanism in order to access an additional million
characters using 16-bit character pairs.

160 IBM solidDB: Programmer Guide


v UTF-8
UTF-8 is a way of transforming all Unicode characters into a variable length
encoding of bytes. It has the advantages that the Unicode characters
corresponding to the familiar ASCII set end up having the same byte values as
ASCII, and that Unicode characters transformed into UTF-8 can be used with
much existing software without extensive software rewrites.
The Unicode Consortium also endorses the use of UTF-8 as a way of
implementing the Unicode standard. Any Unicode character expressed in the
16-bit UTF-16 form can be converted to the UTF-8 form and back without loss of
information.

Designing Unicode databases


This section contains information on how to setup solidDB databases for use with
Unicode.

Note: Unicode applications can be built on both Unicode and partial Unicode
databases. However, the instructions in this section assume that the Unicode
support is based on the Unicode database mode.

Creating Unicode databases

The solidDB database mode is controlled with the parameter


[Link].
v Unicode mode: [Link]=UTF8
When the InternalCharEncoding is set to UTF8, the internal representation for
character data types is UTF-8. Both character data types and wide character data
types are converted between the solidDB server and the application.
v partial Unicode mode: [Link]=Raw
When the InternalCharEncoding is set to Raw, the internal representation for
character data types uses no particular encoding; instead, the data is stored in
byte strings with the assumption that user applications are aware of this and
handled the conversion as necessary. Wide character data types are converted
between the solidDB server and the application.
The databases created with solidDB version 6.3 or earlier are of the partial
Unicode type.

Important: The database mode must be defined when the database is created and
it cannot be changed later.

If the database already exists in either mode and the database mode contradicts the
value of the parameter, the server startup fails with the following error message in
the [Link]:
Parameter [Link] contradicts the existing database mode

Determining which data types to use in Unicode databases

Both character and wide character data types can be used to store Unicode data in
Unicode databases. If mainly multi-byte data is expected, you can optimize
space-efficiency by choosing to store the multi-byte data into wide character
column types. This is because even though UTF-8 and UTF-16 encodings share the
same character set, the data size of each character differs.

5 Using Unicode 161


v Data in wide character column types (WCHAR/WVARCHAR/LONG
WVARCHAR) is represented internally in UTF-16: each character is represented
in two or four bytes.
– Characters in the Basic Multilingual Plane (BMP): two bytes
– Characters outside the BMP (surrogate characters): four bytes
v Data in character column types (CHAR/VARCHAR/LONG VARCHAR) is
represented in UTF-8: each character is represented in one to four bytes.
The size depends on the code point:
Simplified example:
– ASCII characters: one byte
– Cyrillic, Arabic, Hebrew, Latin-1 supplement and so on characters: two bytes
– Asian characters/rest of BMP characters: three bytes
– Characters outside the BMP (surrogate characters): four bytes

For example, Asian languages are stored more efficiently on wide character data
types (UTF-16) since most characters are part of BMP, which requires two bytes.
European languages are stored more efficiently on character data types (UTF-8)
since most common characters are represented in one byte.

Wide character data requires also less processing; using wide character data types
may improve performance.

The Unicode data types are interoperable; because UTF-16 and UTF-8 share the
same character set, there is no risk of data loss when using either data type. All
string operations are possible between character and wide character data types
with implicit type conversions.

Creating columns for storing Unicode data

In order to start storing Unicode data in a Unicode database, tables with Unicode
data columns need to be created first as follows:
CREATE TABLE customer1 (c_id INTEGER, c_name VARCHAR,...)
CREATE TABLE customer2 (c_id INTEGER, c_name WVARCHAR,...)

Ordering data columns (collation)

The character data columns are ordered based on the binary values of the UTF-8
and wide character data columns on the UTF-16 format (using most significant
byte order). If the binary order is different than what the national language users
expect, you need to provide a separate column to store the correct ordering
information.

Using Unicode in database entity names

It is possible to name database entities such as tables, columns, and procedures


with Unicode strings simply by enclosing the Unicode names with double quotes
in all the SQL statements.

solidDB tools can handle Unicode strings according to the default locale of the
environment or according to a specified locale.

For more details, see “Using solidDB tools with Unicode” on page 163.

162 IBM solidDB: Programmer Guide


Using Unicode in user names and passwords

User names and passwords can also be Unicode strings. However, to avoid access
problems from different tools, the original database administrator account
information must be given as pure ASCII strings.

Using Unicode in file names

Unicode strings cannot be used in any file names.

Using solidDB tools with Unicode


This section contains information about how to use the solidDB tools with Unicode
and partial Unicode databases.

The following solidDB tools can be used to output and import data in the system
default locale or a specified locale in both Unicode and partial Unicode databases.
v solidDB SQL Editor (solsql)
v solidDB Data Dictionary (soldd)
v solidDB Export (solexp)
v solidDB Speed Loader (solloado)

solidDB Remote Control (solcon) does not support conversions of data to UTF-8.
For example, if an error message that is output to solcon contains Unicode
encoded data, it is not displayed correctly in the console.

The locale to be used in conversions is defined with the command line options
when starting the tool.

Important:
v The solidDB tools use the solidDB ODBC API 3.5.1; this means that if the
binding method for character data types is defined with the server-side
[Link] or client-side [Link] parameters,
this setting also impacts the behavior of the solidDB tools.
v The Unicode and partial Unicode databases behave differently in reference to
conversions of CHAR and WCHAR data types:
– Unicode databases
Both CHAR and WCHAR data types are converted between the
UTF-8/UTF-16 format in solidDB and the locale/codepage defined with the
chosen binding method.
– partial Unicode databases
CHAR data types are not converted; instead, they are handled in the raw
(binary) format that is used to store CHAR data in partial Unicode databases.
WCHAR data types are converted between the UTF-16 format in solidDB and
the locale/codepage defined with the chosen binding method.

5 Using Unicode 163


Table 141. Command line options for solidDB tools for partial Unicode and Unicode
databases
Option Description
No option/Factory The console locale setting is used, unless overridden with the
setting server-side or client-side parameters in the [Link] file.
Note: If the server-side [Link] or client-side
[Link] parameter is set to UTF8, the locale of the
console must support UTF-8.
-m The console locale setting is used, despite the server-side or
client-side parameters in the [Link] file.
-M<locale_name> The locale console setting is overridden with the locale defined
with <locale_name>. The <locale_name> depends on the operating
system.

For example, in Linux environments, the locale name for the code
page GB18030 in Chinese/China is zh_CN.gb18030.

In Windows environments, the locale name for Latin1 code page


in Finnish/Finland is fin_fin.1252.
-u Input/output is forced to UTF-8.

Note: If the server-side or client-side parameters in the [Link] file are set to use
'Raw' binding, you should always use the -m, -M or -u option to override the
[Link] settings.

Compatibility between Unicode and partial Unicode databases


If a database has been created in Unicode mode, it cannot be changed to partial
Unicode mode, and vice versa. If you need to convert a partial Unicode database
to a Unicode (or vice versa), you can use the solidDB tools to export and reload
your database.

If the database already exists in either mode and the database mode contradicts the
value of the parameter, the server startup fails with the following error message in
[Link].
Parameter [Link] contradicts the existing database mode

Converting partial Unicode databases to Unicode


To convert a partial Unicode database to a Unicode database, use the solidDB tools
to export and reload your database.

Before you begin


v Create a backup of your database.
v Verify the locale/codepage that is used in the application side for encoding data
in CHAR data type columns in the partial Unicode database.
During the export phase, the data in CHAR data type columns is not converted
by solidDB tools; instead, it is output as such. This means that the underlying
locale/codepage for CHAR data types becomes the locale/codepage format for
the output file. To enable the output files to contain data in a single
locale/codepage, solidDB must be able to convert the data in the WCHAR data
type columns from UTF-16 into the exact same locale/codepage format as the
CHAR data.

164 IBM solidDB: Programmer Guide


In the import phase, the solidDB tools convert the data from the
locale/codepage format of the output file into the UTF-8 (CHAR) and UTF-16
(WCHAR) encoding used in Unicode databases.

About this task

In this procedure, the following setup is used as an example:


v The server name is solidDB and the protocol used for connections is TCP/IP,
using port 1964 (network name is "tcpip 1964").
v The partial Unicode database has been created with the username "dbadmin"
and password "password".
v CHAR data types in the partial Unicode database are encoded in the application
side with the locale zh_CN.gb18030 (Chinese/China and code page GB18030).

Tip: If you have your database creation scripts available, you can use them to
create the new database table definitions, instead of using soldd and solsql for
exporting and importing them.

Procedure
1. Extract data definitions with solidDB Data Dictionary (soldd).
Use the following command to extract an SQL script containing definitions for
all tables, views, triggers, indexes, procedures, sequences, and events.
soldd -Mzh_CN.gb18030 "tcpip 1964" dbadmin password
The default file name [Link] is used.

Note: User and role definitions are not listed for security reasons. If the
database contains users or roles, add CREATE statements for them to the
extracted SQL file manually.

Important: To preserve referential integrity, you may need to reorganize the


table definition statements to ensure that the referenced tables are created
before the referencing tables.
2. Extract data from you database with solidDB Export (solexp).
Use the following command to extract the control and data files for all tables.
solexp -Mzh_CN.gb18030 "tcpip 1964" dbadmin password *
This export creates control files (<table_name>.ctr) and data files
(<table_name>.dat) for each table. The default file name is the same as the
exported table name.
3. Create a new Unicode database.
a. Set the [Link] parameter to UTF8.
[General]
InternalCharEncoding=UTF8
b. Create a new database by starting solidDB in the working directory for the
new Unicode database.
4. Import data definitions into the new database using the solidDB SQL Editor
(solsql).
Use the following command to execute the SQL script created by solidDB Data
Dictionary (soldd).
solsql -[Link] -Mzh_CN.gb18030 "tcpip 1964" dbadmin password

5 Using Unicode 165


5. Load the data into the new database using the solidDB Speed Loader
(solloado).
For each table, use the following command to load data into the new database:
solloado -Mzh_CN.gb18030 "tcpip 1964" dbadmin password <table_name>.ctr
Related topics
v Using solidDB management tools in the IBM solidDB Administrator Guide

Developing applications for Unicode


This section contains information on how to design your applications for use with
solidDB databases in Unicode mode.

Supported interfaces
v ODBC
The solidDB ODBC Driver is Unicode compliant; it conforms to the Microsoft
ODBC 3.51 standard.

Note: solidDB provides two versions of the ODBC driver, one for Unicode and
one for ASCII. The Unicode version is a superset of the ASCII version; you can
use it with either Unicode or ASCII character sets.
v JDBC
Unicode is supported in the solidDB JDBC Driver which is a solidDB
implementation of the JDBC 2.0 standard.
As Java uses natively Unicode strings, supporting Unicode means primarily that
when accessing character data in solidDB, no data type conversions are
necessary. Additionally, JDBC ResultSet Class methods getUnicodeStream and
setUnicodeStream are supported for handling large Unicode texts stored in
solidDB.

Multi-client environments with different locale settings

In Unicode databases, the solidDB ODBC and JDBC drivers handle the conversion
of data between the application encoding and the UTF-8/UTF-16 format in the
solidDB server.

In ODBC environments, the conversions can be set to expect the application


default locale or a user-defined locale for the encoding in the application buffer.
This is controlled with server-side [Link] and client-side
[Link] configuration parameters.

SQL string functions

SQL string functions work as expected. Conversions are provided implicitly, when
necessary. If either of the operands is of wide character type, the result is always of
wide character type.

As of 6.5 Fix Pack 10, the functions UPPER() and LOWER() perform the uppercase
or lowercase conversions for all Unicode characters in Unicode databases
([Link]=UTF8). In versions prior to 6.5 Fix Pack 10,
conversions are supported only when the characters are part of Latin 1 code page.
If the Unicode character cannot be converted to uppercase or lowercase, the input
string is returned as it is.

166 IBM solidDB: Programmer Guide


Character padding

The [Link]=yes parameter setting is not effective in Unicode databases;


blank characters in CHAR values are always discarded.

ODBC applications and Unicode databases


In ODBC environments, the solidDB ODBC driver handles the conversion of data
between the encoding used in the application (client) and the UTF-8/UTF-16
format in the solidDB Unicode database. The binding of character data can be set
for all clients using the server-side parameter [Link] or per
client using the client-side parameter [Link]. In both cases, the
standard C type identifier SQL_C_CHAR is used.

For binding of character data, you can set the ODBC driver to use one of the
following methods:
v the current client locale encoding
v specific encoding as defined with a locale name
v no encoding
v UTF-8 encoding

Two use cases are supported for all methods:


v The same binding method is set for all clients using the server-side parameter
ODBCDefaultCharBinding.
[Srv]
ODBCDefaultCharBinding=raw|locale|locale:|locale:<locale name>|UTF8
v The binding method is set per client by using the client-side parameter
ODBCCharBinding.
[Client]
ODBCCharBinding=raw|locale|locale:<locale name>
The ODBCCharBinding parameter overrides the server-side settings set by
ODBCDefaultCharBinding.

The factory value for both is locale:.


v raw — no data conversion takes place between solidDB server and the client
The value raw can be used when you want your database to use the binding
used in the 6.3 or earlier versions of solidDB.
v locale — the current client locale setting is used, also if set by the client system
v locale: — the current client setting are overridden with a default locale set of
the client system
The driver calls setlocale() with an empty string which effectively searches for
the locale setting set in the system.
For example, in Linux environments, the environmental variable LC_CTYPE is
checked first and if that is not defined, the environmental variable LANG is
searched.
v locale:<locale name> — the current client systems setting are overridden and
the given locale is used
The convention for <locale name> depends on the operating system.
For example, in Linux environments, the locale name for the code page GB18030
in Chinese/China is zh_CN.gb18030. In Windows environments, the locale name
for Latin1 code page in Finnish/Finland is fin_fin.1252.

5 Using Unicode 167


v UTF8 — UTF-8 binding is enforced regardless of the locale set in the client-side
system

Note:
v If the value in [Link] is other than locale, it overrides
any current system locale setting for all clients.
v If the value in [Link] is other than locale, it overrides both
the server side value (if set) and the current system locale setting.

Using the current client locale encoding (locale)

To use the current client locale encoding:


1. Configure the parameter setting:
v All clients use the same binding method (server-side parameter)
In the server-side [Link], section [Server], set the
ODBCDefaultCharBinding parameter.
[Srv]
ODBCDefaultCharBinding=locale
v Some or all clients require different binding methods (client-side
parameter)
In the client-side [Link], section [Client], set the ODBCCharBinding
parameter.
[Client]
ODBCCharBinding=locale
The client-side parameter overrides the server-side settings.
2. Set application to call setlocale().

Using a specific locale encoding (locale:<locale_name>)

To use a specific locale encoding:

Define the locale in [Link]:


v All clients use the same binding method (server-side parameter)
In the server-side [Link], section [Server], set the ODBCDefaultCharBinding
parameter.
[Srv]
ODBCDefaultCharBinding=locace:<locale name>
For example in Linux environments:
[Srv]
ODBCDefaultCharBinding=locale:zh_CN.gb18030
v Some or all clients require different binding methods (client-side parameter)
In the client-side [Link], section [Client], set the ODBCCharBinding
parameter.
[Client]
ODBCCharBinding=locale:<locale name>
The client-side parameter overrides the server-side settings.
For example in Linux environments:
[Client]
ODBCCharBinding=locale:zh_CN.gb18030

Note: Setting a specific locale overrides the application settings defined with
setlocale().

168 IBM solidDB: Programmer Guide


Example 1

All clients use the current locale of the client. Different clients can use different
code pages.

The server-side [Link] is used:


[Srv]
ODBCDefaultCharBinding=locale

Example 2

Some clients use the current locale of the client, some clients use Latin1 code page:

The server-side [Link] is used:


[Srv]
ODBCDefaultCharBinding=locale

In those clients that require the Latin1 code page, the client-side [Link] is used:
[Client]
ODBCCharBinding=locale:fin_fin.1252

JDBC applications and Unicode databases


In JDBC environments, the solidDB JDBC driver handles the conversion of data
between the encoding used in the application (client) and the UTF-8/UTF-16
format in the Unicode database. You do not need to make any solidDB specific
settings to use Unicode with JDBC.

5 Using Unicode 169


170 IBM solidDB: Programmer Guide
6 Using Transaction Log Reader
The solidDB Transaction Log Reader is a solution that makes it possible to read log
records from the solidDB transaction log transaction by transaction. Using the Log
Reader interface, you can, for example, write an application that listens to and
displays log traffic in the solidDB server.

The Log Reader is based on a read-only system table called SYS_LOG where each
row corresponds to a single log entry. The SYS_LOG table is a virtual table: when
the Log Reader receives an SQL request for the SYS_LOG table, the appropriate
result set is generated dynamically from the internal log structures. Each log read
can be started from different log record.

For each entry in the transaction log, the SYS_LOG table contains data for
identifying the log record, the type of transaction and statement executed, as well
as the row with the changed data itself.

The SYS_LOG table can be accessed with ODBC and JDBC drivers using SQL
statements. For example, an application could be written to read the solidDB
transaction log and extract records pertaining to SQL DML statements. The
application could then reconstruct the statements into plain text SQL strings and
print them to a desired type of output.

Applications can read the SYS_LOG table both locally and remotely. Several
applications can read the SYS_LOG table concurrently without interference.

A sample application that demonstrates the use of the Log Reader interface is
included in the solidDB package, available in samples/logreader directory.

For a detailed description of the SYS_LOG table, see the section SYS_LOG in the
Appendix Database virtual tables in the IBM solidDB SQL Guide.

Considerations for developing applications with Log Reader


Supported table types
v Both in-memory and disk-based tables are supported.
v Transient and temporary tables are not supported.
Transient and temporary tables are not logged and thus data in them is not
returned through the Log Reader.

Supported database operations


v Only committed transactions are returned by the Log Reader.
All events for one transaction are returned at once. Each transaction is returned
in full at the time of commit. Log Reader returns full committed transactions in
the order they are committed to the log. Overlapping transactions are returned
transaction by transaction.
v Triggers are supported.
Operations in the trigger action part are logged as normal user operations. Write
operations in triggers are logged when they are executed: before-triggers are
logged before user data operation, and after-triggers are logged after user data
operation.

171
v Cascading actions are supported.
Operations resulted from cascading referential actions are logged as normal user
operations. Cascading operations are logged after the actual user data operation.
v DDL operations are supported.
For DDL operations, the Log Reader will return a special
DBE_LOGREADER_LOG_REC_DDL record that contains the original SQL
statement.

Catchup and live data modes


When a log read is started from SYS_LOG, the read goes first into catchup mode.
The catchup mode means that the log read start position is searched from the log
and the read is then started from that position. When log read reaches the end of
the current log, it starts to read live data. In live mode transactions are returned as
they are executed.

When several Log Readers are used, each Log Reader has its own data mode.

In live data mode the cursor returns every second even if there is no data
available. In that case, the FLAGS field in the SYS_LOG table is zero.

Primary keys

Primary key is not mandatory for the tables. System generated internal and hidden
primary key value is not returned through the Log Reader.

When designing your database, you must decide how rows are identified if
primary key is not defined.

High Availability

High Availability (HotStandby) is supported so that the log file contents and log
address are compatible between Primary and Secondary servers. If the log is read
from Primary server and there is a failover, a new read from SYS_LOG can be
started using the last LOGADDR received from the old Primary server.

The log can be read also from the Secondary server. This can useful, for example,
for load balancing reasons.

Throttling

If the server can generate log records faster than the client can read, throttling can
occur. This means that user transactions writing to the server are slowed down to
make sure the Log Readers are not too much behind the live data. The
[Link] parameter can be used to control the buffering after which
throttling can occur.

Applications that start a read but then stop reading can also cause the server to
stop.

Log maximum size

If the application using the Log Reader is stopped or terminated for longer time, a
the log maximum size may be reached. In such a case, no error message is

172 IBM solidDB: Programmer Guide


produced. Also, the position stored by the application for catchup is not available
any more and the effort to catchup fails.

Access rights

Administrator rights are needed to access the SYS_LOG table, to add tables to a
partition or to remove tables from a partition.

Stopping the Log Reader

The log reading can be stopped at any time. No data is lost even of some
undelivered data are left in the log.

The log reading may be resumed without any loss of information if the last read
position is known. By using the current log position, the application will be able to
continue reading the log, without any loss of data, upon the next SYS_LOG query.
If the SYS_LOG table is accessed without specifying the log position, the reading
starts from the live data.

The Log Reader can be stopped in the solidDB server with the ADMIN COMMAND
’LOGREADER STOP’ command.

Configuring the Log Reader


The Log Reader is configured with the server-side configuration parameters in the
LogReader section of the [Link] configuration file.

About this task

Important: The LogReaderEnabled, MaxSpace, and MaxLogSize parameters are also


used with solidDB Universal Cache and InfoSphere® CDC Replication.

Procedure
v Enable the Log Reader by setting LogReaderEnabled to 'yes'.
This enables the Log Reader, allowing reads from SYS_LOG. The transaction
logging mode is also more verbose.
v As necessary for your environment, set the following parameters:
– Set MaxSpace value to define the maximum number of log records buffered
into memory before throttling occurs.
– Set MaxLogSize value to define the maximum size of the log available for a
catchup.
When the log reaches the defined size, old log data is deleted and catchup is
not possible from the older LOGADDR log positions.
– Set MaxMemLogSize value to define the maximum size of the Log Reader logfile
in memory, when logging is not enabled ([Link]=No).

Example
[LogReader]
LogReaderEnabled=yes ;Default: no
;
;MaxLogSize=100000 ;default: 10240 (MB)
; The amount of the log files (in MB) that will be always maintained
; for the sake of a possible catchup. The size should be adjusted to
; the biggest size of a catchup that is reasonable. The space declared
; is always fully occupied.

6 Using Transaction Log Reader 173


;
MaxSpace=500000 ;default:100000
; The size of the in-memory log reader buffer used in throttling,
; in records. When the buffer fills up, the throttling (slowing down)
; is enacted. If the buffer is used, the size adds up to the
: footprint of the solidDB server process.

Reading log data with the Log Reader


The solidDB transaction log can be read with a Log Reader specific SELECT
statement.

About this task

The transaction log can be read by multiple concurrently active SELECT statements
at the same time. Each log read can be started from different log position,
independently from the others.

Tip:

The solidDB package contains a sample application that demonstrates the use of
the Log Reader interface. The sample application is available in the
samples/logreader directory in the solidDB installation directory.

Procedure
1. Read log data from the SYS_LOG table with a SELECT statement.
The basic syntax to read log is:
SELECT RECID, RELID, FLAGS, LOGADDR, DATA FROM SYS_LOG WHERE LOGADDR > ?;
The WHERE condition is allowed only for LOGADDR field. Only constraint that is
allowed is greater than (>). Constraints to other fields will result in an error.
Alternatively, you can start the log read from a specified log position, defined
with the LOGADDR field.
a. Retrieve the current LOGADDR value.
SELECT LOGADDR FROM SYS_LOG LIMIT 1;
For example:
SELECT LOGADDR FROM SYS_LOG LIMIT 1;
LOGADDR
-------
0000000000000001FFFFFFFF0000029500000295
1 rows fetched.
b. Define the LOGADDR in the SELECT statement.
For example:
SELECT RECID,RELID,FLAGS,LOGADDR,DATA FROM SYS_LOG WHERE LOGADDR > ’0000000000000001FFFFFFFF0000029500000295’;

ResultWhen a read is started, the fetch calls will start returning rows. The user
data for the log record is included in the DATA column in binary format.
When no data is available, the server will return empty data in one second
intervals. In such a case, you can issue a new fetch call to see if new data is
available.
For more details on the DATA column and other columns in the SYS_LOG
table, see SYS_LOG table definition in the IBM solidDB SQL Guide.
2. Reconstruct the user data in the rows returned by the Log Reader.

174 IBM solidDB: Programmer Guide


Note: The exact steps for handling the log records depends on the application
design. The following steps are the basic steps that are needed to output the
user data in a format that can be used to process the log records further.
a. Get metadata for the column by querying the solidDB system tables.
For example, in Java environments, the column metadata can be read from
the solidDB system tables using the [Link]() call.
b. Using the metadata, parse the data in the DATA column to produce output
in the format of your choice.
For example, in the sample application (samples/logreader), the log records
are converted into plain text SQL statements.

Partitioning and filtering log records


By default, all the log records generated by any application are returned. If you
only want to access the log records for a subset of the database, you can specify
log reader partitions. A Log Reader partition is a named collection of tables. The
partitions may overlap.

information about the partitions is stored in SYS_FEDT_DB_PARTITION and


SYS_FEDT_TABLE_PARTITION system tables.

Creating and deleting partitions


The Log Reader partitions are be created, modified, and deleted with SQL
statements.

About this task

The partition settings are transactional and persistent.

Procedure
v Creating partitions
Create partitions with the following command:
CREATE LOGREADER PARTITION <partition-name>
v Deleting partitions
Delete (drop) partitions with the following command:
DROP LOGREADER PARTITION <partition-name>
v Modifying partitions
Add or remove tables from a partition with the following command:
ALTER LOGREADER PARTITION <partition-name> {ADD | DROP} TABLE <table-name>

Note: When a table is part of a partition, it cannot be dropped or altered. The


only ALTER statement available is ALTER LOGREADER PARTITION ... DROP
TABLE.

Using partition filters


A session-specific partition filter can be set to read log records only from a specific
partition.

About this task

The setting for the partition filter applies only to the current session and is valid
for all reads from SYS_LOG that are started after the setting. The partition data is

6 Using Transaction Log Reader 175


stored in the SYS_FEDT_DB_PARTITION system table.

Procedure
v Set partition filters with the following statement:
SET LOGREADER PARTITION { <partition-name> | NONE }
When set to NONE (default), all log records are read.
v View the existing partitions in the SYS_FEDT_DB_PARTITION system table with
a SELECT statement.
For example:
SELECT * FROM sys_fedt_db_partition

Setting transaction batches


With transaction batching, multiple transactions from the log can be returned as a
single transaction. Transaction batch sizes are set for a session. If the logged
transactions are being fed into another database, transaction batching can improve
read performance over the network. For example, a number of inserts could be
batched into one transaction so that when the transactions need to be executed in
another database, only one transaction needs to be executed.

About this task

The transaction batch setting applies only to the current session and is valid for all
reads from SYS_LOG that are started after the setting.

Procedure

Set transaction batch size with the following command:


SET LOGREADER BATCH <size>

The default batch size is 1: no batching of transactions is done.

Results

Setting the batch transaction size does not alter the catchup position; the catchup
position can be used to read all transaction in the batch again.

176 IBM solidDB: Programmer Guide


Appendix A. solidDB supported ODBC functions
This topic describes the ODBC functions supported by solidDB.
Table 142. solidDB supported ODBC functions

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

Connecting to a Data Source

SQLAllocEnv (1.0) N/A Deprecated (replaced by N/A


SQLAllocHandle)

SQLAllocConnect (1.0) N/A Deprecated (replaced by N/A


SQLAllocHandle)

SQLAllocHandle (3.0) Returns the list of supported data source Supported ISO 92 ODBC
attributes.
Supported
Returns the list of installed drivers and their
attributes.

SQLConnect (1.0) Establishes connections to a driver and a data Supported ISO 92


source. The connection handle references
storage of all information about the
connection to the data source, including
status, transaction state, and error
information.

SQLDriverConnect (1.0) This function is an alternative to SQLConnect. Supported (including Unicode ODBC
It supports data sources that require more version of this function).
connection information than the three
arguments in SQLConnect, including dialog
boxes to prompt the user for all connection
information, and data sources that are not
defined in the system information.

SQLBrowseConnect (1.0) Returns successive levels of attributes and Not supported ISO 92
attribute values. When all levels have been
enumerated, a connection to the data source
is completed and a complete connection
string is returned. A return of
SQL_SUCCESS_WITH_INFO indicates that all
connection information has been specified
and the application is now connected to the
data source.

SQLGetInfo (1.0) Returns general information about the driver Supported ISO 92
and data source associated with a connection.

177
Table 142. solidDB supported ODBC functions (continued)

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

SQLGetFunctions (1.0) Returns information about whether a driver Supported; this function is ISO 92
supports a specific ODBC function. implemented in the ODBC
Driver Manager. It can also be
implemented in drivers. If a
driver implements
SQLGetFunctions, the Driver
manager calls the function in
the driver. Otherwise, it
executes the function itself. In
the case of solidDB, the
function is implemented in
the driver so that the
application linked to the
driver can also call this
function from the application.

SQLGetTypeInfo (1.0) Returns information about data types Supported ISO 92


supported by the data source. The driver
returns the information in the form of an SQL
result set. The data types are intended for use
in Data Definition Language (DDL)
statements.

Obtaining Information about a Driver and Data Source

SQLDataSources (1.0) Returns information about a data source. Supported; this function is ISO 92
implemented in the ODBC
Driver Manager.

For platforms other than


Windowswhich do not have
the Microsoft ODBC Driver
manager, this function is not
supported.

SQLDrivers (2.0) Lists driver descriptions and driver attribute Supported; this function is ODBC
keywords. implemented in the ODBC
Driver Manager.

For Windows, the Driver


Manager is required if
applications that connect to
solidDB use OLE DB or ADO
APIs or if database tools that
require the Driver Manager,
such as Microsoft Access,
FoxPro, or Crystal Reports are
to be used.

For platforms other than


Windows, the Driver
Managers are provided by
vendors such as iODBC,
Merant, or UnixODBC.

SQLGetConnectAttr (3.0) Returns the value of a connection attribute. Supported ISO 92

SQLSetConnectAttr (3.0) Sets a connection attribute. Supported ISO 92

178 IBM solidDB: Programmer Guide


Table 142. solidDB supported ODBC functions (continued)

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

SQLGetEnvAttr (3.0) Returns the value of an environment Supported ISO 92


attribute.
SQLSetEnvAttr (3.0) Supported ISO 92
Sets an environment attribute.

SQLGetStmtAttr (3.0) Returns the value of a statement attribute. Supported ISO 92

SQLSetStmtAttr (3.0) Sets a statement attribute. Supported ISO 92

SQLSetConnectOption (1.0) N/A Deprecated (replaced by N/A


SQLSetConnectAttr)
SQLGetConnectOption (1.0) N/A
Deprecated (replaced by
SQLGetConnectAttr)

SQLGetStmtOption (1.0) N/A Deprecated (replaced by N/A


SQLGetStmtAttr)
SQLSetStmtOption (1.0) N/A N/A
Deprecated (replaced by
SQLSetStmtAttr)

Setting and Retrieving Descriptor Fields

SQLGetDescField (3.0) Returns the current setting or value of a Supported ISO 92


single descriptor field.
SQLSetDescField (3.0) Supported ISO 92
Sets the value of a single field of a descriptor
record.

SQLGetDescRec (3.0) Returns the current settings or values of Supported ISO 92


multiple fields of a descriptor record. The
SQLSetDescRec (3.0) fields returned describe the name, data type, Supported ISO 92
and storage of column or parameter data.

Sets multiple descriptor fields that affect the


data type and buffer bound to a column or
parameter data.

SQLCopyDesc (3.0) Copies descriptor information from one Supported ISO 92


descriptor handle to another.

Preparing SQL Requests

SQLAllocStmt (1.0) N/A Deprecated (replaced by N/A


SQLAllocHandle)

SQLPrepare (1.0) Prepares an SQL statement for later Supported ISO 92


execution.

SQLBindParameter (2.0) Assigns storage for a parameter in an SQL Supported ODBC


statement.
Note: This function replaces
SQLBindParam which did not
exist in ODBC 2.x, although it
is in the X/Open and ISO
standards.

Appendix A. solidDB supported ODBC functions 179


Table 142. solidDB supported ODBC functions (continued)

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

SQLGetCursorName (1.0) Returns the cursor name associated with a Supported ISO 92
statement handle.
SQLSetCursorName (1.0) Supported ISO 92
Specifies a cursor name with an active
statement. If an application does not call
SQLSetCursorName, the driver generates
cursor names as needed for SQL statement
processing.

SQLParamOptions (1.0) N/A Deprecated (replaced by N/A


SQLSetStmtAttr)

SQLSetParam (1.0) N/A Deprecated (replaced by N/A


SQLBindParameter)

SQLSetScrollOptions (1.0) Sets options that control cursor behavior. Deprecated (replaced by ODBC
SQLGetInfo and
SQLSetStmtAttr)

Submitting Requests

SQLExecute (1.0) Executes a prepared statement using the Supported ISO 92


current values of the parameter marker
variables if any parameter markers exist in
the statement.

SQLExecDirect (1.0) Executes a preparable statement using the Supported ISO 92


current values of the parameter marker
variables if any parameters exist in the
statement. SQLExecDirect is the fastest way
to submit an SQL statement for one-time
execution.

SQLNativeSQL (1.0) Returns the SQL string as modified by the Not implemented; solidDB N/A
driver. SQLNativeSQL does not execute the does not support this
SQL statement. functionality.

SQLDescribeParam (1.0) Returns the text of an SQL statement as Supported ODBC


translated by the driver. This information is
also available in the fields of the IPD.

SQLNumParams (1.0) Returns the number of parameters in an SQL Supported ISO 92


statement.

SQLParamData (1.0) Used in conjunction with SQLPutData to Supported ISO 92


supply parameter data at execution time.
(Useful for long data values.)

SQLPutData (1.0) Allows an application to send data for a Supported ISO 92


parameter or column to the driver at
statement execution time. This function can
be used to send character or binary data
values in parts to a column with a character,
binary, or data source-specific data type (for
example, parameters of the
SQL_LONGVARBINARY or
SQL_LONGVARCHAR types).

180 IBM solidDB: Programmer Guide


Table 142. solidDB supported ODBC functions (continued)

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

Retrieving Results and Information about Results

SQLRowCount (1.0) Returns the number of rows affected by an Supported ISO 92


UPDATE, INSERT, or DELETE statement.

SQLNumResultCols (1.0) Returns the number of columns in a result Supported ISO 92


set.

SQLDescribeCol (1.0) Returns the result descriptor (column name, Supported. ISO 92
type, column size, decimal digits, and
nullability) for one column in the result set.
This information is also available in the fields
of the IRD.

NOTE: The driver now returns the number of


characters instead of the number of bytes for
the following attributes: SQL_DESC_LABEL,
SQL_DESC_NAME, SQL_DESC_SCHEMA_
NAME, SQL_DESC_CATALOG_ NAME,
SQL_DESC_BASE_COLUMN_NAME, and
SQLDESC_BASE_TABLE_NAME

This conforms more closely to the ODBC


standard and works correctly using ADO, VB,
OLE-DB, and ODBC calls. Note, however,
that this causes failure of the Microsoft Visual
DataBase Project. After updating/inserting
the record, the record is not saved and the
following error is displayed: "the table does
not exist.

SQLColAttributes (1.0) N/A Deprecated (replaced by N/A


SQLColAttribute)

SQLColAttribute (3.0) Describes attributes of a column in the result Supported. ISO 92


set.
Note: The driver now returns the number of
characters instead of the number of bytes for
the following attributes: SQL_DESC_LABEL,
SQL_DESC_NAME, SQL_DESC_SCHEMA_
NAME, SQL_DESC_CATALOG_NAME,
SQL_DESC_BASE_COLUMN_NAME, and
SQLDESC_BASE_TABLE_NAME

This conforms more closely to the ODBC


standard and works correctly using ADO, VB,
OLE-DB, and ODBC calls. Note, however,
that this causes failure of the Microsoft Visual
DataBase Project. After updating/inserting
the record, the record is not saved and the
following error is displayed: "the table does
not exist."

SQLBindCol (1.0) Assigns storage for a result column and Supported ISO 92
specifies the data type.

SQLFetch (1.0) Returns multiple result rows, fetching the Supported ISO 92
next rowset of data from the result set and
returning data for all bound columns.

Appendix A. solidDB supported ODBC functions 181


Table 142. solidDB supported ODBC functions (continued)

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

SQLExtendedFetch (2.0) N/A Replaced by SQLFetchScroll N/A

SQLFetchScroll (3.0) Returns scrollable result rows, fetching the Supported ISO 92
specified rowset of data from the result set Note: Since the solidDB
and returning data for all bound columns. ODBC Driver currently has no
Block cursor support enables an application support for bookmarks, it is
to fetch more than one row with a single not possible to support the
fetch into the application buffer. SQL_FETCH_BOOKMARK
option in SQLFetchScroll.
When working with an ODBC 2.x driver, the
Driver Manager maps this function to
SQLExtendedFetch.

SQLGetData (1.0) Returns part or all of one column of one row Supported ISO 92
of a result set. It can be called multiple times
to retrieve variable length data in parts,
making it useful for long data values.

SQLSetPos (1.0) Positions a cursor within a fetched block of Supported, along with all the ODBC
data and allows an application to refresh data options, that is,
in the rowset or to update or delete data in
the result set. SQL_POSITION,

SQL_DELETE, and

SQL_UPDATE

SQLBulkOperations (3.0) Performs bulk insertions and bulk bookmark solidDB supports this, but ODBC
operations, including update, delete, and only when using the
fetch by bookmark. SQL_ADD option.

SQLMoreResults (1.0) Determines whether there are more results Not supported ODBC
available on a statement containing SELECT,
UPDATE, INSERT, or DELETE statement and, solidDB does not support
if so, initializes processing for those results. multiple results.

SQLGetDiagField (3.0) Returns additional diagnostic information (a Supported ISO 92


single field of the diagnostic data structure
associated with a specified handle). This
information includes error, warning, and
status information.

SQLGetDiagRec (3.0) Returns additional diagnostic information Supported ISO 92


(multiple fields of the diagnostic data
structure). Unlike SQLGetDiagField, which
returns one diagnostic field per call,
SQLGetDiagRec returns several commonly
used fields of a diagnostic record, including
the SQLSTATE, the native error code, and the
diagnostic message text.

SQLError (1.0) N/A Deprecated (replaced by N/A


SQLGetDiagRec)

Obtaining Information about the Data Source's System Tables

182 IBM solidDB: Programmer Guide


Table 142. solidDB supported ODBC functions (continued)

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

SQLColumnPrivileges (1.0) Returns a list of columns and associated Supported ODBC


privileges for the specified table. The driver
returns the information as a result set on the
specified StatementHandle. This function is
supported via an appropriate SQL execution.

SQLColumns (1.0) Returns a list of columns and associated Supported X/Open


privileges for the specified table. The driver
returns the information as a result set on the
specified StatementHandle. This function is
supported via an appropriate SQL execution.

SQLForeignKeys (1.0) Returns two type of lists: Supported ODBC


v
Foreign keys in the specified table
(columns in the specified table that refer to
primary keys in other tables).
v
Foreign keys in other tables that refer to
the primary key in the specified table.

The driver returns each list as a result set on


the specified statement.

SQLPrimaryKeys (1.0) Returns the list of column names that make Supported ODBC
up the primary key for a table. The driver
returns the information as a result set. This
function does not support returning primary
keys from multiple tables in a single call.

SQLProcedureColumns (1.0) Returns the list of input and output Supported. ODBC
parameters, as well as the columns that make
up the result set for the specified procedures.
The driver returns the information as a result
set on the specified statement.

SQLProcedures (1.0) Returns the list of procedure names stored in Supported ODBC
a specific data source. Procedure is a generic
term used to describe an executable object, or
a named entity that can be invoked using
input and output parameters.

SQLSpecialColumns (1.0) Returns the following information about Supported X/Open


columns within a specified table:
v The optimal set of columns that uniquely
identifies a row in the table.
v Columns that are automatically updated
when any value in the row is updated by a
transaction.

SQLStatistics (1.0) Returns statistics about a single table and the Supported ISO 92
list of indexes associated with the table. The
driver returns the information as a result set.

Appendix A. solidDB supported ODBC functions 183


Table 142. solidDB supported ODBC functions (continued)

Function Names/Version Availability when using


Introduced1 Purpose ODBC Conformance2

SQLTablePrivileges (1.0) Returns a list of tables and the privileges Supported ODBC
associated with each table. The driver returns
the information as a result set on the
specified statement.

SQLTables (1.0) Returns the list of table, catalog, or schema Supported X/Open
names, and table types, stored in a specific
data source.

Terminating a statement

SQLFreeStmt (1.0) Ends statement processing, discards pending Supported ISO 92


results, and optionally, frees all resources
associated with the statement handle. Note: The SQLFreeStmt with
an option of SQL_DROP is
replaced by SQLFreeHandle.

SQLCloseCursor (3.0) Closes a cursor that has been opened on a Supported ISO 92
statement, and discards pending results.

SQLCancel (1.0) Cancels the processing on an SQL statement. Supported ISO 92

SQLEndTran (3.0) Requests a transaction commit or rollback on Supported ISO 92


all statements associated with a connection.
SQLEndTran can also request that a commit
or rollback operation be performed for all
connections associated with an environment.

SQLTransact (1.0) N/A Deprecated (replaced by N/A


SQLEndTran)

Terminating a Connection

SQLDisconnect (1.0) Closes the connection associated with a Supported ISO 92


specific connection handle.

SQLFreeConnect (1.0) N/A Deprecated (replaced by N/A


SQLFreeHandle)

SQLFreeEnv (1.0) N/A Deprecated (replaced by N/A


SQLFreeHandle)

SQLFreeHandle (3.0) Frees resources associated with a specific Supported ISO 92


environment, connection, statement, or
descriptor handle

1
Version introduced is the version when the function was first added to the ODBC
API.
2
Conformance level can be:
v ISO 92 (also appears in X/Open version 1 because X/Open is a pure superset of
ISO 92)
v X/Open (also appears in ODBC 3.x because ODBC 3.x is a pure superset of
X/Open version 1)

184 IBM solidDB: Programmer Guide


v ODBC (appears in neither ISO 92 or X/Open)
v N/A (Deprecated in ODBC 3.x)

Appendix A. solidDB supported ODBC functions 185


186 IBM solidDB: Programmer Guide
Appendix B. solidDB ODBC Driver 3.5.1 attributes support
This topic provides information about the solidDB ODBC Driver 3.5.1 attributes.

The attributes are grouped in the following categories:


v Environment-level attributes
v Connection-level attributes
v Statement-level attributes
v Column-level attributes
Table 143. 001 Environment Level

Attribute Value (Option) Driver Manager Driver Alone Comments

SQL_ATTR_ SQL_CP_OFF All values are All values are not All values are not
CONNECTION_ supported applicable to the applicable to
POOLING SQL_CP_ driver ODBC drivers,
ONE_PER_DRIVER handled by Driver
Manager, so this
SQL_CP_ attribute will be
ONE_PER_HENV supported if the
application links to
ODBC DM and
can't be simulated
by the driver itself.

SQL_ATTR_CP_MATCH SQL_CP_ All values All values are not All values are not
STRICT_MATCH supported applicable to the applicable to
driver ODBC drivers,
SQL_CP_ handled by Driver
RELAXED_MATCH Manager, so this
attribute will be
supported if the
application links to
ODBC DM and
can't be simulated
by the driver itself.

SQL_ATTR_ SQL_OV_ODBC3 Supported Supported Allows user to set


ODBC_VERSION and get the version
SQL_OV_ODBC2 Not Supported Not Supported to 2, but the
behavior is a per
3.0 and above.

SQL_ATTR_ SQL_TRUE Supported Supported


OUTPUT_NTS
SQL_FALSE Not Supported Not Supported

187
Table 144. 002 Connection Level

Attribute Value (Option) Driver Manager Driver Alone Comments

SQL_ATTR_ODBC_CURSORS SQL_CUR_IF_NEEDED All values not All values not


supported supported
SQL_FETCH_PRIOR

SQL_CUR_USE_ODBC

SQL_CUR_
USE_DRIVER

SQL_ATTR_ACCESS_MODE SQL_MODE_ All values not All values not


READ_ONLY supported supported

SQL_MODE_
READ_WRITE

SQL_ATTR_ASYNC_ENABLE SQL_ASYNC_ All values not All values not


ENABLE_OFF supported supported

SQL_ASYNC_
ENABLE_ON

SQL_ATTR_AUTO_IPD SQL_TRUE All values not All values not


supported supported
SQL_FALSE

SQL_ATTR_AUTOCOMMIT SQL_ATTR_ All values are All values are


AUTOCOMMIT_OFF supported supported

SQL_ATTR_
AUTOCOMMIT_ON

SQL_ATTR_ Timeout value in sec Supported Supported


CONNECTION_
TIMEOUT

SQL_ATTR_ CatalogName Supported Supported


CURRENT_CATALOG

SQL_ATTR_ Timeout value in sec Supported Supported


LOGIN_TIMEOUT

SQL_ATTR_ SQL_TRUE All values not All values not


METADATA_ID supported supported
SQL_FALSE

SQL_ATTR_PACKET_SIZE Packet size in bytes the desired size Not supported

SQL_ATTR_QUIET_MODE Set to NULL can set and get Not supported

SQL_ATTR_TRACE SQL_TRACE_OFF All values All values not All values


supported supported handled by DM,
SQL_TRACE_ON not by driver

188 IBM solidDB: Programmer Guide


Table 144. 002 Connection Level (continued)

Attribute Value (Option) Driver Manager Driver Alone Comments

SQL_ATTR_TRACEFILE Pointer to trace file Supported Not supported Handled by DM,


name not by driver

SQL_ATTR_TRNSLATE_LIB Pointer Name of lib Supported Not supported Handled by DM,


not by driver

SQL_ATTR_TXN_ISOLATION SQL_TXN_ All values are All values are An solidDB server
SERIALIZABLE supported, except supported, except does not support
the
SQL_TXN_READ_ SQL_TXN_ SQL_TXN_
UNCOMMITTED READ_ READ_ READ_
UNCOMMITTED UNCOMMITTED UNCOMMITTED
SQL_TXN_READ_ feature.
COMMITTED

SQL_TXN_
REPEATABLE_
READ

Table 145. 03 Statement Level

Driver Driver
Attribute Value (Option) Manager Alone Comments

SQL_ATTR_ SQL_CONCUR_ All values All values For the value


CONCURRENCY READ_ONLY supported supported SQL_CONCUR_READ_ONLY,
set and get are supported. For
SQL_CONCUR_LOCK all other values, set is
supported and get returns
SQL_CONCUR_ROWVER READ_ONLY.

SQL_CONCUR_VALUES

SQL_ATTR_ SQL_CURSOR_ Supported Supported


CURSOR_TYPE FORWARD_ONLY
Forced to Forced to
dynamic dynamic
SQL_CURSOR_
KEYSET_DRIVEN Forced to Forced to
dynamic dynamic
SQL_CURSOR_DYNAMIC
Forced to Forced to
SQL_CURSOR_STATIC
dynamic dynamic

SQL_ATTR_MAX_LENGTH Length in bytes Not Not Whatever the length, sets only
supported supported to default (0).

SQL_ATTR_MAX_ROWS Maximum number of rows Not Not Whatever the length, sets only
supported supported to default (0).

SQL_ATTR_ SQL_RD_OFF Not Not Sets to SQL_RD_ON only


RETRIEVE_DATA supported supported
SQL_RD_ON
Supported Supported

Appendix B. solidDB ODBC Driver 3.5.1 attributes support 189


Table 145. 03 Statement Level (continued)

Driver Driver
Attribute Value (Option) Manager Alone Comments

SQL_ATTR_ SQL_UB_OFF All values All values


USE_BOOKMARKS not not
SQL_UB_ON supported supported

SQL_ATTR_ An SQLUSMALLINT* Supported Supported The array has as many


ROW_ARRAY_SIZE value that points to an elements as there are rows in
array of SQLUSMALLINT the rowset.
values containing row
status values after a call to
SQLFetch or
SQLFetchScroll.

SQL_ATTR_ROWS_ An SQLUINTEGER* value Supported Supported


FETCHED_PTR that points to a buffer in
which to return the
number of rows fetched
after a call to SQLFetch or
SQLFetchScroll.

SQL_ATTR_ An SQLUINTEGER value Supported Supported


ROW_STATUS_PTR that specifies the number
of rows returned by each
call to SQLFetch or
SQLFetchScroll.

SQL_ROWSET_SIZE Number of rows to return Supported Supported Allows the ODBC application
to set its value to greater than
1.

SQL_ASYNC_ENABLE SQL_ASYNC_ All values All values


ENABLE_ON not not
supported supported
SQL_ASYNC_
ENABLE_OFF

SQL_BIND_TYPE SQL_BIND_BY_COLUMN Not Not


supported supported

SQL_ATTR_KEYSET_SIZE Size Not Not Whatever the size, sets only to


supported supported default (0).

SQL_ATTR_NOSCAN SQL_NOSCAN_OFF Not Not Sets to SQL_NOSCAN_OFF


supported supported only
SQL_NOSCAN_ON
Not Not
supported supported

SQL_ATTR_ SQL_SC_NON_UNIQUE All values All values All values are not relevant to
SIMULATE_CURSOR not not solidDB Driver
SQL_SC_TRY_UNIQUE supported supported
SQL_SC_UNIQUE

190 IBM solidDB: Programmer Guide


Table 145. 03 Statement Level (continued)

Driver Driver
Attribute Value (Option) Manager Alone Comments

SQL_ATTR_ SQL_NULL_HDESC Not Not


APP_PARAM_DESC supported supported

SQL_ATTR_ SQL_NULL_HDESC Not Not


APP_ROW_DESC supported supported

SQL_ATTR_ SQL_SCROLLABLE Not Not Sets to


CURSOR_SCROLLABLE supported supported SQL_NONSCROLLABLE only
SQL_NONSCROLLABLE
Not Not
supported supported

SQL_ATTR_ SQL_UNSPECIFIED Not Not Sets to SQL_UNSPECIFIED


CURSOR_SENSITIVITY supported supported only Sets to SQL_
SQL_INSENSITIVE UNSPECIFIED only
Not Not
SQL_SENSITIVE supported supported

Not Not
supported supported

SQL_ATTR_ROW_NUMBER Number of current row Supported Supported User can get the number of
rows; cannot set because of
read-only property

SQL_ATTR_ SQL_TRUE Both values Both


ENABLE_AUTO_IPD not values not
SQL_FALSE supported supported

SQL_ATTR_METADATA_ID SQL_TRUE Both values Both


not values not
SQL_FALSE supported supported

SQL_ATTR_PARAM_ SQL_DESC_DATA_PTR All values All values


BIND_OFFSET_PTR are are
SQL_DESC_ supported supported
INDICATOR_PTR

SQL_DESC_
OCTET_LENGTH_PTR

SQL_DESC_
BIND_OFFSET_PTR

SQL_ATTR_PARAM_ Pointer to array containing Supported Supported


OPERATION_PTR list of parameters to be
ignored

Appendix B. solidDB ODBC Driver 3.5.1 attributes support 191


Table 145. 03 Statement Level (continued)

Driver Driver
Attribute Value (Option) Manager Alone Comments

SQL_ATTR_PARAMS_ Unsigned integer pointer Supported Supported


PROCESSED_PTR to return the number of
sets of parameters that
have been processed by
the SQL statement
executed through
SQLExecute or
SQLExecDirect.

Table 146. 04 Column Attributes

Value
Attribute (Option) Driver Manager Driver Alone Comments

SQL_DESC_BASE_COLUMN_NAME Supported Supported

SQL_DESC_BASE_TABLE_NAME Supported Supported

SQL_DESC_DISPLAY_SIZE Supported Supported

SQL_DESC_NAME

SQL_DESC_NULLABLE Supported Supported

SQL_DESC_OCTET_LENGTH Supported Supported

SQL_DESC_PRECISION Supported Supported

SQL_DESC_SCALE Supported Supported

SQL_DESC_UPDATABLE Supported Supported

SQL_DESC_FIXED_PREC_SCALE Supported Supported

SQL_DESC_TABLE_NAME Supported Supported

SQL_DESC_TYPE Supported Supported

SQL_DESC_UNNAMED Supported Supported

SQL_DESC_SCHEMA_NAME Supported Supported

SQL_DESC_LOCAL_TYPE_NAME Supported Supported

SQL_DESC_LABEL Supported Supported

SQL_DESC_TYPE_NAME Supported Supported

SQL_DESC_AUTO_UNIQUE_VALUE Supported Supported

192 IBM solidDB: Programmer Guide


Table 146. 04 Column Attributes (continued)

Value
Attribute (Option) Driver Manager Driver Alone Comments

SQL_DESC_CONCISE_TYPE Supported Supported

SQL_DESC_LITERAL_PREFIX Supported Supported

SQL_DESC_UNSIGNED Supported Supported

SQL_DESC_LITERAL_PREFIX Supported Supported

SQL_DESC_UNSIGNED Supported Supported

SQL_DESC_LITERAL_SUFFIX Supported Supported

SQL_DESC_CATALOG_NAME Supported Supported

SQL_DESC_COUNT Supported Supported

SQL_DESC_SEARCHABLE Supported Supported

SQL_DESC_LENGTH Supported Supported

SQL_DESC_CASE_SENSITIVE Supported Supported

SQL_DESC_NUM_PREX_RADIX Supported Supported

Appendix B. solidDB ODBC Driver 3.5.1 attributes support 193


194 IBM solidDB: Programmer Guide
Appendix C. SQLSTATE error codes
This topic contains an error codes table that provides possible SQLSTATE values
that a driver returns for the SQLGetDiagRec function.

Note: The SQLGetDiagRec and SQLGetDiagField return SQLSTATE values that


conform to the X/Open (The Open Group) Data Management: Structured Query
Language (SQL), Version 2 (3/95).

Error codes table convention


Table 147. Error code class values

Class value Meaning

01 Indicates a warning and includes a return


code of SQL_SUCCESS_WITH_INFO.
Note: Error class 01 returns both warnings
and errors.

01, 07, 08, 21, 22, 23, 24, 25, 28, 34, 3C, 3D, Indicates an error that includes a return
3F, 40, 42, 44, HY value of SQL_ERROR.
Note: Error class 01 returns both warnings
and errors.

IM Indicates warning and errors that are


derived from ODBC.

Note: Typically, when a function successfully executes, it returns a value of


SQL_SUCCESS; in some cases, however, the function may also return the
SQLSTATE 00000, which also indicates successful execution.

SQLSTATE codes
Table 148. SQLSTATE codes

SQLSTATE Error Can be returned from

01000 General warning All ODBC functions except:

SQLGetDiagField

SQLGetDiagRec

01001 Cursor operation conflict SQLExecDirect

SQLExecute

SQLParamData

SQLSetPos

01002 Disconnect error SQLDisconnect

195
Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

01003 NULL value eliminated in set SQLExecDirect


function
SQLExecute

SQLParamData

v SQLColAttribute
01004 String data, right truncated
v SQLDataSources
v SQLDescribeCol
v SQLDriverConnect
v SQLDrivers
v SQLExecDirect
v SQLExecute
v SQLExtendedFetch
v SQLFetch
v SQLFetchScroll
v SQLGetConnectAttr
v SQLGetCursorName
v SQLGetData
v SQLGetDescField
v SQLGetDescRec
v SQLGetEnvAttr
v SQLGetInfo
v SQLGetStmtAttr
v SQLParamData
v SQLPutData
v SQLSetCursorName

01006 Privilege not revoked SQLExecDirect

SQLExecute

SQLParamData

01007 Privilege not granted SQLExecDirect

SQLExecute

SQLParamData

01S00 Invalid connection string SQLDriverConnect


attribute
SQLSetPos

01S01 Error in row SQLExtendedFetch

v SQLConnect
01S02 Option value changed
v SQLDriverConnect
v SQLExecDirect
v SQLExecute
v SQLParamData
v SQLPrepare
v SQLSetConnectAttr
v SQLSetDescField
v SQLSetEnvAttr
v SQLSetStmtAttr

196 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

01S06 Attempt to fetch before the SQLExtendedFetch


result set returned the first
rowset SQLFetchScroll

01S07 Fractional truncation SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLParamData

SQLSetPos

01S08 Error saving File DSN SQCriverConnect

01S09 Invalid keyword SQLDriverConnect

07001 Wrong number of parameters SQLExecDirect

SQLExecute

07002 COUNT field incorrect SQLExecDirect

SQLExecute

SQLParamData

07005 Prepared statement not a SQLColAttribute


cursor_specification
SQLDescribeCol

07006 Restricted data type attribute SQLBindCol


violation
SQLBindParameter

SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLParamData

SQLPutData

Appendix C. SQLSTATE error codes 197


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

07009 Invalid descriptor index SQLBindCol

SQLBindParameter

SQLColAttribute

SQLDescribeCol

SQLDesribeParam

SQLFetch

SQLFetchScroll

SQLGetData

SQLGetDescField

SQLParamData

SQLSetDescField

SQLSetDescRec

SQLSetPos

07S01 Invalid use of default SQLExecDirect


parameter
SQLExecute

SQLParamData

SQLPutData

08001 Client unable to establish SQLConnect


connection
SQLDriverConnect

08002 Connection name in use SQLConnect

SQLDriverConnect

SQLSetConnectAttr

08003 Connection does not exist SQLAllocHandle

SQLDisconnect

SQLEndTran

SQLGetConnectAttr

SQLGetInfo

SQLSetConnectAttr

08004 Server rejected the SQLConnect


connection
SQLDriverConnect

08007 Connection failure during SQLEndTran


transaction

198 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

v SQLColumnPrivileges
08S01 Communication link failure
v SQLColumns
v SQLConnect
v SQLConnect
v SQLCopyDesc
v SQLDescribeCol
v SQLDescribeParam
v SQLDriverConnect
v SQLExecDirect
v SQLExecute
v SQLExtendedFetch
v SQLFetch
v SQLFetchScroll
v SQLForeignKeys
v SQLGetConnectAttr
v SQLGetData
v SQLGetDescField
v SQLGetDescRec
v SQLGetFunctions
v SQLGetInfo
v SQLGetTypeInfo
v SQLMoreResults
v SQLNumParams
v SQLNumResultCols
v SQLParamData
v SQLPrepare
v SQLPrimaryKeys
v SQLProcedureColumns
v SQLProcedures
v SQLPutData
v SQLSetConnectAttr
v SQLSetDescField
v SQLSetDescRec
v SQLSetEnvAttr
v SQLSetStmtAttr
v SQLSpecialColumns
v SQLStatistics
v SQLTablePrivileges
v SQLTables

21S01 Insert value list does not SQLExecDirect


match column list
SQLPrepare

21S02 Degree of derived table does SQLExecDirect


not match column list
SQLExecute

SQLParamData

SQLPrepare

SQLSetPos

Appendix C. SQLSTATE error codes 199


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

22001 String data, right truncated SQLExecDirect

SQLExecute

SQLFetch

SQLFetchScroll

SQLParamData

SQLPutData

SQLSetDescField

SQLSetPos

22002 Indicator variable required SQLExecDirect


but not supplied
SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLParamData

22003 Numeric value out of range SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLGetInfo

SQLParamData

SQLPutData

SQLSetPos

22007 Invalid datetime format SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLParamData

SQLPutData

SQLSetPos

200 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

22008 Datetime field overflow SQLExecDirect

SQLExecute

SQLParamData

SQLPutData

22012 Division by zero SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLParamData

SQLPutData

22015 Interval field overflow SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLParamData

SQLPutData

SQLSetPos

22018 Invalid character value for SQLExecDirect


cast specification
SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLGetData

SQLParamData

SQLPutData

SQLSetPos

22019 Invalid escape character SQLExecDirect

SQLExecute

SQLPrepare

Appendix C. SQLSTATE error codes 201


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

22025 Invalid escape sequence SQLExecDirect

SQLExecute

SQLPrepare

22026 String data, length mismatch SQLParamData

23000 Integrity constraint violation SQLExecDirect

SQLExecute

SQLParamData

SQLSetPos

24000 Invalid cursor state SQLCloseCursor

SQLColumnPrivileges

SQLColumns

SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLForeignKeys

SQLGetData

SQLGetStmtAttr

SQLGetTypeInfo

SQLPrepare

SQLPrimaryKeys

SQLProcedureColumns

SQLProcedures

SQLConnectAttr

SQLSetCursorName

SQLSetPos

SQLSpecialColumns

SQLStatistics

SQLTablePrivileges

SQLTables

25000 Invalid transaction state SQLDisconnect

25S01 Transaction state SQLEndTran

25S02 Transaction is still active SQLEndTran

202 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

25S03 Transaction is rolled back SQLEndTran

28000 Invalid authorization SQLConnect


specification
SQLDriverConnect

34000 Invalid cursor name SQLExecDirect

SQLPrepare

SQLSetCursorName

3C000 Duplicate cursor name SQLSetCursorName

3D000 Invalid catalog name SQLExecDirect

SQLPrepare

SQLSetConnectAttr

3F000 Invalid schema name SQLExecDirect

SQLPrepare

40001 Serialization failure SQLColumnPrivileges

SQLColumns

SQLEndTran

SQLExecDirect

SQLExecute

SQLFetch

SQLFetchScroll

SQLForeignKeys

SQLGetTypeInfo

SQLMoreResults

SQLParamData

SQLPrimaryKeys

SQLProcedureColumns

SQLProcedures

SQLSetPos

SQLSpecialColumns

SQLStatistics

SQLTablePrivileges

SQLTables

40002 Integrity constraint violation SQLEndTran

Appendix C. SQLSTATE error codes 203


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

40003 Statement completion SQLColumnPrivileges


unknown
SQLColumns

SQLExecDirect

SQLExecute

SQLFetch

SQLFetchScroll

SQLGetTypeInfo

SQLForeignKeys

SQLMoreResults

SQLPrimaryKeys

SQLProcedureColumns

SQLProcedures

SQLParamData

SQLSetPos

SQLSpecialColumns

SQLStatistics

SQLTables

42000 Syntax error or access SQLExecDirect


violation
SQLExecute

SQLParamData

SQLPrepare

SQLSetPos

42S01 Base table or view already SQLExecDirect


exists
SQLPrepare

42S02 Base table or view not found SQLExecDirect

SQLPrepare

42S11 Index already exists SQLExecDirect

SQLPrepare

42S12 Index not found SQLExecDirect

SQLPrepare

42S21 Column already exists SQLExecDirect

SQLPrepare

42S22 Column not found SQLExecDirect

SQLPrepare

204 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

44000 WITH CHECK OPTION SQLExecDirect


violation
SQLExecute

SQLParamData

HY000 General Error All ODBC functions except:

SQLGetDiagField

SQLGetDiagRec

HY001 Memory allocation error All ODBC function except:

SQLGetDiagField

SQLGetDiagRec

HY003 Invalid application buffer SQLBindCol


type
SQLBindParameter

SQLGetData

HY004 Invalid SQL data type SQLBindParameter

SQLGetTypeInfo

HY007 Associated statement is not SQLCopyDesc


prepared
SQLGetDescField

SQLGetDescRec

Appendix C. SQLSTATE error codes 205


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

HY008 Operation canceled All ODBC functions that can be processed asynchronously:

SQLColAttribute

SQLColumnPrivileges

SQLColumns

SQLDescribeCol

SQLDescribeParam

SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLForeignKeys

SQLGetData

SQLGetTypeInfo

SQLMoreResults

SQLNumParams

SQLNumResultCols

SQLParamData

SQLPrepare

SQLPrimaryKeys

SQLProcedureColumns

SQLProcedures

SQLPutData

SQLSetPos

SQLSpecialColumns

SQLStatistics

SQLTablePrivileges

SQLTables

206 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

HY009 Invalid use of null pointer SQLAllocHandle

SQLBindParameter

SQLColumnPrivileges

SQLColumns

SQLExecDirect

SQLForeignKeys

SQLGetCursorName

SQLGetData

SQLGetFunctions

SQLPrepare

SQLPrimaryKeys

SQLProcedureColumns

SQLProcedures

SQLPutData

SQLSetConnectAttr

SQLSetCursorName

SQLSetEnvAttr

SQLSetStmtAttr

SQLSpecialColumns

SQLStatistics

SQLTablePrivileges

SQLTables

Appendix C. SQLSTATE error codes 207


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

v SQLAllocHandle
HY010 Function sequence error
v SQLBindCol
v SQLBindParameter
v SQLCloseCursor
v SQLColAttribute
v SQLColumnPrivileges
v SQLColumns
v SQLCopyDesc
v SQLDescribeCol
v SQLDescribeParam
v SQLDisconnect
v SQLEndTran
v SQLExecDirect
v SQLExecute
v SQLExtendedFetch
v SQLFetch
v SQLFetchScroll
v SQLForeignKeys
v SQLFreeHandle
v SQLFreeStmt
v SQLGetConnectAttr
v SQLGetCursorName
v SQLGetData
v SQLGetDescField
v SQLGetDescRec
v SQLGetFunctions
v SQLGetStmtAttr
v SQLGetTypeInfo
v SQLMoreResults
v SQLNumParams
v SQLNumResultCols
v SQLParamData
v SQLPrepare
v SQLPrimaryKeys
v SQLProcedureColumns
v SQLProcedures
v SQLPutData
v SQLRowCount
v SQLSetConnectAttr
v SQLSetCursorName
v SQLSetDescField
v SQLSetEnvAttr
v SQLSetDescRec
v SQLSetPos
v SQLSetStmtAttr
v SQLSpecialColumns
v SQLStatistics
v SQLTablePrivileges
v SQLTables

208 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

HY011 Attribute cannot be set now SQLParamData

SQLSetConnectAttr

SQLSetPos

SQLSetStmtAttr

HY012 Invalid transaction operation SQLEndTran


code

HY013 Memory Management err All ODBC functions except:

SQLGetDiagField

SQLGetDiagRec

HY014 Limit on the number of SQLAllocHandle


handles exceeded

HY015 No cursor name available SQLGetCursorName

HY016 Cannot modify an SQLCopyDesc


implementation row
descriptor SQLSetDescField

SQLSetDescRec

HY017 Invalid use of an SQLFreeHandle


automatically allocated
descriptor handle SQLSetStmtAttr

HY018 Server declined cancel SQLCancel


request

HY019 Non-character and SQLPutData


non-binary data sent in
pieces

HY020 Attempt to concatenate a null SQLPutData


value

HY021 Inconsistent descriptor SQLBindParameter


information
SQLCopyDesc

SQLGetDescField

SQLSetDescField

SQLSetDescRec

HY024 Invalid attribute value SQLSetConnectAttr

SQLSetEnvAttr

SQLSetStmtAttr

Appendix C. SQLSTATE error codes 209


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

v SQLBindCol
HY090 Invalid string or buffer
length v SQLBindParameter
v SQLBrowseConnect
v SQLColAttribute
v SQLColumnPrivileges
v SQLColumns
v SQLConnect
v SQLDataSources
v SQLDescribeCol
v SQLDriverConnect
v SQLDrivers
v SQLExecDirect
v SQLExecute
v SQLFetch
v SQLFetchScroll
v SQLForeignKeys
v SQLGetConnectAttr
v SQLGetCursorName
v SQLGetData
v SQLGetDescField
v SQLGetInfo
v SQLGetStmtAttr
v SQLParamData
v SQLPrepare
v SQLPrimaryKeys
v SQLProcedureColumns
v SQLProcedures
v SQLPutData
v SQLSetConnectAttr
v SQLSetCursorName
v SQLSetDescField
v SQLSetDescRec
v SQLSetEnvAttr
v SQLSetStmtAttr
v SQLSetPos
v SQLSpecialColumns
v SQLTablePrivileges
v SQLStatistics
v SQLTables

HY091 Invalid descriptor field SQLColAttribute


identifier
SQLGetDescField

SQLSetDescField

210 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

HY092 Invalid attribute/option SQLAllocHandle


identifier
SQLCopyDesc

SQLDriverConnect

SQLEndTran

SQLFreeStmt

SQLGetConnectAttr

SQLGetEnvAttr

SQLGetStmtAttr

SQLParamData

SQLSetConnectAttr

SQLSetDescField

SQLSetEnvAttr

SQLSetPos

SQLSetStmtAttr

HY095 Function type out of range SQLGetFunctions

HY096 Invalid information type SQLGetInfo

HY097 Column type out of range SQLSpecial Columns

HY098 Scope type out of range SQLSpecial Columns

HY099 Nullable type out of range SQLSpecial Columns

HY100 Uniqueness option type out SQLStatistics


of range

HY101 Accuracy option type out of SQLStatistics


range

HY103 Invalid retrieval code SQLDataSources

SQLDrivers

HY104 Invalid precision or scale SQLBindParameter


value

HY105 Invalid parameter type SQLBindParameter

SQLExecDirect

SQLExecute

SQLParamData

SQLSetDescField

HY106 Fetch type out of range SQLExtendedFetch

SQLFetchScroll

Appendix C. SQLSTATE error codes 211


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

HY107 Row value out of range SQLExtendedFetch

SQLFetch

SQLFetchScroll

SQLSetPos

HY109 Invalid cursor position SQLExecDirect

SQLExecute

SQLGetData

SQLGetStmtAttr

SQLParamData

SQLSetPos

HY110 Invalid driver completion SQLDriverConnect

HY111 Invalid bookmark value SQLExtendedFetch

SQLFetchScroll

212 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

v SQLBindCol
HYC00 Optional feature not
implemented v SQLBindParameter
v SQLColAttribute
v SQLColumnPrivileges
v SQLColumns
v SQLDriverConnect
v SQLEndTran
v SQLConnect
v SQLExecDirect
v SQLExecute
v SQLExtendedFetch
v SQLFetch
v SQLFetchScroll
v SQLForeignKeys
v SQLGetConnectAttr
v SQLGetData
v SQLGetEnvAttr
v SQLSetPos
v SQLGetInfo
v SQLGetStmtAttr
v SQLGetTypeInfo
v SQLParamData
v SQLPrepare
v SQLPrimaryKeys
v SQLProcedureColumns
v SQLProcedures
v SQLSetConnectAttr
v SQLSetEnvAttr
v SQLSetStmtAttr
v SQLSpecialColumns
v SQLStatistics
v SQLTablePrivileges
v SQLTables

Appendix C. SQLSTATE error codes 213


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

HYT00 Timeout expired SQLBrowseConnect

SQLColumnPrivileges

SQLColumns

SQLConnect

SQLDriverConnect

SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLForeignKeys

SQLGetTypeInfo

SQLParamData

SQLPrepare

SQLPrimaryKeys

SQLProcedureColumns

SQLProcedures

SQLSetPos

SQLSpecialColumns

SQLStatistics

SQLTablePrivileges

SQLTables

HYT01 Connection timeout expired All ODBC functions except:

SQLDrivers

SQLDataSources

SQLGetEnvAttr

SQLSetEnvAttr

IM001 Driver does not support this All ODBC functions except:
function
SQLAllocHandle

SQLDataSources

SQLDrivers

SQLFreeHandle

SQLGetFunctions

IM002 Data source name not found SQLConnect


and no default driver
specified SQLDriverConnect

IM003 Specified driver could not be SQLConnect


loaded.

214 IBM solidDB: Programmer Guide


Table 148. SQLSTATE codes (continued)

SQLSTATE Error Can be returned from

IM004 Driver's SQLAllocHandle on SQLDriverConnec


SQL_HANDLE_ENV failed
SQLConnect

SQLDriverConnect

IM005 Driver's SQLAllocHandle on SQLConnect


SQL_HANDLE_DBC failed
SQLDriverConnect

IM006 Driver's SQLSetConnectAttr SQLConnect


Failed
SQLDriverConnect

IM007 No data source or driver SQLDriverConnect


specified; dialog prohibited

IM008 Dialog failed SQLDriverConnect

IM009 Unable to load translation SQLConnect


DLL
SQLDriverConnect

SQLSetConnectAttr

IM010 Data source name too long SQLConnect

SQLDriverConnect

IM011 Driver name too long SQLDriverConnect

IM012 DRIVER keyword syntax SQLDriverConnect


error

IM013 Trace file error All ODBC functions

IM014 Invalid name of File DSN SQLDriverConnect

IM015 Corrupt file data source SQLDriverConnect

Appendix C. SQLSTATE error codes 215


216 IBM solidDB: Programmer Guide
Appendix D. Minimum SQL grammar requirements for ODBC
This section describes the minimum subset of SQL-92 Entry level syntax that an
ODBC driver must support. An application that uses this syntax will be supported
by any ODBC-compliant driver.

Applications can call SQLGetInfo with the SQL_SQL_CONFORMANCE to


determine if additional features of SQL-92, not covered in this section, are
supported.

Note: If the driver supports only read-only data sources, the SQL syntax that
applies to changing data may not apply to the driver. Applications need to call
SQLGetInfo with the SQL_DATA_SOURCE_READ_ONLY information type to
determine if a data source is read-only.

SQL statements
This section describes the subset of SQL statements and elements.
create-table-statement ::=
CREATE TABLE base_table_name
(column_identifier data_type [, column_identifier data_type]...)

Important: As the data_type in a create_table_statement, applications require a data


type from the TYPE_NAME column of the result set returned by SQLGetTypeInfo.
delete_statement_searched ::=
DELETE FROM table_name [WHERE search_condition]
drop_table_statement ::=
DROP TABLE base_table_name
select_statement ::=
SELECT [ALL | DISTINCT] select_list
FROM table_reference_list
[WHERE search_condition]
[order_by_clause]
statement ::= create_table_statement |
delete_statement_searched |
drop_table_statement |
insert_stetement |
select_statement |
update_statement_searched
Update_statement_searched ::=
UPDATE table_name
SET column_identifier = {expression |
NULL}
[, column_identifier = {expression |
NULL}]...
[WHERE search_condition]

SQL statement elements


base_table_identifier ::= user_defined_name
base_table_name ::= base_table_identifier
boolean_factor ::= [NOT] boolean_primary
boolean_primary ::= predicate | ( search_condition )
boolean_term ::= boolean_factor [AND boolean_term]
character_string_literal :: = "{character}..."
(character is any character in the character set
of the driver/data source. To include a single
literal quote character (’) in a character_string_literal,
use two literal quote characters [""].)

217
column_identifier ::= user_defined_name
column_name ::= [table_name.]column_identifier
comparison_operator ::= < | > | <= | >= | = | <>
comparison_predicate ::= expression comparison_operator expression
data_type ::= character_string_type
(character_string_type is any data type for which the
""DATA_TYPE"" column in the result set returned by SQLGetTypeInfo
is either SQL_CHAR or SQLVARCHAR.)
digit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
dynamic_parameter ::= ?
expression ::= term | expression {+|-} term
factor ::= [+|-]primary
insert_value ::= dynamic_parameter | literal | NULL | USER
letter ::= lower_case_letter | upper_case_letter
literal ::= character_string_literal
lower_case_letter ::= a | b | c | d | e | f | g |
h | i | j | k | l | m | n | o | p | q | r | s |
t | u | v | w | x | y | z
order_by_clause ::= ORDER BY sort_specification [, sort_specification]...
primary ::= column_name | dynamic_parameter | literal | ( expression )
search_condition ::= boolean_term [OR search_condition]
select_list ::= * | select_sublist [, select_sublist]...
(select_list cannot contain parameters.)
select_sublist ::= expression
sort_specification ::= {unsigned_integer | column_name } [ASC | DESC]
table_identifier ::= user_defined_name
table_name ::= table_identifier
table_reference ::= table_name
table_reference ::= table_name [,table_reference]...
term ::= factor | term {*|/} factor
unsigned_integer ::= {digit}
upper_case_letter ::= A | B | C | D | E | F | G |
H | I | J | K | L | M | N | O | P | Q | R | S |
T | U | V | W | X | Y | Z
user_defined_name ::= letter[ digit | letter| _ ]...

Control statements (logical condition)


This topic provides a summary of control statements that are available in solidDB
database procedures.

For a more detailed description of these control statements, see the discussion on
stored procedures in the solidDB SQL Guide.
Table 149. Control Statements

Control statement Description

set variable = expression


Assigns a value to a variable. The value can
be either a literal value (for example, 10 or
'text') or another variable. Parameters are
considered as normal variables.

variable := expression
Alternate syntax for assigning values to
variables.

boolean_expr
A boolean expression which evaluates to
"true" or "false". The expression can include
comparison operators, such as =, >, and <)
and logical operators and, or, and not.

218 IBM solidDB: Programmer Guide


Table 149. Control Statements (continued)

Control statement Description

statement_list
A valid procedure statement that executes as
a result of a boolean expression.

while
boolean_expr This loops while the expression is true. For
loop examples of valid parentheses use in WHILE
statement_list loops, see the discussion of stored
end loop procedures in solidDB SQL Guide.

leave
Leaves the innermost while loop and
continues executing the procedure from the
next statement after the keyword end loop.

if
boolean_expr Executes statement_list1 if boolean_expr is
then true; otherwise, executes statement_list2. For
statement_list1 examples of valid parentheses use in IF
else statements, see the discussion on stored
statement_list2 procedures in solidDB SQL Guide.
end if

if
boolean_expr1 If boolean_expr1 is true, executes
then statement_list1. If boolean_expr2 is true,
statement_list1 executes statement_list2. The statement can
elseif optionally contain multiple elseif statements
boolean_expr2 and also an else statement. For examples of
then valid parentheses use in IF statement, see
statement_list2 the discussion of stored procedures in
end if solidDB SQL Guide.

return
Returns the current values of output
parameters and exits the procedure. If a
procedure has a return row statement, return
behaves like return norow.

return sqlerror of cursor_name


Returns the sqlerror associated with the
cursor and exits the procedure.

return row
Returns the current values of output
parameters and continues execution of the
procedure. Return row does not exit the
procedure and return control to the caller.

return norow
Returns the end of the set and exits the
procedure.

Data type support


At minimum, ODBC drivers must support either SQL_CHAR or SQL_VARCHAR.

Appendix D. Minimum SQL grammar requirements for ODBC 219


Other data types support is determined by the driver's or data source's SQL-92
conformance level. To determine the SQL-92 conformance level for a driver or data
source, applications need to call SQLGetTypeInfo.

Parameter data types


This topic describes how data types are determined for parameters and the
parameter markers support.

Even though each parameter specified with SQLBindParameter is defined using an


SQL data type, the parameters in an SQL statement have no intrinsic data type.
Therefore, parameter markers can be included in an SQL statement only if their
data types can be inferred from another operand in the statement. For example, in
an arithmetic expression such as ? + COLUMN1, the data type of the parameter
can be inferred from the data type of the named column represented by
COLUMN1. An application cannot use a parameter marker if the data type cannot
be determined.

The following table describes how a data type is determined for several types of
parameters according to SQL-92 standards. For comprehensive information about
inferring the parameter type, see the SQL-92 specification.
Table 150. Determining Data Ttype for Several Types of Parameters

Location of Parameter Assumed Data Type

One operand of a binary arithmetic or Same as the other operand


comparison operator

The first operand in a BETWEEN clause Same as the second operand

The second or third operand in a BETWEEN Same as the first operand


clause

An expression used with IN Same as the first value or the result column
of the subquery

A value used with IN Same as the expression or the first value if


there is a parameter marker in the
expression

A pattern value used with LIKE VARCHAR

An update value used with UPDATE Same as the update column

Parameter markers

According to the SQL-92 specification, an application cannot place parameter


markers in the following locations:
v In a SELECT list.
v As both expressions in a comparison-predicate.
v As both operands of a binary operator.
v As both the first and second operands of a BETWEEN operation.
v As both the first and third operands of a BETWEEN operation.

220 IBM solidDB: Programmer Guide


v As both the expression and the first value of an IN operation.
v As the operand of a unary + or - operation.
v As the argument of a set-function-reference.

For a comprehensive list and more details, see the SQL-92 specification.

Literals in ODBC
This section contains information that will help driver writers who are converting
a character string type to a numeric or interval type, or from a numeric or interval
type to a character string type.

Interval literal syntax

The following syntax is used for interval literals in ODBC.


interval_literal ::= INTERVAL [+|_] interval_string interval_qualifier
interval_string ::= quote { year_month_literal
| day_time_literal } quote
year_month_literal ::= years_value | [years_value] months_value
day_time_literal ::= day_time_interval | time_interval
day_time_interval ::= days_value [hours_value
[:minutes_value[:seconds_value]]]
time_interval ::= hours_value [:minutes_value [:seconds_value ] ]
| minutes_value [:seconds_value ]
| seconds_value
years_value ::= datetime_value
months_value ::= datetime_value
days_value ::= datetime_value
hours_value ::= datetime_value
minutes_value ::= datetime_value
seconds_value ::= seconds_integer_value [.[seconds_fraction] ]
seconds_integer_value ::= unsigned_integer
seconds_fraction ::= unsigned_integer
datetime_value ::= unsigned_integer
interval_qualifier ::= start_field TO end_field
| single_datetime_field
start_field ::= non_second_datetime_field
[(interval_leading_field_precision )]
end_field ::= non_second_datetime_field
| SECOND[(interval_fractional_seconds_precision)]
single_datetime_field ::= non_second_datetime_field
[(interval_leading_field_precision)]
| SECOND[(interval_leading_field_precision
[, (interval_fractional_seconds_precision)]
datetime_field ::= non_second_datetime_field | SECOND
non_second_datetime_field ::= YEAR | MONTH | DAY | HOUR | MINUTE
interval_fractional_seconds_precision ::= unsigned_integer
interval_leading_field_precision ::= unsigned_integer
quote ::= ’
unsigned_integer ::= digit...

Numeric Literal Syntax

The following syntax is used for numeric literals in ODBC:


numeric_literal ::= signed_numeric_literal | unsigned_numeric_literal
signed_numeric_literal ::= [sign] unsigned_numeric_literal
unsigned_numeric_literal ::= exact_numeric_literal
| approximate_numeric_literal
exact_numeric_literal ::= unsigned_integer [period[unsigned_integer]]
| period unsigned_integer
sign ::= plus_sign | minus_sign
approximate_numeric_literal ::= mantissa E exponent

Appendix D. Minimum SQL grammar requirements for ODBC 221


mantissa ::= exact_numeric_literal
exponent ::= signed_integer
signed_integer ::= [sign] unsigned_integer
unsigned_integer ::= digit...
plus_sign ::= +
minus_sign ::= _
digit ::= 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0
period ::= .

List of reserved keywords


To ensure compatibility with drivers that support the core SQL grammar, there are
keywords that applications should avoid using.

These words do not constrain the minimum SQL grammar. The #define value
SQL_ODBC_KEYWORDS contains a comma-separated list of these keywords.

For a complete list of reserved keywords in several SQL standards and solidDB
ODBC API, see “Reserved Words” in IBM solidDB SQL Guide.
Table 151. List of Reserved Keywords

Keyword Keyword Keyword Keyword

ABSOLUTE ACTION ADA ADD

ALL ALLOCATE ALTER AND

ANY ARE AS ASC

ASSERTION AT AUTHORIZATION AVG

BEGIN BETWEEN BIT BIT_LENGTH

BOTH BY CASCADE CASCADED

CASE CAST CATALOG CHAR

CHAR_LENGTH CHARACTER CHARACTER_LENGTH CHECK

CLOSE COALESCE COLLATE COLLATION

COLUMN COMMIT CONNECT CONNECTION

CONSTRAINT CONSTRAINTS CONTINUE CONVERT

CORRESPONDING COUNT CREATE CROSS

CURRENT CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP

CURRENT_USER CURSOR DATE DAY

DEALLOCATE DEC DECIMAL DECLARE

DEFAULT DEFERRABLE DEFERRED DELETE

222 IBM solidDB: Programmer Guide


Table 151. List of Reserved Keywords (continued)

Keyword Keyword Keyword Keyword

DESC DESCRIBE DESCRIPTOR DIAGNOSTICS

DISCONNECT DISTINCT DOMAIN DOUBLE

DROP ELSE END END-EXEC

ESCAPE EXCEPT EXCEPTION EXEC

EXECUTE EXISTS EXTERNAL EXTRACT

FALSE FETCH FIRST FLOAT

FOR FOREIGN FORTRAN FOUND

FROM FULL GET GLOBAL

GO GOTO GRANT GROUP

HAVING HOUR IDENTITY IMMEDIATE

IN INCLUDE INDEX INDICATOR

INITIALLY INNER INPUT INSENSITIVE

INSERT INT INTEGER INTERSECT

INTERVAL INTO IS ISOLATION

JOIN KEY LANGUAGE LAST

LEADING LEFT LEVEL LIKE

LOCAl LOWER MATCH MAX

MIN MINUTE MODULE MONTH

NAMES NATIONAL NATURAL NCHAR

NEXT NO NONE NOT

NULL NULLIF NUMERIC OCTET_LENGTH

OF ON ONLY OPEN

OPTION OR ORDER OUTER

OUTPUT OVERLAPS PASCAL POSITION

PRECISION PREPARE PRESERVE PRIMARY

Appendix D. Minimum SQL grammar requirements for ODBC 223


Table 151. List of Reserved Keywords (continued)

Keyword Keyword Keyword Keyword

PRIOR PRIVILEGES PROCEDURE PUBLIC

READ REAL REFERENCES RELATIVE

RESTRICT REVOKE RIGHT ROLLBACK

ROWS SCHEMA SCROLL SECOND

SECOND SECTION SELECT SESSION

SESSION_USER SET SIZE SMALLINT

SOME SPACE SQL SQLCA

SQLCODE SQLERROR SQLSTATE SQLWARNING

SUBSTRING SUM SYSTEM_USER TABLE

TEMPORARY THEN TIME TIMESTAMP

TIMEZONE_HOUR TIMEZONE_MINUTE TO TRAILING

TRANSACTION TRANSLATE TRANSLATION TRIM

TRUE UNION UNIQUE UNKNOWN

UPDATE UPPER USAGE USER

USING VALUE VALUES VARCHAR

VARYING VIEW WHEN WHENEVER

WHERE WITH WORK WRITE

YEAR ZONE

224 IBM solidDB: Programmer Guide


Appendix E. Data types
This section describes the ODBC data types.

ODBC defines the following sets of data types:


v SQL data types, which indicate the data type of data stored at the data source
(for example, the solidDB server).
v C data types, which indicate the data type of data stored in application buffers.

Each SQL data type corresponds to an ODBC C data type. Before returning data
from the data source, the driver converts it to the specified C data type. Before
sending data to the data source, the driver converts it from the specified C data
type.

For information about driver-specific SQL data types, see the driver's
documentation.

SQL data types


In accordance with the SQL-92 standard, each DBMS defines its own set of SQL
data types. For each SQL data type in the SQL-92 standard, a #define value, known
as a type identifier, is passed as an argument in ODBC functions or returned in the
metadata of a result set.

Drivers map data source-specific SQL data types to ODBC SQL data type
identifiers and driver-specific SQL data type identifiers. The
SQL_DESC_CONCISE_TYPE field of an implementation descriptor is where the
SQL data type is stored.

solidDB's ODBC driver does not support the following SQL_92 data types:
v BIT
v BIT_VARYING
v TIME_WITH_TIMEZONE
v TIMESTAMP_WITH_TIMEZONE
v NATIONAL_CHARACTER

C data types
ODBC defines the C data types and their corresponding ODBC type identifiers.

Applications call one of the following functions:


v SQLBindCol or SQLGetData to pass an applicable C type identifier in the
TargetType argument. In this way, applications specify the C data type of the
buffer that receives result set data.
v SQLBindParameter to pass the appropriate C type identifier in the ValueType
argument. In this way, applications specify the C data type of the buffer
containing a statement parameter.

The SQL_DESC_CONCISE_TYPE field of an application descriptor is where the C


data type is stored.

225
Note: Driver-specific C data types do not exist.

Data type identifiers


Data type identifiers are stored in the SQL_DESC_CONCISE_TYPE field of a
descriptor. Data type identifiers in applications describe their buffers to the driver.

They also retrieve metadata about the result set from the driver so applications
know what type of C buffers to use for data storage. Applications use data type
identifiers to perform these tasks by calling these functions:
v To describe the C data type of application buffers, applications call
SQLBindParameter, SQLBindCol, and SQLGetData.
v To describe the SQL data type of dynamic parameters, applications call
SQLBindParameter.
v To retrieve the SQL data types of result set columns, applications call
SQLColAttribute and SQLDescribeCol.
v To retrieve the SQL data types of parameters, applications call
SQLDescribeParameter.
v To retrieve the SQL data types of various schema information, applications call
SQLColumns, SQLProcedureColumns, and SQLSpecialColumns.
v To retrieve a list of supported data types, applications call SQLGetTypeInfo.

In addition, the SQLSetDescField and SQLSetDescRec descriptor functions are also


used to perform the above tasks. For details, see the SQLSetDescField and
SQLSetDescRec functions.

SQL data types


A given driver and data source do not necessarily support all of the SQL data
types defined in the ODBC grammar. Furthermore, they may support additional,
driver-specific SQL data types.

A driver's support is determined by the level of SQL-92 conformance. To determine


which data types a driver supports, an application calls SQLGetTypeInfo. See
“SQLGetTypeInfo Result Set Example” on page 229. For information about
driver-specific SQL data types, see the driver's documentation.

A driver also returns the SQL data types when it describes the data types of
columns and parameters using the following functions:
v SQLColAttribute
v SQLColumns
v SQLDescribeCol
v SQLDescribeParam
v SQLProcedureColumns
v SQLSpecialColumns

Note:

For details on fields that store SQL data type values and characteristics, see “Data
type identifiers and descriptors” on page 238.

The following table is not a comprehensive list of SQL data types, but offers
commonly used names, ranges, and limits. A data source may only support some

226 IBM solidDB: Programmer Guide


of the data types that are listed in the table and depending on your driver, the
characteristics of the data types can differ form this table's description. The table
includes the description of the associated data type from SQL-92 (if applicable)
Table 152. Common SQL Data Type Names, Ranges, and Limits

SQL Type Identifier [1] Typical SQL Data Type [2] Typical Type Description

SQL_CHAR CHAR(n) Character string of fixed string length n.

SQL_VARCHAR VARCHAR(n) Variable-length character string with a maximum


string length n.

SQL_LONGVARCHAR LONG VARCHAR Variable length character data. Maximum length is


data source-dependent. [3]

SQL_WCHAR WCHAR(n) Unicode character string of fixed string length n.

SQL_WVARCHAR VARWCHAR(n) Unicode variable-length character string with a


maximum string length n.

SQL_WLONGVARCHAR LONGWVARCHAR Unicode variable-length character data. Maximum


length is data source-dependent.

SQL_DECIMAL DECIMAL(p, s) Signed, exact, numeric value with a precision p and


scale s. (The maximum precision is driver-defined.)

(1 <= p <= 16; s <= p). [4]

SQL_NUMERIC NUMERIC(p,s) Signed, exact, numeric value with a precision p and


scale s.

(1 <= p <= 16; s <= p). [4]

SQL_SMALLINT SMALLINT Exact numeric value with precision 5 and scale 0.

(signed: -32,768 <=n <= 32,767, unsigned: 0 <= n <=


65,535)

solidDB supports only signed, not unsigned,


SMALLINT. [5]

SQL_INTEGER INTEGER Exact numeric value with precision 10 and scale 0.


(signed: -231 <= n <= 231 -1, unsigned: 0 <= n <= 232
-1) solidDB supports only signed, not unsigned,
INTEGER. [5]

SQL_REAL REAL Signed, approximate, numeric value with a binary


precision 24 (zero or absolute value 10-38 to 1038).

SQL_FLOAT FLOAT(p) Signed, approximate, numeric value with a binary


precision of at least p. (The maximum precision is
driver defined.) [6]

SQL_DOUBLE DOUBLE PRECISION Signed, approximate, numeric value with a binary


precision 53 (zero or absolute value 10-308 to 10 308
).

SQL_BIT BIT Single bit binary data. NOTE: solidDB does not
support BIT/SQL_BIT. [7]

Appendix E. Data types 227


Table 152. Common SQL Data Type Names, Ranges, and Limits (continued)

SQL Type Identifier [1] Typical SQL Data Type [2] Typical Type Description

SQL_TINYINT TINYINT Exact numeric value with precision 3 and scale 0


(signed:-128 <= n <= 127 unsigned: 0 <= n <= 255)
solidDB supports only signed, not unsigned,
TINYINT. [5].

SQL_BIGINT BIGINT Exact numeric value with precision 19 (if signed) or


20 (if unsigned) and scale 0 (signed: -263 <= n <= 263 -
1, unsigned: 0 <= n <= 264 - 1)

solidDB supports only signed, not unsigned, BIGINT.


[3], [5].

SQL_BINARY BINARY(n) Binary data of fixed length n. [3]

SQL_VARBINARY VARBINARY(n) Variable length binary data of maximum length n.


The maximum is set by the user. [3]

SQL_LONGVARBINARY LONG VARBINARY Variable length binary data. Maximum length is data
source-dependent. [3]

SQL_TYPE_DATE [8] DATE Year, month, and day fields, conforming to the rules
of the Gregorian calendar. (See “Constraints of the
gregorian calendar” on page 242.)

SQL_TYPE_TIME [8] TIME(p) Hour, minute, and second fields. Valid values for
hours are 00 to 23. Valid values for minutes are 00 to
59. Valid values for seconds are 00 to 61 (60 and 61
are to handle "leap seconds" (see
[Link] Precision p
indicates the precision of the seconds field.

SQL_TYPE_TIMESTAMP [8] TIMESTAMP(p) Year, month, day, hour, minute, and send fields, with
valid values as defined for the DATE and Time data
types.
Note:

[1] This is the value returned in the DATA_TYPE column by a call to SQLGetTypeInfo.

[2] This is the value returned in the NAME and CREATE PARAMS column by a call to SQLGetTypeInfo. The NAME column
returns the designation - for example, CHAR - while the CREATE PARAMS column returns a comma-separated list of creation
parameters such as precision, scale, and length.

[3] This data type has no corresponding data type in SQL-92.

[4] SQL_DECIMAL and SQL_NUMERIC data types differ only in their precision. The precision of a DECIMAL(p,s) is an
implementation-defined decimal precision that is no less than p, while the precision of a NUMERIC(p,s) is exactly equal to p.

[5] An application uses SQLGetTypeInfo or SQLColAttribute to determine if a particular data type or a particular column in a
result set is unsigned.

[6] Depending on the implementation, the precision of SQL_FLOAT can be either 24 or 53: if it is 24, the SQL_FLOAT data type is
the same as SQL_REAL; if it is 53, the SQL_FLOAT data type is the same as SQL_DOUBLE.

[7] The SQL_BIT data type has different characteristics than the BIT type in SQL-92.

[8] This data type has no corresponding data type in SQL-92.

228 IBM solidDB: Programmer Guide


SQLGetTypeInfo Result Set Example

Applications call SQLGetTypeInfo result set for a list of supported data types and
their characteristics for a given data source.

The example below shows the data types that SQLGetTypeInfo returns for a data
source; all data types under "DATA_TYPE" are supported in this data source.

The example below is divided into 3 sections so that it fits the width of a page. In
fact, it is all one example.
Table 153. Data types SQLGetTypeInfo returns (1)

TYPE_ COLUMN_ LITERAL_ LITERAL_ CREATE_


NAME DATA_TYPE SIZE PREFIX SUFFIX PARAMS NULLABLE

"char" SQL_CHAR 255 "" "" "length" SQL_TRUE

"text" SQL_LONG VARCHAR 2147483647 "" "" <Null> SQL_TRUE

"decimal" SQL_DECIMAL 18 [a] <Null> <Null> "precision, scale" SQL_TRUE

"real" SQL_REAL 7 <Null> <Null> <Null> SQL_TRUE

"datetime" SQL_TYPE_ 29 [b] "" "" <Null> SQL_TRUE


TIMESTAMP

Table 154. Data Types SQLGetTypeInfo Returns (2)

AUTO_
CASE_ UNSIGNED_ FIXED_ PREC_ UNIQUE_ LOCAL_ TYPE_
(continued) SENSITIVE SEARCHABLE ATTRIBUTE SCALE VALUE NAME

SQL_CHAR SQL_FALSE SQL_ <Null> SQL_FALSE <Null> "char"


SEARCHABLE

SQL_LONG SQL_FALSE SQL_PRED_ <Null> SQL_FALSE <Null> "text"


VARCHAR CHAR

SQL_DECIMAL SQL_FALSE SQL_PRED_ SQL_FALSE SQL_FALSE SQL_FALSE "decimal"


BASIC

SQL_REAL SQL_FALSE SQL_PRED_ SQL_FALSE SQL_FALSE SQL_FALSE "real"


BASIC

SQL_TYPE_ SQL_FALSE SQL_ <Null> SQL_FALSE <Null> "datetime"


TIMESTAMP SEARCHABLE

Table 155. Data Types SQLGetTypeInfo Returns (3)

SQL_
MINIMUM_ MAXIMUM_ SQL_DATA_ DATETIME_ NUM_ PREC_ INTERVAL_
(continued) SCALE SCALE TYPE SUB RADIX PRECISION

SQL_CHAR <Null> <Null> SQL_CHAR <Null> <Null> <Null>

Appendix E. Data types 229


Table 155. Data Types SQLGetTypeInfo Returns (3) (continued)

SQL_
MINIMUM_ MAXIMUM_ SQL_DATA_ DATETIME_ NUM_ PREC_ INTERVAL_
(continued) SCALE SCALE TYPE SUB RADIX PRECISION

SQL_LONG <Null> <Null> SQL_LONG <Null> <Null> <Null>


VARCHAR VARCHAR

SQL_DECIMAL 0 16 SQL_ <Null> 10 <Null>


DECIMAL

SQL_REAL <Null> <Null> SQL_REAL <Null> 10 <Null>

SQL_TYPE_ 3 3 SQL_ SQL_CODE_ <Null> 12


TIMESTAMP DATETIME TIMESTAMP

Explanations of Footnote Numbering in the Table Above

[a] 16 digits, 1 decimal point, and an optional sign character for negative numbers

[b] 29 characters to display yyyy-mm-dd hh:MM:[Link]

C data types
The solidDB ODBC Driver supports all C data types in keeping with the need for
character SQL type conversion to and from all C types.

The C data type is specified in the following functions:


v SQLBindCol and SQLGetData functions with the TargetType argument.
v SQLBindParameter with the ValueType argument.
v SQLSetDescField to set the SQL_DESC_CONCISE_TYPE field of an ARD1 or
APD2
v SQLSetDescRec with the Type argument, SubType argument (if needed), and the
DescriptorHandle argument set to the handle of an ARD or APD.
– ARD: Application Row Descriptors contain information about application
variables that are bound to columns returned by an SQL statement. The
information includes the addresses, lengths, and C data types of the bound
variables.
– APD: Application Parameter Descriptors contain information about
application variables that are bound to the parameter markers ("?") used in an
SQL statement, for example:
SELECT * FROM table1 WHERE id = ?
The information in the descriptors includes the addresses, lengths, and C data
types of the bound variables.

The table below contains the following three columns:


C Type Identifiers
The first column shows the C Type Identifiers that are passed to functions
like SQLBindCol to indicate the type of the variable that will be bound to
the column. In the following example, SQL_C_DECIMAL is a C Type
Identifier:

230 IBM solidDB: Programmer Guide


// Bind MySharedVariable to column 1 of the result set. (Column 1 is a
// DECIMAL column.) The C Type Identifier SQL_C_DECIMAL shows that the
// variable MySharedVariable is of a type equivalent to DECIMAL.
SQLBindCol(..., 1, SQL_C_DECIMAL, &MySharedVariable, ...);
ODBC C Data Type
The second columns shows the ODBC C Data Type that is associated with
each C Type Identifier. This ODBC C data type is a "typedef" that you use
to define variables in your ODBC program. This helps insulate your
program from platform-specific requirements. For example, if you have a
column of type SQL FLOAT and you want to bind a variable to that
column, you can declare your variable to be of type SQLFLOAT in the
following way:
SQLFLOAT MySharedVariable; // Can be bound to a column of type SQL FLOAT.
C Type
The third column contains an example of a C type definition that
corresponds to the ODBC C Data Type "typdef". The examples in this
column show the most frequently used definitions on 32-bit platforms.

Note: The data types specified in this column are not platform-
independent; they are examples.
// A portable way to declare a variable that will be bound to a column of
// type SQL FLOAT.
SQLFLOAT MySharedSQLFLOATVariable = 0.0;
// A non-portable way to declare a variable that will be bound to a column
// of type SQL INTEGER. This declaration works properly on most 32-bit
// platforms, but may fail on 64-bit platforms.
long int MySharedSQLINTEGERVariable = 0;
// Bind MySharedSQLFLOATVariable to column 1 of the result set.
SQLBindCol(..., 1, SQL_C_DOUBLE, &MySharedSQLFLOATVariable, ...);
// Bind MySharedSQLINTEGERVariable to column 2 of the result set.
SQLBindCol(..., 2, SQL_C_SLONG, &MySharedSQLINTEGERVariable, ...);

The C Type Identifier and the ODBC C Type do not always have similar names.
The C Type Identifier has a name based on the C language data type (for example,
"float"), while the ODBC C Typedef has a name that is based on the SQL data type.
Since C-language "float" corresponds to SQL "REAL", the table lists
"SQL_C_FLOAT" as the C Type Identifier that corresponds to the ODBC C Typedef
"SQLREAL".
Table 156. C vs ODBC Naming Correspondence

C Type identifier ODBC C Typedef C Type

SQL_C_CHAR SQLCHAR unsigned char

SQL_C_STINYINT SCHAR char

SQL_C_UTINYINT [i] UCHAR unsigned char

SQL_C_SSHORT [h] SQLSMALLINT short int

SQL_C_USHORT [h] [i] SQLUSMALLINT unsigned short int

SQL_C_SLONG [h] SQLINTEGER int

SQL_C_ULONG [h] [i] SQLUINTEGER unsigned int

Appendix E. Data types 231


Table 156. C vs ODBC Naming Correspondence (continued)

C Type identifier ODBC C Typedef C Type

SQL_C_SBIGINT SQLBIGINT _int64 [g]

SQL_C_UBIGINT [i] SQLUBIGINT unsigned _int64 [g]

solidDB does not support


unsigned data types such as
this.

SQL_C_FLOAT SQLREAL float

SQL_C_DOUBLE SQLDOUBLE double

SQLFLOAT

SQL_C_NUMERIC SQLNUMERIC unsigned char [f]

SQL_C_DECIMAL SQLDECIMAL unsigned char [f]

SQL_C_BINARY SQLCHAR * unsigned char *

struct tagDATE_STRUCT{
SQL_C_TYPE_DATE [c] SQL_DATE_STRUCT SQLSMALLINT year;
SQLUSMALLINT month;
SQLUSMALLINT day;
} DATE_STRUCT; [a]

struct tagTIME_STRUCT {
SQL_C_TYPE_TIME [c] SQL_TIME_STRUCT SQLUSMALLINT hour;
SQLUSMALLINT minute;[d]
SQLUSMALLINT second;[e]
}

struct tagTIMESTAMP_STRUCT {
SQL_C_TYPE_TIMESTAMP SQL_TIMESTAMP_STRUCT SQLSMALLINT year; [a]
[c] SQLUSMALLINT month; [b]
SQLUSMALLINT day; [c]
SQLUSMALLINT hour;
SQLUSMALLINT minute; [d]
SQLUSMALLINT second;[e]
SQLUINTEGER fraction;
}

232 IBM solidDB: Programmer Guide


Table 156. C vs ODBC Naming Correspondence (continued)

C Type identifier ODBC C Typedef C Type


Note:

[a] The values of the year, month, day, hour, minute, and second fields in the datetime C
data types must conform to the constraints of the Gregorian calendar. (See “Constraints of
the gregorian calendar” on page 242.)

[b] The value of the fraction field is the number of nanoseconds (billionths of a second)
and ranges from 0 through 999,999,999 (1 less than 1 billion). For example, the value of the
fraction field for a half-second is 500,000,000, for a thousandth of a second (one
millisecond) is 1,000,000, for a millionth of a second (one microsecond) is 1,000, and for a
billionth of a second (one nanosecond) is 1.

[c] In ODBC 2.x, the C date, time, and timestamp data types are SQL_C_DATE,
SQL_C_TIME, and SQL_C_TIMESTAMP.

[d] A number is stored in the val field of the SQL_NUMERIC_STRUCT structure as a


scaled integer, in little endian mode (the leftmost byte being the least-significant byte). For
example, the number 10.001 base 10, with a scale of 4, is scaled to an integer of 100010.
Because this is 186AA in hexadecimal format, the value in SQL_NUMERIC_STRUCT
would be "AA 86 01 00 00 ... 00", with the number of bytes defined by the
SQL_MAX_NUMERIC_LEN #define.

[e] The precision and scale fields of the SQL_C_NUMERIC data type are never used for
input from an application, only for output from the driver to the application. When the
driver writes a numeric value into the SQL_NUMERIC_STRUCT, it will use its own
driver-specific default as the value for the precision field, and it will use the value in the
SQL_DESC_SCALE field of the application descriptor (which defaults to 0) for the scale
field. An application can provide its own values for precision and scale by setting the
SQL_DESC_PRECISION and SQL_DESC_SCALE fields of the application descriptor.

[f] The DECIMAL and NUMERIC data types take up more than one byte/character. The
data types will actually be declared as arrays based on the precision required for the
column. For example, a column of type SQL DECIMAL(10,4) might be declared as
SQL_DECIMAL[13] to take into account the 10 digits, the sign character, the decimal point
character, and the string terminator.

[g] _int64 might not be supplied by some compilers.

[h] _SQL_C_SHORT, SQL_C_LONG, and SQL_C_TINYINT have been replaced in ODBC


by signed and unsigned types: SQL_C_SSHORT and SQL_C_USHORT, SQL_C_SLONG
and SQL_C_ULONG, and SQL_C_STINYINT and SQL_C_UTINYINT. An ODBC 3.x driver
that should work with ODBC 2.x applications should support SQL_C_SHORT,
SQL_C_LONG, and SQL_C_TINYINT, because when they are called, the Driver Manager
passes them through to the driver.

[i] solidDB does not support unsigned SQL data types. You may bind an unsigned C data
type to a signed SQL column, but you should not do this unless the values stored in the
SQL column and the C variable are within the valid range for both data types. For
example, since signed TINYINT columns hold values from -128 to +127, while unsigned
SQL_C_UTINYINT variables hold values from 0 to 255, you may only store values
between 0 and +127 in the column and bound variable if you want the values to be
interpreted properly.

Appendix E. Data types 233


64-Bit Integer Structures

On Microsoft C compilers, the C data type identifiers SQL_C_SBIGINT and


SQL_C_UBIGINT are defined as _int64. When a non-Microsoft C compiler is used,
the C type may differ. If the compiler in use is supporting 64-bit integers natively,
then define the driver or application ODBCINT64 as the native 64-bit integer type.
If the compiler in use does not support 64-bit integers natively, define the
following structures to ensure access to these C types:
typedef struct{
SQLUINTEGER dwLowWord;
SQLUINTEGER dwHighWord;
} SQLUBIGINT

typedef struct {
SQLUINTEGER dwLowWord;
SQLINTEGER sdwHighWord;
} SQLBIGINT

Because a 64-bit integer is aligned to the 8-byte boundary, be sure to align these
structures to an 8-byte boundary.

Note:

solidDB supports signed BIGINT, but not unsigned BIGINT.

Default C data types

In applications that specify SQL_C_DEFAULT in SQLBindCol, SQLGetData, or


SQLBindParameter, the driver assumes that the C data type of the output or input
buffer corresponds to the SQL data type of the column or parameter to which the
buffer is bound.

Important: To avoid compatibility problems when using different platforms, we


strongly recommend that you avoid using SQL_C_DEFAULT. Instead, specify the C
type of the buffer in use.

Drivers cannot always determine the correct default C type for these reasons:
v The DBMS may have promoted an SQL data type of a column or a parameter; in
this case, the driver is unable to determine the original SQL data type and
consequently, cannot determine the corresponding default C data type.
v The DBMS determined whether the data type of a column or parameter is
signed or unsigned; in this case, the driver is unable to determine this for a
particular SQL data type and consequently, cannot determine this for the
corresponding default C data type.

See “Converting data from SQL to C data types” on page 243.

SQL_C_TCHAR

The SQL_C_TCHAR type identifier is used for Unicode purposes. Use this
identifier in applications that transfer character data and are compiled to use both
ASCII and Unicode character sets. Note that the SQL_C_TCHAR is not a type
identifier in the conventional sense; instead, it is a macro contained in the header
file for Unicode conversion. SQL_C_CHAR or SQL_C_WCHAR replaces
SQL_C_TCHAR depending on the setting of the UNICODE #define.

234 IBM solidDB: Programmer Guide


Numeric literals
To store numeric data values in character strings, you use numeric literals.

Numeric literal syntax specifies what is stored in the target during the following
conversions:
v SQL data to an SQL_C_CHAR string
v C data to an SQL_CHAR or SQL_VARCHAR string

The syntax also validates what is stored in the source during the following
conversions:
v numeric stored as an SQL_C_CHAR string to numeric SQL data
v numeric stored as an SQL_CHAR string to numeric C data

For more information, see “Numeric Literal Syntax” on page 221.

Conversion Rules
The following rules apply to conversions involving numeric literals. Following are
terms used in this topic:
Table 157. Conversions Involving Numeric Literals

Term Meaning

Store assignment Refers to sending data into a table column in a database


when calling SQLExecute and SQLExecDirect. During
store assignment, "target" refers to a database column and
"source" refers to data in application buffers.

Retrieval assignment Refers to retrieving data from the database into


application buffers when calling SQLFetch, SQLGetData,
and SQLFetchScroll. During retrieval assignment, "target"
refers to the application buffers and "source" refers to the
database column.

CS Value in the character source.

NT Value in the numeric target.

NS Value in the numeric source.

CT Value in the character target.

Precision of an exact numeric Number of digits that the literal contains.


literal

Scale of an exact numeric Number of digits to the right of the expressed or implied
literal decimal point.

Precision of an approximate Precision of the literal's mantissa.


numeric literal

Appendix E. Data types 235


Rules for Character Source to Numeric Target

Following are the rules for converting from a character source (CS) to a numeric
target (NT):
1.
Replace CS with the value obtained by removing any leading or trailing spaces
in CS. If CS is not a valid numeric-literal, SQLSTATE 22018 (Invalid character
value for cast specification) is returned.
2.
Replace CS with the value obtained by removing leading zeroes before the
decimal point, trailing zeroes after the decimal point, or both.
3.
Convert CS to NT. If the conversion results in a loss of significant digits,
SQLSTATE 22003 (Numeric value out of range) is returned. If the conversion
results in the loss of nonsignificant digits, SQLSTATE 01S07 (Fractional
truncation) is returned.

Following are the rules for converting from a numeric source (NS) to a character
target (CT):
1.
Let LT be the length in characters of CT.
For retrieval assignment, LT is equal to the length of the buffer in characters
minus the number of bytes in the null-termination character for this character
set.
2.
Take one of the following actions depending on the type of NS.
v
If NS is an exact numeric type, then let YP equal the shortest character string
that conforms to the definition of exact-numeric-literal such that the scale of
YP is the same as the scale of NS, and the interpreted value of YP is the
absolute value of NS.
v
If NS is an approximate numeric type, then let YP be a character string as
follows:
Case:
a. If NS is equal to 0, then YP is the string "0".
b. Let YSN be the shortest character string that conforms to the definition of
exact-numeric-literal and whose interpreted value is the absolute value of
NS. If the length of YSN is less than the (precision + 1) of the data type of
NS, then let YP equal YSN.
c. Otherwise, YP is the shortest character string that conforms to the definition
of approximate-numeric-literal whose interpreted value is the absolute value
of NS and whose mantissa consists of a single digit that is not '0', followed
by a period and an unsigned-integer.
3. If NS is less than 0, then let Y be the result of:
’-’ || YP
where '||' is the string concatenation operator.
Otherwise, let Y equal YP.
4.
Let LY be the length in characters of Y.

236 IBM solidDB: Programmer Guide


5. Take one of the following action depending on the value of LY.
v If LY equals LT, then CT is set to Y.
v If LY is less than LT, then CT is set to Y extended on the right by appropriate
number of spaces.
v Otherwise (LY > LT), copy the first LT characters of Y into CT.
Case:
– If this is a store assignment, return the error SQLSTATE 22001 (String
data, right-truncated).
– If this is retrieval assignment, return the warning SQLSTATE 01004 (String
data, right-truncated). When the copy results in the loss of fractional digits
(other than trailing zeros), depending on the driver definition, one of the
following actions occurs:
a. The driver truncates the string in Y to an appropriate scale (which can be
zero also) and writes the result into CT.
b. The driver rounds the string in Y to an appropriate scale (which can be
zero also) and writes the result into CT.
c. The driver neither truncates nor rounds, but just copies the first LT
characters of Y into CT.

Overriding default precision and scale for numeric data types


The following table provides the override default precision and scale values for
numeric data type.
Table 158. Override Default Precision and Scale Values for Numeric Data Type

Function calls to Setting Override

SQLBindCol or SQL_DESC_TYPE field in SQL_DESC_SCALE field in the ARD is


SQLSetDescField an ARD is set to set to 0 and the
SQL_C_NUMERIC SQL_DESC_PRECISION field is set to a
driver-defined default precision. [a]

SQLBindParameter or SQL_DESC_SCALE field SQL_DESC_SCALE field in the ARD is


SQLSetDescField in an APD is set to set to 0 and the
SQL_C_NUMERIC SQL_DESC_PRECISION field is set to a
driver-defined default precision. This is
true for input, input/output, or output
parameters. [a]

SQLGetData Data is returned into an Default SQL_DESC_SCALE and


SQL_C_NUMERIC SQL_DESC_PRECISION fields are used.
structure [b]

Explanations of Footnote Numbering in the Table Above

[a] If the defaults are not acceptable for an application, the application can call the
SQLSetDescField or SQLSetDescRec to set the SQL_DESC_SCALE or
SQL_DESC_PRECISION field.

[b] If the defaults are not acceptable, the application must call SQLSetDescRec or
SQLSetDescField to set the fields and then call SQLGetData with a TargetType of
SQL_ARD_TYPE to use the values in the descriptor fields.

Appendix E. Data types 237


Data type identifiers and descriptors
Unlike the "concise" SQL and C data types, where each identifier refers to a single
data type, descriptors do not in all cases use a single value to identify data types.
In some cases, descriptors use a verbose data type and a type subcode. For most
data types, the verbose data type identifier matches the concise type identifier.

The exception, however, is the datetime and interval data types. For these data
types:
v SQL_DESC_TYPE contains the verbose type (SQL_DATETIME)
v SQL_DESC_CONCISE_TYPE contains a concise type

For details on setting fields and a setting's effect on other fields, see the
SQLSetDescField function description on the Microsoft ODBC web site.

When the SQL_DESC_TYPE or SQL_DESC_CONCISE_TYPE field is set for some


data types, the following fields are set to default values appropriate for the data
type:
v SQL_DESC_DATETIME_INTERVAL_PRECISION
v SQL_DESC_LENGTH
v SQL_DESC_PRECISION
v SQL_DESC_SCALE

For more information, see the SQL_DESC_TYPE field under SQLSetDescField


function description on the Microsoft ODBC web site.

Note: If the default values set are not appropriate, you can explicitly set the
descriptor field in the application by calling SQLSetDescField.

The following table lists for each SQL and C type identifier, the concise type
identifier, verbose identifier, and type subcode for each datetime.

For datetime data types, the SQL_DESC_TYPE have the same manifest constants
for both SQL data types (in implementation descriptors) and for C data types (in
application descriptors):
Table 159. Concise Type Identifier, Verbose Identifier, and Type Subcode for Each Datetime

DATETIME_INTERVAL_CODE
Concise SQL Type Concise C Type Verbose Type (also called "type subcode")

SQL_TYPE_DATE SQL_C_TYPE_DATE SQL_DATETIME SQL_CODE_DATE

SQL_TYPE_TIME SQL_C_TYPE_TIME SQL_DATETIME SQL_CODE_TIME

SQL_TYPE_TIMESTAMP SQL_C_TYPE_TIMESTAMP SQL_DATETIME SQL_CODE_TIME STAMP

Pseudo-type identifiers

ODBC defines a number of pseudo-type identifiers, which depending on the


situation, resolve to existing data types. Tthese identifiers do not correspond to
actual data types, but are provided for your application programming convenience.

238 IBM solidDB: Programmer Guide


Decimal digits
Decimal digits apply to decimal and numeric data types. They refer to the
maximum number of digits to the right of the decimal point, or the scale of the
data.

Because the number of digits to the right of the decimal point is not fixed, the
scale is undefined for approximate floating-point number columns or parameters.
When datetime data contains a seconds component, the decimal digits are the
number of digits to the right of the decimal point in the seconds component of the
data.

Typically, the maximum scale matches the maximum precision for SQL_DECIMAL
and SQL_NUMERIC data types. Some data sources, however, have their own
maximum scale limit. An application can call SQLGetTypeInfo to determine the
minimum and maximum scales allowed for a data type.

The following ODBC functions return parameter decimal attributes in an SQL


statement data type or decimal attributes on a data source:
Table 160. ODBC Functions' Return Parameter

ODBC Function Returns...

SQLDescribeCol Decimal digits of the columns it describes.

SQLDescribeParam Decimal digits of the parameters it describes.

SQLProcedureColumns Decimal digits in a column of a procedure.

SQLColumns Decimal digits in specified tables (such as


the base table, view, or a system table).

SQLColAttribute Decimal digits of columns at the data


source.

SQLGetTypeInfo Minimum and maximum decimal digits of


an SQL data type on a data source.

Note: The SQLBindParameter sets the decimal digits for a parameter in an SQL
statement.

The values returned by ODBC functions for decimal digits correspond to "scale" as
defined in ODBC 2.x.

Descriptor fields describe the characteristics of a result set. They do not contain
valid data values before statement execution. However, the decimal digits values
returned by SQLColumns, SQLProcedureColumns, and SQLGetTypeInfo, do
represent the characteristics of database objects, such as table columns and data
types form the data source's catalog.

Each concise SQL data type has the following decimal digits definition as noted in
the following table:

Appendix E. Data types 239


Table 161. SQL data type decimal digits

SQL Type Identifier Decimal Digits

All character and binary types [a] N/A

SQL_DECIMAL The defined number of digits to the right of


the decimal point. For example, the scale of
SQL_NUMERIC a column defined as NUMERIC(10,3) is 3.
(In some implementations, this can be a
negative number to support storage of very
large numbers without using exponential
notation; for example, "12000" could be
stored as "12" with a scale of -3. However,
solidDB does not support negative scale.)

All exact numeric types other than 0


SQL_DECIMAL and SQL_NUMERIC [a]

All approximate data types [a] N/A


Note: [a] SQLBindParameter's DecimalDigits argument is ignored for this data type.

For decimal digits, the values returned do not correspond to the values in any one
descriptor field. The values returned (for example, in SQLColAttribute) for the
decimal digits can come from either the SQL_DESC_SCALE or the
SQL_DESC_PRECISION field, depending on the data type, as shown in the
following table:
Table 162. Descriptor field corresponding to decimal digits

Descriptor field corresponding to decimal


SQL Type Identifier digits

All character and binary types N/A

All exact numeric types SCALE

All approximate numeric types N/A

All datetime types PRECISION

Transfer octet length


When data is transferred to its default C data type, an application receives a
maximum number of bytes. This maximum is known as the transfer octet length of
a column.

For character data, space for the null-termination character is not included in the
transfer octet length. Note that the transfer octet length in bytes can differ from the
number of bytes needed to store the data on the data source.

The following ODBC functions return parameter decimal attributes in an SQL


statement data type or decimal attributes on a data source:

240 IBM solidDB: Programmer Guide


Table 163. ODBC Functions' Return parameter Decimal Attributes

ODBC Function Returns

SQLColumns Transfer octet length of a column in


specified tables (such as the base table, view,
or a system table).

SQLColAttribute Transfer octet length of columns at the data


source.

SQLProcedureColumns Transfer octet length of a column in a


procedure.

The values returned by ODBC functions for the transfer octet length may not
correspond to the values returned in SQL_DESC_LENGTH. For all character and
binary types, the values come from a descriptor field's
SQL_DESC_OCTET_LENGTH. For other data types, there is no descriptor field
that stores this information.

Descriptor fields describe the characteristics of a result set. They do not contain
valid data values before statement execution. In its result set, SQLColAttribute
returns the transfer octet length of columns at the data source; these values may
not match the values in the SQL_DESC_OCTET_LENGTH descriptor fields. For
more information about descriptor fields, see SQLSetDescField function description
on the Microsoft ODBC Web site.

Each concise SQL data type has the following transfer octet length definition as
noted in the table below.
Table 164. Transfer Octet Lengths

SQL Type Identifier Transfer Octet Length

All character and binary The defined or the maximum (for variable type) length of the
types [a] column in bytes. This value matches the one in the
SQL_DESC_OCTET_LENGTH descriptor field.

SQL_DECIMAL The number of bytes required to hold the character


representation of this data if the character set is ASCII, and
SQL_NUMERIC twice this number if the character set is UNICODE. The
character representation is the maximum number of digits
plus two; the data is returned as a character string, where the
characters are needed for digits, a sign, and a decimal point.
For example, the transfer length of a column defined as
NUMERIC(10,3) is 12 because there are 10 bytes for the digits,
1 byte for the sign, and 1 byte for the decimal point.

SQL_TINYINT 1

SQL_SMALLINT 2

SQL_INTEGER 4

Appendix E. Data types 241


Table 164. Transfer Octet Lengths (continued)

SQL Type Identifier Transfer Octet Length

SQL_BIGINT The number of bytes required to hold the character


representation of this data if the character set is ASCII, and
twice this number if the character set is UNICODE. This data
type is returned as a character string by default. The character
representation consists of 20 characters for 19 digits and a sign
(if signed), or 20 digits (if unsigned). The length is 20.

solidDB supports only signed, not unsigned, BIGINT.

SQL_REAL 4

SQL_FLOAT 8

SQL_DOUBLE 8

All binary types [a] The number of bytes required to store the defined (for fixed
types) or maximum (for variable types) number of characters.

SQL_TYPE_DATE 6 (size of the structures SQL_DATE_STRUCT or


SQL_TIME_STRUCT).
SQL_TYPE_TIME

SQL_TYPE_TIMESTAMP 16 (size of the structure SQL_TIMESTAMP_STRUCT).

Explanations of Footnote Numbering in the Table Above

[a] SQL_NO_TOTAL is returned when the driver cannot determine the column or
parameter length for variable types.

Constraints of the gregorian calendar


The following table contains the Gregorian calendar constraints for date and
datetime data types.
Table 165. Constraints of the Gregorian Calendar

Value Requirement

month field Must be between 1 and 12, inclusive.

day field Range must be from 1 through the number of days in the
month, which is determined from the values of the year and
months fields and can be 28, 29, 30, or 31. A leap year can
also affect the number of days in the month.

hour field Must be between 0 and 23, inclusive.

minute field Must be between 0 and 59, inclusive.

242 IBM solidDB: Programmer Guide


Table 165. Constraints of the Gregorian Calendar (continued)

Value Requirement

trailing seconds field Must be between 0 and 61.9(n), inclusive, where n specifies
the number of digits at the place of "9" and the value of n is
the fractional seconds precision. The range of seconds permits
a maximum of two leap seconds to maintain synchronization
of sidereal time.

Converting data from SQL to C data types


This section provides information about converting data from SQL to C data types.

When an application calls SQLFetch, SQLFetchScroll, or SQLGetData, the driver


retrieves the data from the data source. If necessary, it converts the data from the
data type in which the driver retrieved it to the data type specified by the
TargetType argument in SQLBindCol or SQLGetData. Finally, it stores the data in
the location pointed to by the TargetValuePtr argument in SQLBindCol or
SQLGetData (and the SQL_DESC_DATA_PTR field of the ARD).

The following table shows the supported conversions from ODBC SQL data types
to ODBC C data types. A solid circle indicates the default conversion for an SQL
data type (the C data type to which the data will be converted when the value of
TargetType is SQL_C_DEFAULT). A hollow circle indicates a supported conversion.

For an ODBC 3.x application working with an ODBC 2.x driver, conversion from
driver-specific data types might not be supported.

The format of the converted data is not affected by the Windows country setting.

solidDB supports only signed, not unsigned, integer data types (SQL_TINYINT,
SQL_SMALLINT, SQL_INTEGER, SQL_BIGINT). You may bind an unsigned C
variable to a signed SQL column, but you must make sure that the values you
store fit within the range supported by both data types.

solidDB does not support the BIT/SQL_BIT data type for SQL columns. However,
you may bind a numeric SQL column to a BIT data type in your C application. For
example, you may use a TINYINT column in your database and bind that column
to a C variable of type SQL_C_BIT. The solidDB ODBC driver will try to convert
numeric types in the database to BIT data types for the C variables. The numeric
data values must be 1 or 0 or NULL; other values cause a data conversion error.
The table below does not discuss BIT/SQL_BIT data types.

CAUTION:
Although the table shows a wide range of ODBC conversions, including
conversions involving unsigned data types, solidDB supports only signed
integer data types (for example, TINYINT, SMALLINT, INTEGER, and BIGINT).

Appendix E. Data types 243


Table 166. C Data Type — SQL_C_datatype where Datatype Is:
T
S U I
T T T S U N M
I I I S U B B D U B E
W N N N S S S S U I I F O M I S
C C Y Y Y H H H L L L G G L U E N D T T
H H I I I O O O O O O I I O B R A A I A
A A N N N R R R N N N N N A L I R T M M
SQL Data Type R R T T T T T T G G G T T T E C Y E E P

SQL_CHAR * o o o o o o o o o o o o o o o o o o o

SQL_VARCHAR * o o o o o o o o o o o o o o o o o o o

SQL_LONGVARCHAR * o o o o o o o o o o o o o o o o o o o

SQL_WCHAR o * o o o o o o o o o o o o o o o o o o

SQL_WVARCHAR o * o o o o o o o o o o o o o o o o o o

SQL_WLONGVARCHAR o * o o o o o o o o o o o o o o o o o o

SQL_TINYINT (signed) o o * o o o o o o o o o o o o o o

SQL_TINYINT (unsigned) o o o * o o o o o o o o o o o o o

SQL_SMALLINT (signed) o o o o o * o o o o o o o o o o o

SQL_SMALLINT (unsigned) o o o o o o * o o o o o o o o o o

SQL_INTEGER (signed) o o o o o o o o * o o o o o o o o

SQL_INTEGER (unsigned) o o o o o o o o o * o o o o o o o

SQL_BIGINT (signed) o o o o o o o o o o o * o o o o

SQL_BIGINT (unsigned) o o o o o o o o o o o o * o o o o

SQL_REAL o o o o o o o o o o o o o * o o o

SQL_FLOAT o o o o o o o o o o o o o o * o o

SQL_DOUBLE o o o o o o o o o o o o o o * o o

SQL_DECIMAL * o o o o o o o o o o o o o o o o

SQL_NUMERIC * o o o o o o o o o o o o o o o o

SQL_BINARY o o *

SQL_VARBINARY o o *

SQL_LONGVARBINARY o o *

244 IBM solidDB: Programmer Guide


Table 166. C Data Type — SQL_C_datatype where Datatype Is: (continued)
T
S U I
T T T S U N M
I I I S U B B D U B E
W N N N S S S S U I I F O M I S
C C Y Y Y H H H L L L G G L U E N D T T
H H I I I O O O O O O I I O B R A A I A
A A N N N R R R N N N N N A L I R T M M
SQL Data Type R R T T T T T T G G G T T T E C Y E E P

SQL_TYPE_DATE o o o * o

SQL_TYPE_TIME o o o * o

SQL_TYPE_TIMESTAMP o o o o o *

* These datatypes have the word "TYPE" in the datatype name. For example,
SQL_C_TYPE_DATE, SQL_C_TYPE_TIME, and SQL_C_TYPE_TIMESTAMP.

Legend:

* Default Conversion

o Supported Conversion

Data conversion tables from SQL to C


The tables in the following sections describe how the driver or data source
converts data retrieved from the data source; drivers are required to support
conversions to all ODBC C data types from the ODBC SQL data types that they
support.

Conversion Table Description (SQL to C)

The following columns are included in the tables:


v For a given ODBC SQL data type, the first column of the table lists the legal
input values of the TargetType argument in SQLBindCol and SQLGetData.
v The second column lists the outcomes of a test, often using the BufferLength
argument specified in SQLBindCol or SQLGetData, which the driver performs to
determine if it can convert the data.
v For each outcome, the third and fourth columns list the values placed in the
buffers specified by the TargetValuePtr and StrLen_or_IndPtr arguments
specified in SQLBindCol or SQLGetData after the driver has attempted to
convert the data. (The StrLen_or_IndPtr argument corresponds to the
SQL_DESC_OCTET_LENGTH_PTR field of the ARD.)
v The last column lists the SQLSTATE returned for each outcome by SQLFetch,
SQLFetchScroll, or SQLGetData.

If the TargetType argument in SQLBindCol or SQLGetData contains a value for an


ODBC C data type not shown in the table for a given ODBC SQL data type,
SQLFetch, SQLFetchScroll, or SQLGetData returns SQLSTATE 07006 (Restricted
data type attribute violation). If the TargetType argument contains a value that
specifies a conversion from a driver-specific SQL data type to an ODBC C data

Appendix E. Data types 245


type and this conversion is not supported by the driver, SQLFetch, SQLFetchScroll,
or SQLGetData returns SQLSTATE HYC00 (Optional feature not implemented).

Although it is not shown in the tables, the driver returns SQL_NULL_DATA in the
buffer specified by the StrLen_or_IndPtr argument when the SQL data value is
NULL. The length specified by StrLen_or_IndPtr does not include the
null-termination byte. If TargetValuePtr is a null pointer, SQLGetData returns
SQLSTATE HY009 (Invalid use of null pointer); in SQLBindCol, this unbinds the
columns.

The following terms and conventions are used in the tables:


v Byte length of data is the number of bytes of C data available to return in *
TargetValuePtr, whether or not the data will be truncated before it is returned to
the application. For string data, this does not include the space for the
null-termination character.
v Character byte length is the total number of bytes needed to display the data in
character format.
v Words in italics represent function arguments or elements of the SQL grammar.
See Appendix D, “Minimum SQL grammar requirements for ODBC,” on page
217 for the syntax of grammar elements.

SQL to C: Character

The character ODBC SQL data types are:


SQL_CHAR
SQL_VARCHAR
SQL_LONGVARCHAR
SQL_WCHAR
SQL_WVARCHAR
SQL_WLONGVARCHAR

The following table shows the ODBC C data types to which character SQL data
can be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (SQL to C)” on page 245.
Table 167. Character SQL Data to ODBC C Data Types

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_CHAR Byte length of data < Data Length of data in N/A


BufferLength bytes
Truncated data 01004
Byte length of data >= Length of data in
BufferLength bytes

SQL_C_WCHAR Character length of data < Data Length of data in N/A


BufferLength characters
Truncated data 01004
(Character length of data) >= Length of data in
BufferLength characters

246 IBM solidDB: Programmer Guide


Table 167. Character SQL Data to ODBC C Data Types (continued)

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

EXACT NUMERIC TYPES Data converted without Data Number of bytes of N/A
[h] truncation [b] the C data type
Truncated data 01S07
SQL_C_STINYINT Data converted with Number of bytes of
truncation of fractional digits Undefined the C data type 22003
SQL_C_UTINYINT [a]
Undefined Undefined 22018
SQL_C_TINYINT Conversion of data would
result in loss of whole (as Undefined
SQL_C_SSHORT opposed to fractional) digits
[b]
SQL_C_USHORT
Data is not a numeric-literal
SQL_C_SHORT
[b]
SQL_C_SLONG

SQL_C_ULONG

SQL_C_LONG

SQL_C_SBIGINT

SQL_C_UBIGINT

SQL_C_NUMERIC

APPROXIMATE NUMERIC Data is within the range of Data Size of the C data N/A
TYPES [h] the data type to which the type
number is being converted Undefined 2003
SQL_C_FLOAT [a] Undefined
Undefined 22018
SQL_C_DOUBLE Data is outside the range of Undefined
the data type to which the
number is being converted
[a]

Data is not a numeric-literal


[b]

SQL_C_BINARY Byte length of data <= Data Length of data N/A


BufferLength
Truncated data Length of data 01004
Byte length of data >
BufferLength

Appendix E. Data types 247


Table 167. Character SQL Data to ODBC C Data Types (continued)

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_TYPE_DATE Data value is a valid Data 6 [b] N/A


date-value [a]
Data 6 [b] N/A
Data value is a valid
timestamp-value; time Truncated data 6 [b] 01S07
portion is zero [a]
Undefined Undefined 22018
Data value is a valid
timestamp-value; time
portion is nonzero [a], [c],

Data value is not a valid


date-value or
timestamp_value [a]

SQL_C_TYPE_TIME Data value is a valid Data 6 [b] N/A


time-value and the fractional
seconds value is 0 [a] Data 6 [b] N/A

Data value is a valid Truncated data 6 [b] 01S07


timestamp-value or a valid
time_value; fractional Undefined Undefined 22018
seconds portion is zero
[a],[d]

Data value is a valid


timestamp-value ; fractional
seconds portion is nonzero
[a], [d], [e]

Data value is not a valid


timestamp-value or
time_value [a]

SQL_C_TYPE_TIMESTAMP Data value is a valid Data 16 [b] N/A


timestamp-value or a valid
time_value; fractional Truncated data 16 [b] 01S07
seconds portion not
truncated [a], [d] Data [f] 16 [b] N/A

Data value is a valid Data [g] 16 [b] N/A


timestamp-value or a valid
Undefined Undefined 22018
time_value; fractional
seconds portion truncated [a]

Data value is a valid


date-value [a]

Data value is a valid


time_value [a]

Data value is not a valid


date_value, time_value, or
timestamp_value [a]

248 IBM solidDB: Programmer Guide


Table 167. Character SQL Data to ODBC C Data Types (continued)

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE


Note:

[a] The value of BufferLength is ignored for this conversion. The driver assumes that the size of *TargetValuePtr is
the size of the C data type.

[b] This is the size of the corresponding C data type.

[c] The time portion of the timestamp-value is truncated.

[d] The date portion of the timestamp-value is ignored.

[e] The fractional seconds portion of the timestamp is truncated.

[f] The time fields of the timestamp structure are set to zero.

[g] The date fields of the timestamp structure are set to the current date.

[h] The exact numeric types include NUMERIC/DECIMAL as well as integer. These data types store the exact value
that you specify, as long as it is within the precision of the data type. The approximate data types include
FLOAT/REAL, which store only approximately the value that you specify (in some cases, the least significant digit
may be slightly different from what you specified).

When character SQL data is converted to numeric, date, time, or timestamp C data,
leading and trailing spaces are ignored.

SQL to C: Numeric
SQL_DECIMAL SQL_BIGINT
SQL_NUMERIC SQL_REAL
SQL_TINYINT SQL_FLOAT
SQL_SMALLINT SQL_DOUBLE
SQL_INTEGER

The following table shows the ODBC C data types to which numeric SQL data
may be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (SQL to C)” on page 245.
Table 168. SQL Data to ODBC C Data Types

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_CHAR Character byte length < Data Length of data in N/A


BufferLength bytes
Truncated data 01004
Number of whole (as opposed Length of data in
to fractional) digits < Undefined bytes 22003
BufferLength
Undefined
Number of whole (as opposed
to fractional) digits ≥
BufferLength

Appendix E. Data types 249


Table 168. SQL Data to ODBC C Data Types (continued)

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_WCHAR Character length < BufferLength Data Length of data in N/A


bytes
Number of whole (as opposed Truncated data 01004
to fractional) digits < Length of data in
BufferLength Undefined bytes 22003

Number of whole (as opposed Undefined


to fractional) digits ≥
BufferLength

EXACT NUMERIC Data converted without Data Size of the C data N/A
TYPES [c] truncation [a] type
Truncated data 01S07
SQL_C_STINYINT Data converted with truncation Size of the C data
of fractional digits [a] Undefined type 22003
SQL_C_UTINYINT
Conversion of data would result Undefined
SQL_C_TINYINT in loss of whole (as opposed to
fractional) digits [a]
SQL_C_SBIGINT

SQL_C_UBIGINT

SQL_C_SSHORT

SQL_C_USHORT

SQL_C_SHORT a

SQL_C_SLONG

SQL_C_ULONG

SQL_C_LONG

SQL_C_NUMERIC

APPROXIMATE Data is within the range of the Data Size of the C data N/A
NUMERIC TYPES [c] data type to which the number type
is being converted [a] Undefined 22003
SQL_C_FLOAT Undefined
Data is outside the range of the
SQL_C_DOUBLE data type to which the number
is being converted [a]

SQL_C_BINARY Length of data ≤ BufferLength Data Length of data N/A

Length of data > BufferLength Undefined Undefined 22003

250 IBM solidDB: Programmer Guide


Table 168. SQL Data to ODBC C Data Types (continued)

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE


Note:

[a] The value of BufferLength is ignored for this conversion. The driver assumes that the size of *TargetValuePtr is
the size of the C data type.

[b] This is the size of the corresponding C data type.

[c] The exact numeric types include NUMERIC/DECIMAL as well as integer. These data types store the exact value
that you specify, as long as it is within the precision of the data type. The approximate data types include
FLOAT/REAL, which store only approximately the value that you specify (in some cases, the least significant digit
may be slightly different from what you specified).

SQL to C: Binary

The binary ODBC SQL data types are:


SQL_BINARY
SQL_VARBINARY
SQL_LONGVARBINARY

The following table shows the ODBC C data types to which binary SQL data may
be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (SQL to C)” on page 245.
Table 169. Binary SQL Data to ODBC C Data Types

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_CHAR (Byte length of data) * 2 < Data Length of data in N/A


BufferLength bytes
Truncated data 01004
(Byte length of data) * 2 >= Length of data in
BufferLength bytes

SQL_C_WCHAR (Character length of data) * 2 Data Length of data in N/A


< BufferLength bytes
Truncated data 01004
(Character length of data) * 2 Length of data in
>= BufferLength bytes

SQL_C_BINARY Byte length of data <= Data Length of data in N/A


BufferLength bytes
Truncated data 01004
Byte Length of data > Length of data in
BufferLength bytes

When binary SQL data is converted to character C data, each byte (8 bits) of source
data is represented as two ASCII characters. These characters are the ASCII
character representation of the number in its hexadecimal form. For example, a
binary 00000001 is converted to "01"and a binary 11111111 is converted to "FF".

T he driver always converts individual bytes to pairs of hexadecimal digits and


terminates the character string with a null byte. Because of this, if BufferLength is
even and is less than the length of the converted data, the last byte of the

Appendix E. Data types 251


*TargetValuePtr buffer is not used. (The converted data requires an even number of
bytes, the next-to-last byte is a null byte, and the last byte cannot be used.)

Application developers are discouraged from binding binary SQL data to a


character C data type. This conversion is usually inefficient and slow.

SQL to C: Date

The date ODBC SQL data type is:


SQL_DATE

The following table shows the ODBC C data types to which date SQL data may be
converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (SQL to C)” on page 245.
Table 170. Date SQL Data to ODBC C Data Types

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_CHAR BufferLength > Character byte Data 10 N/A


length
Truncated data Length of data in 01004
11<= BufferLength <= bytes
Character byte length Undefined 22003
Undefined
BufferLength < 11

SQL_C_WCHAR BufferLength > Character Data 10 N/A


length
Truncated data Length of data in 01004
11<= BufferLength <= bytes
Character length Undefined 22003
Undefined
BufferLength < 11

SQL_C_BINARY Byte length of data <= Data Length of data in N/A


BufferLength bytes
Undefined 22003
Byte length of data > Undefined
BufferLength

SQL_C_DATE None [a] Data 6 [c] N/A

SQL_C_TIMESTAMP None [a] Data [b] 16 [c] N/A


Note:

[a] The value of BufferLength is ignored for this conversion. The driver assumes that the size of *TargetValuePtr is
the size of the C data type.

[b] The time fields of the timestamp structure are set to zero.

[c] This is the size of the corresponding C data type.

When date SQL data is converted to character C data, the resulting string is in the
"yyyy-mm-dd"format. This format is not affected by the Windows country setting.

252 IBM solidDB: Programmer Guide


SQL to C: Time

The time ODBC SQL data type is:


SQL_TIME

The following table shows the ODBC C data types to which time SQL data may be
converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (SQL to C)” on page 245.
Table 171. Time SQL Data to ODBC C Data Types

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_CHAR BufferLength > Character byte Data Length of data in N/A


length bytes
Truncated data 01004
9 <= BufferLength <= Character [a] Length of data in
byte length bytes 22003
Undefined
BufferLength < 9 Undefined

SQL_C_WCHAR BufferLength > Character byte Data Length of data in N/A


length 9 <= BufferLength <= characters
Character byte length Truncated data 01004
BufferLength < 9 [a] Length of data in
characters 22003
Undefined
Undefined

SQL_C_BINARY Byte length of data <= Data Length of data in N/A


BufferLength bytes
Undefined 22003
Byte length of data > Undefined
BufferLength

SQL_C_DATE None [a] Data 6 [c] N/A

SQL_C_TIMESTAMP None [a] Data [b] 16 [c] N/A


Note:

[a]: The fractional seconds of the time are truncated.

[b]: The value of BufferLength is ignored for this conversion. The driver assumes that the size of *TargetValuePtr is
the size of the C data type.

[c]: The date fields of the timestamp structure are set to the current date and the fractional seconds field of the
timestamp structure is set to zero.

[d]: This is the size of the corresponding C data type.

When time SQL data is converted to character C data, the resulting string is in the
"hh:mm:ss "format.

SQL to C: Timestamp

The timestamp ODBC SQL data type is:


SQL_TIMESTAMP

Appendix E. Data types 253


The following table shows the ODBC C data types to which timestamp SQL data
may be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (SQL to C)” on page 245.
Table 172. Timestamp SQL Data to ODBC C Data Types

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE

SQL_C_CHAR BufferLength > Character Data Length of data in N/A


byte length bytes
Truncated data 01004
20 <= BufferLength <= [b] Length of data in
Character byte length bytes 22003
Undefined
BufferLength < 20 Undefined

SQL_C_WCHAR BufferLength > Character Data Length of data in N/A


byte length characters
Truncated data 01004
20 <= BufferLength <= [b] Length of data in
Character byte length characters 22003
Undefined
BufferLength < 20 Undefined

SQL_C_BINARY Byte length of data <= Data Length of data in N/A


BufferLength bytes
Undefined 22003
Byte length of data > Undefined
BufferLength

SQL_C_TYPE_DATE Time portion of timestamp is Data 6 [f] N/A


zero [a]
Truncated data 6 [f] 01S07
Time portion of timestamp is [c]
non-zero [a]

SQL_C_TYPE_TIME Fractional seconds portion of Data [d] 6 [f] N/A


timestamp is zero [a]
Truncated data 6 [f] 01S07
Fractional seconds portion of [d], [e]
timestamp is non-zero [a]

SQL_C_TYPE_TIMESTAMP Fractional seconds portion of Data [e] 6 [f] N/A


timestamp is not truncated
[a] Truncated data 6 [f] 01S07
[e]
Fractional seconds portion of
timestamp is truncated [a]

254 IBM solidDB: Programmer Guide


Table 172. Timestamp SQL Data to ODBC C Data Types (continued)

C Type Identifier Test *TargetValuePtr *StrLen_or_IndPtr SQLSTATE


Note:

[a] The value of BufferLength is ignored for this conversion. The driver assumes that the size of *TargetValuePtr is
the size of the C data type.

[b] The fractional seconds of the timestamp are truncated.

[c] The time portion of the timestamp is truncated.

[d] The date portion of the timestamp is ignored.

[e] The fractional seconds portion of the timestamp is truncated.

[f] This is the size of the corresponding C data type.

When timestamp SQL data is converted to character C data, the resulting string is
in the "yyyy-mm-dd hh:mm:ss [ .f ...]"format, where up to nine digits may be used
for fractional seconds. The format is not affected by the Windows country setting.
(Except for the decimal point and fractional seconds, the entire format must be
used, regardless of the precision of the timestamp SQL data type.)

SQL to C data conversion examples


The following examples illustrate how the driver converts SQL data to C data.
Table 173. SQL to C Data Conversion Examples

SQL Data Buffer


SQL Type Identifier Values C Type Identifier Length *TargetValuePtr SQLSTATES

SQL_CHAR abcdef SQL_C_CHAR 7 abcdef\0 [a] N/A

SQL_CHAR abcdef SQL_C_CHAR 6 abcde\0 [a] 01004

SQL_DECIMAL 1234.56 SQL_C_CHAR 8 1234.56\0 [a] N/A

SQL_DECIMAL 1234.56 SQL_C_CHAR 5 1234\0 [a] 01004

SQL_DECIMAL 1234.56 SQL_C_CHAR 4 ---- 22003

SQL_DECIMAL 1234.56 SQL_C_FLOAT ignored 1234.56 N/A

SQL_DECIMAL 1234.56 SQL_C_SSHORT ignored 1234 01S07

SQL_DECIMAL 1234.56 SQL_C_STINYINT ignored ---- 22003

SQL_DOUBLE 1.2345678 SQL_C_DOUBLE ignored 1.2345678 N/A

SQL_DOUBLE 1.2345678 SQL_C_FLOAT ignored 1.234567 N/A

SQL_DOUBLE 1.2345678 SQL_C_STINYINT ignored 1 N/A

Appendix E. Data types 255


Table 173. SQL to C Data Conversion Examples (continued)

SQL Data Buffer


SQL Type Identifier Values C Type Identifier Length *TargetValuePtr SQLSTATES

SQL_TYPE_DATE 1992-12-31 SQL_C_CHAR 11 1992-12-31\0 [a] N/A

SQL_TYPE_DATE 1992-12-31 SQL_C_CHAR 10 ----- 22003

SQL_TYPE_DATE 1992-12-31 SQL_C_ ignored 1992,12,31, 0,0,0,0 N/A


TIMESTAMP [b]

SQL_TYPE_TIMESTAMP 1992-12-31 SQL_C_CHAR 23 1992-12-31 N/A


23:45:55.12 23:45:55.12\0 [a]

SQL_TYPE_TIMESTAMP 1992-12-31 SQL_C_CHAR 22 1992-12-31 01004


23:45:55.12 23:45:55.1\0 [a]

SQL_TYPE_TIMESTAMP 1992-12-31 SQL_C_CHAR 18 ---- 22003


23:45:55.12

[a] "\0"represents a null-termination byte. The driver always null-terminates


SQL_C_CHAR data.

[b] The numbers in this list are the numbers stored in the fields of the
TIMESTAMP_STRUCT structure.

Converting data from C to SQL data types


This section provides information about converting data from C to SQL data types.

When an application calls SQLExecute or SQLExecDirect, the driver retrieves the


data for any parameters bound with SQLBindParameter from storage locations in
the application. For data-at-execution parameters, the application sends the
parameter data with SQLPutData. If necessary, the driver converts the data from
the data type specified by the ValueType argument in SQLBindParameter to the
data type specified by the ParameterType argument in SQLBindParameter. Finally,
the driver sends the data to the data source.

The following table shows the supported conversions from ODBC C data types to
ODBC SQL data types. A solid circle indicates the default conversion for an SQL
data type (the C data type from which the data will be converted when the value
of ValueType or the SQL_DESC_CONCISE_TYPE descriptor field is
SQL_C_DEFAULT). A hollow circle indicates a supported conversion.

The format of the converted data is not affected by the Windows country setting.

solidDB supports only signed, not unsigned, integer data types (SQL_TINYINT,
SQL_SMALLINT, SQL_INTEGER, SQL_BIGINT). You may bind an unsigned C
variable to a signed SQL column, but you must make sure that the values you
store fit within the range supported by both data types.

solidDB does not support the BIT/SQL_BIT data type for SQL columns. However,
you may bind a numeric SQL column to a BIT data type in your C application. For

256 IBM solidDB: Programmer Guide


example, you may use a TINYINT column in your database and bind that column
to a C variable of type SQL_C_BIT. The solidDB ODBC driver will try to convert
numeric types in the database to BIT data types for the C variables. The numeric
data values must be 1 or 0 or NULL; other values cause a data conversion error.
The table below does not discuss BIT/SQL_BIT data types.

CAUTION:
Although the table above shows a wide range of ODBC conversions, including
conversions involving unsigned data types, solidDB supports only signed
integer data types (for example, TINYINT, SMALLINT, INT, and BIGINT).
Table 174. SQL Data Type — SQL_datatype where Datatype Is:
T S I
I M N B
T N S A I T I
I Y M L N E B G
N I A L T G I I L
W Y N L I E E G N O
L L I T L N G R I T N
O O N ( I T E ( N ( G
N N T u N (u R u T u V V T
G W G ( n T n ( n ( n A A I
V V V V D N s s (s s s s s s R R M
A A A A E U i i i i i i i i D B B B E
R R W R R C M g g g g g g g g F O I I I S
C C C C C C I E n n n n n n n n R L U N N N D T T
H H H H H H M R e e e e e e e e E O B A A A A I A
A A A A A A A I d d d d d d d d A A L R R R T M M
C Data Type R R R R R R L C ) ) ) ) ) ) ) ) L T E Y Y Y E E P

SQL_C_CHAR * * * o o o * * o o o o o o o o o o o o o o o o o

SQL_WCHAR o o o * * * o o o o o o o o o o o o o o o o o o o

SQL_C_NUMERIC * o o o o o o o o o o o o o o o o o o

SQL_C_STINYINT o o o o o o o o * o o o o o o o o o o

SQL_C_UTINYINT o o o o o o o o o * o o o o o o o o o

SQL_C_TINYINT o o o o o o o o o o o o o o o o o o o

SQL_C_SSHORT o o o o o o o o o o * o o o o o o o o

SQL_C_USHORT o o o o o o o o o o o * o o o o o o o

SQL_C_SHORT o o o o o o o o o o o o o o o o o o o

SQL_C_SLONG o o o o o o o o o o o o * o o o o o o

SQL_C_ULONG o o o o o o o o o o o o o * o o o o o

SQL_C_LONG o o o o o o o o o o o o o o o o o o o

SQL_C_SBIGINT o o o o o o o o o o o o o o * * o o o

SQL_C_UBIGINT o o o o o o o o o o o o o o o * o o o

SQL_C_FLOAT o o o o o o o o o o o o o o o o * o o

Appendix E. Data types 257


Table 174. SQL Data Type — SQL_datatype where Datatype Is: (continued)
T S I
I M N B
T N S A I T I
I Y M L N E B G
N I A L T G I I L
W Y N L I E E G N O
L L I T L N G R I T N
O O N ( I T E ( N ( G
N N T u N (u R u T u V V T
G W G ( n T n ( n ( n A A I
V V V V D N s s (s s s s s s R R M
A A A A E U i i i i i i i i D B B B E
R R W R R C M g g g g g g g g F O I I I S
C C C C C C I E n n n n n n n n R L U N N N D T T
H H H H H H M R e e e e e e e e E O B A A A A I A
A A A A A A A I d d d d d d d d A A L R R R T M M
C Data Type R R R R R R L C ) ) ) ) ) ) ) ) L T E Y Y Y E E P

SQL_C_DOUBLE o o o o o o o o o o o o o o o o o * *

SQL_C_BINARY o o o o o o o o o o o o o o o o o o o * * * o o o

SQL_C_DATE o o o o o o * o

SQL_C_TIME o o o o o o * o

SQL_C_TIMESTAMP o o o o o o o o *

Legend:

* Default conversion,

o Supported conversion

Data conversion tables from C to SQL


The tables in the following sections describe how the driver or data source
converts data sent to the data source; drivers are required to support conversions
from all ODBC C data types to the ODBC SQL data types that they support.

Conversion Table Description (C to SQL)

The following columns are included in the tables:


v For a given ODBC C data type, the first column of the table lists the legal input
values of the ParameterType argument in SQLBindParameter.
v The second column lists the outcomes of a test that the driver performs to
determine if it can convert the data.
v The third column lists the SQLSTATE returned for each outcome by
SQLExecDirect, SQLExecute, or SQLPutData. Data is sent to the data source only
if SQL_SUCCESS is returned.

If the ParameterType argument in SQLBindParameter contains a value for an


ODBC SQL data type that is not shown in the table for a given C data type,
SQLBindParameter returns SQLSTATE 07006 (Restricted data type attribute
violation). If the ParameterType argument contains a driver-specific value and the

258 IBM solidDB: Programmer Guide


driver does not support the conversion from the specific ODBC C data type to that
driver-specific SQL data type, SQLBindParameter returns SQLSTATE HYC00
(Optional feature not implemented).

If the ParameterValuePtr and StrLen_or_IndPtr arguments specified in


SQLBindParameter are both null pointers, that function returns SQLSTATE HY009
(Invalid use of null pointer). Although it is not shown in the tables, an application
sets the value pointed to by the StrLen_or_IndPtr argument of SQLBindParameter
or the value of the StrLen_or_IndPtr argument to SQL_NULL_DATA to specify a
NULL SQL data value. (The StrLen_or_IndPtr argument corresponds to the
SQL_DESC_OCTET_LENGTH_PTR field of the APD.) The application sets these
values to SQL_NTS to specify that the value in *ParameterValuePtr in
SQLBindParameter or *DataPtr in SQLPutData (pointed to by the
SQL_DESC_DATA_PTR field of the APD) is a null-terminated string.

The following terms are used in the tables:


v Byte length of data is the number of bytes of SQL data available to send to the
data source, regardless of whether the data will be truncated before it is sent to
the data source. For string data, this does not include the null-termination
character.
v Column byte length is the number of bytes required to store the data at the data
source.
v Character byte length is the maximum number of bytes needed to display data in
character form.
v Number of digits is the number of characters used to represent a number,
including the minus sign, decimal point, and exponent (if needed).
v Words in italics represent elements of the ODBC SQL grammar. For the syntax of
grammar elements, see Appendix D, “Minimum SQL grammar requirements for
ODBC,” on page 217.

C to SQL: Character

The character ODBC C data type is:

SQL_C_CHAR SQL_C_WCHAR

The following table shows the ODBC SQL data types to which C character data
may be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (C to SQL)” on page 258.

Note: The length of the Unicode data type must be an even number when
character C data is converted to Unicode SQL data.
Table 175. C Character Data to ODBC SQL Data Types

SQL Type Identifier Test SQLSTATE

SQL_CHAR Byte length of data <= Column N/A


length
SQL_VARCHAR 22001
Byte length of data > Column length
SQL_LONGVARCHAR

Appendix E. Data types 259


Table 175. C Character Data to ODBC SQL Data Types (continued)

SQL Type Identifier Test SQLSTATE

SQL_WCHAR Character length of data <= Column N/A


length
SQL_WVARCHAR 22001
Character length of data > Column
SQL_WLONGVARCHAR length

SQL_DECIMAL Data converted without truncation N/A

SQL_NUMERIC Data converted with truncation of 22001


fractional digits [e]
SQL_TINYINT 22001
Conversion of data would result in
SQL_SMALLINT loss of whole (as opposed to 22018
fractional) digits [e]
SQL_INTEGER
Data value is not a numeric-literal
SQL_BIGINT

SQL_REAL Data is within the range of the data N/A


type to which the number is being
SQL_FLOAT converted 22003

SQL_DOUBLE Data is outside the range of the data 22005


type to which the number is being
converted

Data value is not a numeric-literal

SQL_BIT Data is 0 or 1 N/A

Data is greater than 0, less than 2, 22001


and not equal to 1
22003
Data is less than 0 or greater than or
equal to 2 22018

Data is not a numeric-literal.

Note: solidDB does not support


SQL_BIT.

SQL_BINARY (Byte length of data) / 2 <= Column N/A


byte length
SQL_VARBINARY 22001
(Byte length of data) / 2 > Column
SQL_LONG-VARBINARY byte length 22018

Data value is not a hexadecimal


value

260 IBM solidDB: Programmer Guide


Table 175. C Character Data to ODBC SQL Data Types (continued)

SQL Type Identifier Test SQLSTATE

SQL_TYPE_DATE Data value is a valid N/A


ODBC_date_literal
N/A
Data value is a valid
ODBC_timestamp_literal; time portion 22008
is zero
22018
Data value is a valid
ODBC_timestamp_literal; time portion
is non-zero [a]

Data value is not a valid


ODBC_date_literal or
ODBC_timestamp_literal

SQL_TYPE_TIME Data value is a valid N/A


ODBC_time_literal
N/A
Data value is a valid
ODBC_timestamp_literal; fractional 22008
seconds portion is zero [b]
22018
Data value is a valid
ODBC_timestamp_literal; fractional
seconds portion is non-zero [b]

Data value is not a valid


ODBC_time_literal or
ODBC_timestamp_literal

SQL_TYPE_TIMESTAMP Data value is a valid N/A


ODBC_timestamp_literal; fractional
seconds portion not truncated 22008

Data value is a valid N/A


ODBC-timestamp-literal; fractional
seconds portion truncated N/A

Data value is a valid 22018


ODBC-date-literal [c]

Data value is a valid


ODBC-time-literal [d]

Data value is not a valid


ODBC-date-literal, ODBC-time-literal,
or ODBC-timestamp-literal

Appendix E. Data types 261


Table 175. C Character Data to ODBC SQL Data Types (continued)

SQL Type Identifier Test SQLSTATE


Note:

[a] The time portion of the timestamp is truncated.

[b] The date portion of the timestamp is ignored.

[c] The time portion of the timestamp is set to zero.

[d] The date portion of the timestamp is set to the current date.

[e] The driver/data source effectively waits until the entire string has been received (even if the character data is
sent in pieces by calls to SQLPutData) before attempting to perform the conversion.

When character C data is converted to numeric, date, time, or timestamp SQL data,
leading and trailing blanks are ignored.

When character C data is converted to binary SQL data, each two bytes of
character data are converted to a single byte (8 bits) of binary data. Each two bytes
of character data represent a number in hexadecimal form. For example, "01" is
converted to a binary 00000001 and "FF" is converted to a binary 11111111.

The driver always converts pairs of hexadecimal digits to individual bytes and
ignores the null termination byte. Because of this, if the length of the character
string is odd, the last byte of the string (excluding the null termination byte, if any)
is not converted.

Note: Because binding character C data to a binary SQL data type is inefficient
and slow, refrain from doing this.

C to SQL: Numeric

The numeric ODBC C data types are:


v SQL_C_STINYINT
v SQL_C_SLONG
v SQL_C_UTINYINT
v SQL_C_ULONG
v SQL_C_TINYINT
v SQL_C_LONG
v SQL_C_SSHORT
v SQL_C_FLOAT
v SQL_C_USHORT
v SQL_C_DOUBLE
v SQL_C_SHORT
v SQL_C_NUMERIC
v SQL_C_SBIGINT
v SQL_C_UBIGINT

For more information about the SQL_C_TINYINT, SQL_C_SHORT, and


SQL_C_LONG data types, see “C data types” on page 230. The following table
262 IBM solidDB: Programmer Guide
shows the ODBC SQL data types to which numeric C data may be converted. For
an explanation of the columns and terms in the table, see “Conversion Table
Description (C to SQL)” on page 258.
Table 176. Numeric C Data to ODBC SQL Data Types

ParameterType Test SQLSTATE

SQL_CHAR Number of digits <= Column N/A


byte length
SQL_VARCHAR 22001
Number of digits > Column
SQL_LONGVARCHAR byte length

SQL_WCHAR Number of characters <= N/A


Column character length
SQL_WVARCHAR 22001
Number of characters >
SQL_WLONGVARCHAR Column character length

SQL_DECIMAL [a] Data converted without N/A


truncation or with truncated
SQL_NUMERIC [a] of fractional digits 22003

SQL_TINYINT [a] Data converted with


truncation of whole digits
SQL_SMALLINT [a]

SQL_INTEGER [a]

SQL_BIGINT [a]

SQL_REAL Data is within the range of N/A


the data type to which the
SQL_FLOAT number is being converted 22003

SQL_DOUBLE Data is outside the range of


the data type to which the
number is being converted
Note:

[a] For the "n/a" case, a driver may optionally return SQL_SUCCESS_WITH_INFO and
01S07 when there is a fractional truncation.

The driver ignores the length or indicator value when converting data from the
numeric C data types and assumes that the size of the data buffer is the size of the
numeric C data type. The length or indicator value is passed in the
StrLen_or_IndPtr argument in SQLPutData and in the buffer specified with the
StrLen_or_IndPtr argument in SQLBindParameter. The data buffer is specified with
the DataPtr argument in SQLPutData and the ParameterValuePtr argument in
SQLBindParameter.

C to SQL: Bit

The bit ODBC C data type is:


SQL_C_BIT

Appendix E. Data types 263


The following table shows the ODBC SQL data types to which bit C data may be
converted. For an explanation of the columns and terms in the table, see For an
explanation of the columns and terms in the table, see “Conversion Table
Description (C to SQL)” on page 258.
Table 177. Bit C Data to ODBC SQL Data Types

SQL Type Identifier Test SQLSTATE

SQL_CHAR None N/A

SQL_VARCHAR

SQL_LONGVARCHAR

SQL_WCHAR

SQL_WVARCHAR

SQL_WLONGVARCHAR

SQL_DECIMAL None N/A

SQL_NUMERIC

SQL_TINYINT

SQL_SMALLINT

SQL_INTEGER

SQL_BIGINT

SQL_REAL

SQL_FLOAT

SQL_DOUBLE

The driver ignores the length or indicator value when converting data from the bit
C data types and assumes that the size of the data buffer is the size of the bit C
data type. The length or indicator value is passed in the StrLen_or_Ind argument
in SQLPutData and in the buffer specified with the StrLen_or_IndPtr argument in
SQLBindParameter. The data buffer is specified with the DataPtr argument in
SQLPutData and the ParameterValuePtr argument in SQLBindParameter.

C to SQL: Binary

The binary ODBC C data type is:

SQL_C_BINARY

The following table shows the ODBC SQL data types to which binary C data may
be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (C to SQL)” on page 258.

264 IBM solidDB: Programmer Guide


Table 178. Binary C Data to ODBC SQL Data Types

SQL Type Identifier Test SQLSTATE

SQL_CHAR Byte length of data <= N/A


Column byte length
SQL_VARCHAR 22001
Byte length of data >
SQL_LONGVARCHAR Column length

SQL_WCHAR Character length of data <= N/A


Column character length
SQL_WVARCHAR 22001
Character length of data >
SQL_WLONGVARCHAR Column character length

SQL_DECIMAL Byte length of data = SQL N/A


data length
SQL_NUMERIC 22003
Length of data <> SQL data
SQL_TINYINT length

SQL_SMALLINT

SQL_INTEGER

SQL_BIGINT

SQL_REAL

SQL_FLOAT

SQL_DOUBLE

SQL_TYPE_DATE

SQL_TYPE_TIME

SQL_TYPE_TIMESTAMP

SQL_BINARY Length of data <= Column N/A


length
SQL_VARBINARY 22001
Length of data > Column
SQL_LONGVARBINARY length

C to SQL: Date

The date ODBC C data type is:


SQL_C_DATE

The following table shows the ODBC SQL data types to which date C data may be
converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (C to SQL)” on page 258.

Appendix E. Data types 265


Table 179. Date C Data to ODBC SQL Data Types

SQL Type Identifier Test SQLSTATE

SQL_CHAR Column byte length >= 10 N/A

SQL_VARCHAR Column byte length < 10 22001

SQL_LONGVARCHAR Data value is not a valid 22008


date

SQL_CHAR Column character length >= N/A


10
SQL_VARCHAR 22001
Column character length <
SQL_LONGVARCHAR 10 22008

Data value is not a valid


date

SQL_TYPE_DATE Data value is a valid date N/A

Data value is not a valid 22007


date

SQL_TYPE_TIMESTAMP Data value is a valid date [a] N/A

Data value is not a valid 22007


date
Note: [a] The time portion of the timestamp is set to zero.

For information about what values are valid in an SQL_C_TYPE_DATE structure,


see “C data types” on page 230.

When date C data is converted to character SQL data, the resulting character data
is in the "yyyy-mm-dd "format.

The driver ignores the length or indicator value when converting data from the
date C data types and assumes that the size of the data buffer is the size of the
date C data type. The length or indicator value is passed in the StrLen_or_Ind
argument in SQLPutData and in the buffer specified with the StrLen_or_IndPtr
argument in SQLBindParameter. The data buffer is specified with the DataPtr
argument in SQLPutData and the ParameterValuePtr argument in
SQLBindParameter.

C to SQL: Time

The time ODBC C data type is:

SQL_C_TIME

T he following table shows the ODBC SQL data types to which time C data may
be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (C to SQL)” on page 258.

266 IBM solidDB: Programmer Guide


Table 180. Time C Data to ODBC SQL Data Types

SQL Type Identifier Test SQLSTATE

SQL_CHAR Column byte length >= 8 N/A

SQL_VARCHAR Column byte length < 8 22001


SQL_LONGVARCHAR
Data value is not a valid 22008
time

SQL_WCHAR Column character length >= N/A


8
SQL_WVARCHAR 22001
Column character length < 8
SQL_WLONGVARCHAR 22008
Data value is not a valid
time

SQL_TYPE_TIME Data value is a valid time N/A

Data value is not a valid 22007


time

SQL_TYPE_TIMESTAMP Data value is a valid time [a] N/A

Data value is not a valid 22007


time
Note: [a] The date portion of the timestamp is set to the current date and the fractional
seconds portion of the timestamp is set to zero.

For information about what values are valid in an SQL_C_TYPE_TIME structure,


see “C data types” on page 230.

When time C data is converted to character SQL data, the resulting character data
is in the "hh:mm:ss" format.

The driver ignores the length or indicator value when converting data from the
time C data types and assumes that the size of the data buffer is the size of the
time C data type. The length or indicator value is passed in the StrLen_or_Ind
argument in SQLPutData and in the buffer specified with the StrLen_or_IndPtr
argument in SQLBindParameter. The data buffer is specified with the DataPtr
argument in SQLPutData and the ParameterValuePtr argument in
SQLBindParameter.

C to SQL: Timestamp

The timestamp ODBC C data type is:

SQL_C_TIMESTAMP

The following table shows the ODBC SQL data types to which timestamp C data
may be converted. For an explanation of the columns and terms in the table, see
“Conversion Table Description (C to SQL)” on page 258.

Appendix E. Data types 267


Table 181. Timestamp C Data to ODBC SQL Data Ttypes

SQL Type Identifier Test SQLSTATE

SQL_CHAR Column byte length >= N/A


Character byte length
SQL_VARCHAR 22001
19 <= Column byte length <
SQL_LONGVARCHAR Character byte length 22001

Column byte length < 19 22008

Data value is not a valid


date

SQL_WCHAR Column character length >= N/A


Character length of data
SQL_WVARCHAR 22001
19 <= Column character
SQL_WLONGVARCHAR length < Character length of 22001
data
22008
Column character length <
19

Data value is not a valid


timestamp

SQL_TYPE_DATE Time fields are zero N/A

Time fields are non-zero 22008

Data value does not contain 22007


a valid date

SQL_TYPE_TIME Fractional seconds fields are N/A


zero [a]
22008
Fractional seconds fields are
non-zero [a] 22007

Data value does not contain


a valid time

SQL_TYPE_TIMESTAMP Fractional seconds fields are N/A


not truncated
22008
Fractional seconds fields are
truncated 22007

Data value is not a valid


timestamp
Note: [a] The date fields of the timestamp structure are ignored.

For information about what values are valid in an SQL_C_TIMESTAMP structure,


see “C data types” on page 230.

When timestamp C data is converted to character SQL data, the resulting character
data is in the "yyyy-mm-dd hh:mm:ss [ .f. ..]" format.

268 IBM solidDB: Programmer Guide


The driver ignores the length or indicator value when converting data from the
timestamp C data types and assumes that the size of the data buffer is the size of
the timestamp C data type. The length or indicator value is passed in the
StrLen_or_Ind argument in SQLPutData and in the buffer specified with the
StrLen_or_IndPtr argument in SQLBindParameter. The data buffer is specified with
the DataPtr argument in SQLPutData and the ParameterValuePtr argument in
SQLBindParameter.

C to SQL data conversion examples


The following examples illustrate how the driver converts C data to SQL data.
Table 182. C Data to SQL Data

Column
C Data Type C Data Value SQL Data Type Length SQL Data Value SQLSTATE

SQL_C_CHAR abcdef\0 [a] SQL_CHAR 6 abcdef N/A

SQL_C_CHAR abcdef\0 [a] SQL_CHAR 5 abcde 22001

SQL_C_CHAR 1234.56\0 [a] SQL_DECIMAL 8 [b] 1234.56 N/A

SQL_C_CHAR 1234.56\0 [a] SQL_DECIMAL 7 [b] 1234.5 22001

SQL_C_CHAR 1234.56\0 [a] SQL_DECIMAL 4 ---- 22003

SQL_C_FLOAT 1234.56 SQL_FLOAT not 1234.56 N/A


applicable

SQL_C_FLOAT 1234.56 SQL_INTEGER not 1234 22001


applicable

SQL_C_FLOAT 1234.56 SQL_TINYINT not ---- 22003


applicable

SQL_C_TYPE_DATE 1992,12,31 [c] SQL_CHAR 10 1992-12-31 N/A

SQL_C_TYPE_DATE 1992,12,31 [c] SQL_CHAR 9 ---- 22003

SQL_C_TYPE_DATE 1992,12,31 [c] SQL_TIMESTAMP not 1992-12-31 N/A


applicable 00:00:00.0

SQL_C_TYPE TIMESTAMP 1992,12,31, SQL_CHAR 22 1992-12-31 N/A


23,45,55, 23:45:55.12
120000000 [d]

SQL_C_TYPE TIMESTAMP 1992,12,31, SQL_CHAR 21 1992-12-31 22001


23,45,55, 23:45:55.1
120000000 [d]

SQL_C_TYPE TIMESTAMP 1992,12,31, SQL_CHAR 18 ---- 22003


23,45,55,
120000000 [d]

Appendix E. Data types 269


Table 182. C Data to SQL Data (continued)

Column
C Data Type C Data Value SQL Data Type Length SQL Data Value SQLSTATE
Note:

[a] "\0" represents a null-termination byte. The null-termination byte is required only if the length of the data is
SQL_NTS.

[b] In addition to bytes for numbers, one byte is required for a sign and another byte is required for the decimal
point.

[c] The numbers in this list are the numbers stored in the fields of the SQL_DATE_STRUCT structure.

[d] The numbers in this list are the numbers stored in the fields of the SQL_TIMESTAMP_STRUCT structure.

270 IBM solidDB: Programmer Guide


Appendix F. Scalar functions
This section provides additional information about ODBC scalar functions.

ODBC specifies five types of scalar functions:


v String functions
v Numeric functions
v Time and date functions
v System functions
v Data type conversion functions

A scalar function is a function that returns one value for each row in the query.
Functions like SQRT() and ABS() are scalar functions. Functions like SUM() and
AVG() are not scalar functions because they return a single value even if they
process more than one row.

This section includes tables for each scalar function category. Within each table,
functions have been added in ODBC 3.0 to align with SQL-92. Each table also
provides the version number when the function was introduced.

ODBC and SQL-92 scalar functions


This topic provides information about ODBC and SQL-92 scalar functions.

Because functions are often data-source-specific, ODBC does not require a data
type for return values from scalar functions. To force data type conversion,
applications should use the CONVERT scalar function.

Note:

ODBC and SQL-92 classify functions in different ways. ODBC classifies scalar
functions by argument type, whereas SQL-92 classifies them by return value. For
example, in ODBC, the EXTRACT function is classified as a timedate function
because the extract-field argument is a timedate keyword and the extract_source
argument is a timedate or interval expression. In SQL-92, however, the EXTRACT
function is classified as a numeric scalar function because the return value is
numeric.

Applications need to call SQLGetInfo to determine which scalar functions a driver


supports. ODBC and SQL-92 information types are available for scalar function
classifications. Because ODBC and SQL-92 use different classifications, the
information types for the same function may differ between ODBC and SQL-92.
For example, to determine support for the EXTRACT function requires
SQL_TIMEDATE_FUNCTIONS information type in ODBC and
SQL_SQL92_NUMERIC_VALUE_FUNCTIONS information type in SQL-92.

String functions
This topic lists string manipulation functions.

271
Applications can call SQLGetInfo with the SQL_STRING_FUNCTIONS information
type to determine which string functions are supported by a driver.

String Function Arguments


Table 183. String Function Arguments

Arguments denoted as... Definition

string_exp These arguments can be the name of a column, a string literal,


or the result of another scalar function, where the underlying
data type can be represented as SQL_CHAR, SQL_VARCHAR,
or SQL_LONGVARCHAR.

start, length or count These arguments can be a numeric literal or the result of
another scalar function, where the underlying data type can
be represented as SQL_TINYINT, SQL_SMALLINT, or
SQL_INTEGER

character_exp These arguments are a variable-length character string

The following string functions are 1-based, that is, the first character in the string is
character 1, not character 0.

Note: BIT_LENGTH, CHAR_LENGTH, CHARACTER_LENGTH,


OCTET_LENGTH, and POSITION string scalar functions were added in ODBC 3.0
to align with SQL-92.

List of String Functions


Table 184. List of String Functions

Function Description

ASCII(string_exp) Returns the ASCII code value of the leftmost


character of string_exp as an integer.
(ODBC 1.0)

BIT_LENGTH(string_exp) Returns the length in bits of string expression.

(ODBC 3.0)

CHAR(code) Returns the character that has the ASCII code value
specified by code. The value of code should be
(ODBC 1.0) between 0 and 255; otherwise, the return value is
data source-dependent.

CHAR_LENGTH(string_exp) Returns the length in characters of the string


expression, if the string expression is of a character
(ODBC 3.0) data type; otherwise, returns the length in bytes of
the string expression (the smallest integer not less
than the number of bits divided by 8). (This
function is the same as CHARACTER_LENGTH
function.)

272 IBM solidDB: Programmer Guide


Table 184. List of String Functions (continued)

Function Description

CHARACTER_LENGTH(string_exp) Returns the length in characters of the string


expression, if the string expression is of a character
(ODBC 3.0) data type; otherwise, returns the length in bytes of
the string expression (the smallest integer not less
than the number of bits divided by 8). (This
function is the same as the CHAR_LENGTH
function.)

CONCAT(string_exp1, string_exp2) Returns a character string that is the result of


concatenating string_exp2 to string_exp1. The
(ODBC 1.0) resulting string is DBMS-dependent.

DIFFERENCE(string_exp1, The function returns the difference between the


string_exp2) soundex (see soundex function below) values of
two character expressions, as an integer. The
(ODBC 2.0) integer returned is the number of characters in the
soundex values that are the same. The return value
ranges from 0 through 4: 0 indicates little or no
similarity, and 4 indicates strong similarity or
identical values.

INSERT(string_exp1, start, length, Returns a character string where length characters


string_exp2) have been deleted from string_exp1 beginning at
start and where string_exp2 has been inserted into
(ODBC 1.0) string_exp, beginning at start.

LCASE(string_exp) Returns a string equal to that string_exp, with all


uppercase characters converted to lowercase.
(ODBC 1.0)

LEFT(string_exp, count) Returns the leftmost count of characters of


string_exp.
(ODBC 1.0)

LENGTH(string_exp) Returns the number of characters in string_exp,


excluding trailing blanks.
(ODBC 1.0)

Appendix F. Scalar functions 273


Table 184. List of String Functions (continued)

Function Description

LOCATE(string_exp1, string_exp2[, Returns the starting position of the first occurrence


start]) of string_exp1 within string_exp2. The search for the
first occurrence of string_exp1 begins with the first
character position in string_exp2 unless the optional
argument, start, is specified. If start is specified, the
search begins with the character position indicated
by the value of start. The first character position in
string_exp2 is indicated by the value 1. If
string_exp1 is not found within string_exp2, the
value 0 is returned.

If an application can call the LOCATE scalar


function with the string_exp1, string_exp2, and start
arguments, the driver returns
SQL_FN_STR_LOCATE when SQLGetInfo is called
with an option of SQL_STRING_FUNCTIONS. If
the application can call the LOCATE scalar function
with only the string_exp1 and string_exp2
arguments, the driver returns
SQL_FN_STR_LOCATE_2 when SQLGetInfo is
called with an option of
SQL_STRING_FUNCTIONS. Drivers that support
calling the LOCATE function with either two or
three arguments return both
SQL_FN_STR_LOCATE and
SQL_FN_STR_LOCATE_2.

LTRIM(string_exp) Returns the characters of string_exp, with leading


blanks removed.
(ODBC 1.0)

OCTET_LENGTH(string_exp) Returns the length in bytes of the string expression.


The result is the smallest integer not less than the
(ODBC 3.0) number of bits divided by 8.

POSITION(character_exp IN Returns the position of the first character


character_exp) expression in the second character expression. The
result is an exact numeric with an
(ODBC 3.0) implementation-defined precision and a scale of 0.

REPEAT(string_exp, count) Returns a character string composed of string_exp


repeated count times.
(ODBC 1.0)

REPLACE(string_exp1, string_exp2, Search string_exp1 for occurrences of string_exp2,


string_exp3) and replace with string_exp3.

(ODBC 1.0)

RIGHT(string_exp, count) Returns the rightmost count of characters of


string_exp.
(ODBC 1.0)

274 IBM solidDB: Programmer Guide


Table 184. List of String Functions (continued)

Function Description

RTRIM(string_exp) Returns the characters of string_exp with trailing


blanks removed.
(ODBC 1.0)

SOUNDEX(string_exp1) Returns a character string containing the phonetic


representation of the argument. This function lets
(ODBC 2.0) you compare words that are spelled differently, but
sound alike in English. If you supply a word to
Soundex, it returns a 4-character phonetic code
used by the [Link] Bureau since 1930s.

SPACE(count) Returns a character string consisting of count


spaces.
(ODBC 2.0)

SUBSTRING(string_exp, start, length) Returns a character string that is derived from


string_exp, beginning at the character position
(ODBC 1.0) specified by start for length characters.

TRIM(string_exp) Returns the characters of string_exp with leading


blanks and trailing blanks removed.

UCASE(string_exp) Returns a string equal to that in string_exp, with all


lowercase characters converted to uppercase.
(ODBC 1.0)

Numeric functions
This topic describes numeric functions that are included in the ODBC scalar
function set.

Applications can call SQLGetInfo with the SQL_NUMERIC_FUNCTIONS


information type to determine which numberic functions are supported by a
driver.

Except for ABS, ROUND, TRUNCATE, SIGN, FLOOR, and CEILING (which return
values of the same data type as the input parameters), all numeric functions return
values of data type SQL_FLOAT.

Numeric Function Arguments


Table 185. Numeric Function Arguments

Arguments denoted as... Definition

numeric_exp These arguments can be the name of a column, the result of


another scalar function, or a numeric literal, where the
underlying data type could be represented as
SQL_NUMERIC, SQL_DECIMAL, SQL_TINYINT,
SQL_SMALLINT, SQL_INTEGER, SQL_BIGINT, SQL_FLOAT,
SQL_REAL, or SQL_DOUBLE

Appendix F. Scalar functions 275


Table 185. Numeric Function Arguments (continued)

Arguments denoted as... Definition

float_exp These arguments can be the name of a column, the result of


another scalar function, or a numeric literal, where the
underlying data type can be represented as SQL_FLOAT.

integer_exp These arguments can be the name of a column, the result of


another scalar function, or a numeric literal, where the
underlying data type can be represented as SQL_TINYINT,
SQL_SMALLINT, SQL_INTEGER, or SQL_BIGINT

List of Numeric Functions


Table 186. List of Numeric Functions

Function Description

ABS(numeric_exp) Returns the absolute value of numeric_exp.

(ODBC 1.0)

ACOS(float_exp) Returns the arccosine of float_exp as an angle, expressed in


radians.
(ODBC 1.0)

ASIN(float_exp) Returns the arcsine of float_exp as an angle, expressed in


radians.
(ODBC 1.0)

ATAN(float_exp) Returns the arctangent of float_exp as an angle, expressed in


radians.
(ODBC 1.0)

ATAN2(float_exp1, Returns the arctangent of the x and y coordinates, specified by


float_exp2) float_exp1 and float_exp2, respectively, as an angle, expressed in
radians.
(ODBC 2.0)

CEILING(numeric_exp) Returns the smallest integer greater than or equal to


numeric_exp. The return value is of the same data type as the
(ODBC 1.0) input parameter.

COS(float_exp) Returns the cosine of float_exp, where float_exp is an angle


expressed in radians.
(ODBC 1.0)

COT(float_exp) Returns the cotangent of float_exp, where float_exp is an angle


expressed in radians.
(ODBC 1.0)

DEGREES(numeric_exp) Returns the number of degrees converted from numeric_exp


radians.
(ODBC 2.0)

276 IBM solidDB: Programmer Guide


Table 186. List of Numeric Functions (continued)

Function Description

EXP(float_exp) Returns the exponential value of float_exp.

(ODBC 1.0)

FLOOR(numeric_exp) Returns largest integer less than or equal to numeric_exp. The


return value is of the same data type as the input parameter.
(ODBC 1.0)

LOG(float_exp) Returns the natural logarithm of float_exp.

(ODBC 1.0)

LOG10(float_exp) Returns the base 10 logarithm of float_exp.

(ODBC 2.0)

MOD(integer_exp1, Returns the remainder (modulus) of integer_exp1 divided by


integer_exp2) integer_exp2.

(ODBC 1.0)

PI( ) Returns the constant value of pi as a floating point value.

(ODBC 1.0)

POWER(numeric_exp, Returns the value of numeric_exp to the power of integer_exp.


integer_exp)

RADIANS(numeric_exp) Returns the number of radians converted from numeric_exp


degrees.
(ODBC 2.0)

ROUND(numeric_exp, Returns numeric_exp rounded to integer_exp places right of the


integer_exp) decimal point. If integer_exp is negative, numeric_exp is
rounded to |integer_exp| places to the left of the decimal
(ODBC 2.0) point.

SIGN(numeric_exp) Returns an indicator or the sign of numeric_exp. If numeric_exp


is less than zero, -1 is returned. If numeric_exp equals zero, 0 is
(ODBC 1.0) returned. If numeric_exp is greater than zero, 1 is returned.

SIN(float_exp) Returns the sine of float_exp, where float_exp is an angle


expressed in radians.
(ODBC 1.0)

SQRT(float_exp) Returns the square root of float_exp.

(ODBC 1.0)

TAN(float_exp) Returns the tangent of float_exp, where float_exp is an angle


expressed in radians.
(ODBC 1.0)

Appendix F. Scalar functions 277


Table 186. List of Numeric Functions (continued)

Function Description

TRUNCATE(numeric_exp, Returns numeric_exp truncated to integer_exp places right of


integer_exp) the decimal point. If integer_exp is negative, numeric_exp is
truncated to |integer_exp| places to the left of the decimal
(ODBC 2.0) point.

Time and date functions


This section lists time and date functions that are included in the ODBC scalar
function set.

Applications can call SQLGetInfo with the SQL_TIMEDATE_FUNCTIONS


information type to determine which time and date functions are supported by a
driver.

Time and Data Arguments


Table 187. Time and Data Arguments

Arguments denoted as... Definition

timestamp_exp These arguments can be the name of a column, the result of


another scalar function, or an ODBC_time_escape,
ODBC_date_escape, or ODBC_timestamp_escape, where the
underlying data type could be represented as SQL_CHAR,
SQL_VARCHAR, SQL_TYPE_TIME, SQL_TYPE_DATE, or
SQL_TYPE_TIMESTAMP.

date_exp These arguments can be the name of a column, the result of


another scalar function, or an ODBC_date_escape or
ODBC_timestamp_escape, where the underlying data type could
be represented as SQL_CHAR, SQL_VARCHAR,
SQL_TYPE_DATE, or SQL_TYPE_TIMESTAMP.

time_exp These arguments can be the name of a column, the result of


another scalar function, or an ODBC_time_escape or
ODBC_timestamp_escape, where the underlying data type could
be represented as SQL_CHAR, SQL_VARCHAR,
SQL_TYPE_TIME, or SQL_TYPE_TIMESTAMP

List of Time and Date Functions


Table 188. List of Time and Date Functions

Function Description

CURRENTTIME Returns the current local time as a time value. The


[(time_precision)] time_precision argument (0-6) determines the milliseconds
precision of the returned value.
(ODBC 3.0)
Value 0 means no timestamp or time fractions are shown. If
the value is not specified, the value 0 is used.

278 IBM solidDB: Programmer Guide


Table 188. List of Time and Date Functions (continued)

Function Description

CURRENT_TIMESTAMP Returns the current local date and local time as a


[(timestamp_precision)] timestamp value. The timestamp_precision argument (0-6)
determines the milliseconds precision of the returned
(ODBC 3.0) timestamp.

Value 0 means no timestamp or time fractions are shown. If


the value is not specified, the value 0 is used.

CURDATE( ) Returns the current date.

(ODBC 1.0)

CURTIME[(time_precision)] Returns the current local time. The time_precision argument


(0-6) determines the milliseconds precision of the returned
(ODBC 1.0) value.

Value 0 means no timestamp or time fractions are shown. If


the value is not specified, the value 0 is used.

DAYNAME(date_exp) Returns a character string containing the data


source-specific name of the day (for example, Sunday,
(ODBC 2.0) through Saturday or Sun. through Sat. for a data source
that uses English, or Sonntag through Samstag for a data
source that uses German) for the day portion of date_exp.

DAYOFMONTH(date_exp) Returns the day of the month in date_exp as an integer


value in the range of 1-31.
(ODBC 1.0)

DAYOFWEEK(date_exp) Returns the day of the week based on the week field in
date_exp as an integer value in the range of 1-7, where 1
(ODBC 1.0) represents Sunday.

DAYOFYEAR(date_exp) Returns the day of the year based on the year field in
date_exp as an integer value in the range of 1-366.
(ODBC 1.0)

EXTRACT(extract_field Returns the extract_field portion of the extract_source. The


FROM extract_source) extract_source argument is a datetime or interval
expression. The extract_field argument can be one of the
(ODBC 3.0) following keywords"
YEAR
MONTH
DAY
HOUR
MINUTE
SECOND

The precision of the returned value is implementation-


defined. The scale is 0 unless SECOND is specified, in
which case the scale is not less than the fractional seconds
precision of the extract_source field.

Appendix F. Scalar functions 279


Table 188. List of Time and Date Functions (continued)

Function Description

HOUR(time_exp) Returns the hour based on the hour field in time_exp as an


integer value in the range of 0-23.
(ODBC 1.0)

MINUTE(time_exp) Returns the minute based on the minute field in time_exp as


an integer value in the range of 0-59.
(ODBC 1.0)

MONTH(date_exp) Returns the month based on the month field in date_exp as


an integer value in the range of 1-12.
(ODBC 1.0)

MONTHNAME(date_exp) Returns a character string containing the data


source-specific name of the month (for example, January
(ODBC 2.0) through December or Jan. through Dec. for a data source
that uses English, or Januar through Dezember for a data
source that uses German) for the month portion of date_exp.

NOW [(timestamp_precision)] Returns current date and time as a timestamp value. The
timestamp_precision argument (0-6) determines the
(ODBC 1.0) milliseconds precision of the returned timestamp.

Value 0 means no timestamp or time fractions are shown. If


the value is not specified, the value 0 is used.

QUARTER(date_exp) Returns the quarter in date_exp as an integer value in the


range of 1- 4, where 1 represents January 1 through March
(ODBC 1.0) 31.

SECOND(time_exp) Returns the second in time_exp as an integer value in the


range of 0-59.
(ODBC 1.0)

280 IBM solidDB: Programmer Guide


Table 188. List of Time and Date Functions (continued)

Function Description

TIMESTAMPADD(interval, Returns the timestamp calculated by adding integer_exp


integer_exp, timestamp_exp) intervals of type interval to timestamp_exp. Valid values of
interval are the following keywords:
(ODBC 2.0)
SQL_TSI_FRAC_SECOND
SQL_TSI_SECOND
SQL_TSI_MINUTE
SQL_TSI_HOUR
SQL_TSI_DAY
SQL_TSI_WEEK
SQL_TSI_MONTH
SQL_TSI_QUARTER
SQL_TSI_YEAR

where fractional seconds are expressed in billionths of a


second (nanoseconds). For example, the following SQL
statement returns the name of each employee and his or
her one-year anniversary date:
SELECT NAME, {fn
TIMESTAMPADD(SQL_TSI_YEAR, 1,
HIRE_DATE)} FROM
EMPLOYEES

If timestamp_exp is a time value and interval specifies day,


weeks, months, quarters, or years, the date portion of
timestamp_exp is set to the current date before calculating
the resulting timestamp.

If timestamp_exp is a date value and interval specifies


fractional seconds, seconds, minutes, or hours, the time
portion of timestamp_exp is set to 0 before calculating the
resulting timestamp.

An application determines which intervals a data source


supports by calling SQLGetInfo with the
SQL_TIMEDATE_ADD_INTERVALS option.

Appendix F. Scalar functions 281


Table 188. List of Time and Date Functions (continued)

Function Description

TIMESTAMPDIFF(interval, Returns the number of unit intervals (as integers) of type


timestamp_exp1, interval between timestamp_exp1 and timestamp_exp2.
timestamp_exp2)
If an application relies on the old TIMESTAMPDIFF
(ODBC 2.0) semantics, the old behavior can be emulated by the
following configuration setting in the SQL section of the
[Link] file.
[SQL]
EmulateOldTIMESTAMPDIFF=YES

Note that the old semantics returns the integer number of


intervals of type interval by which timestamp_exp2 is greater
than timestamp_exp1.

Valid values of interval are the following keywords:


SQL_TSI_FRAC_SECOND
SQL_TSI_SECOND
SQL_TSI_MINUTE
SQL_TSI_HOUR
SQL_TSI_DAY
SQL_TSI_WEEK
SQL_TSI_MONTH
SQL_TSI_QUARTER
SQL_TSI_YEAR

where fractional seconds are expressed in billionths of a


second (nanoseconds). For example, the following SQL
statement returns the name of each employee and the
number of years they have been employed:
SELECT NAME, {fn
TIMESTAMPDIFF(SQL_TSI_YEAR,
{fn CURDATE()}, HIRE_DATE)}
FROM EMPLOYEES

If either timestamp expression is a time value and interval


specifies days, weeks, months, quarters, or years, the date
portion of that timestamp is set to the current date before
calculating the difference between the timestamps.

If either timestamp expression is a date value and interval


specifies fractional seconds, seconds, minutes, or hours, the
time portion of that timestamp is set to 0 before calculating
the difference between the timestamps.

An application determines which intervals a data source


supports by calling SQLGetInfo with the
SQL_TIMEDATE_DIFF_INTERVALS option.

WEEK(date_exp) Returns the week of the year based on the week field in
date_exp as an integer value in the range of 1-53.
(ODBC 1.0)

YEAR(date_exp) Returns the year based on the year field in date_exp as an


integer value. The range is data source-dependent.
(ODBC 1.0)

282 IBM solidDB: Programmer Guide


System functions
This section lists system functions that are included in the ODBC scalar function
set.

Applications can call SQLGetInfo with the SQL_SYSTEM_FUNCTIONS


information type to determine which string functions are supported by a driver.

System Functions Arguments


Table 189. System Function Arguments

Arguments denoted as... Definition

exp These arguments can be the name of a column, the result of


another scalar function, or a literal, where the underlying data
type could be represented as SQL_NUMERIC,
SQL_DECIMAL, SQL_TINYINT, SQL_SMALLINT,
SQL_INTEGER, SQL_BIGINT, SQL_FLOAT, SQL_REAL,
SQL_DOUBLE, SQL_TYPE_DATE, SQL_TYPE_TIME, or
SQL_TYPE_TIMESTAMP.

value These arguments can be a literal constant, where the


underlying data type can be represented as SQL_NUMERIC,
SQL_DECIMAL, SQL_TINYINT, SQL_SMALLINT,
SQL_INTEGER, SQL_BIGINT, SQL_FLOAT, SQL_REAL,
SQL_DOUBLE, SQL_TYPE_DATE, SQL_TYPE_TIME, or
SQL_TYPE_TIMESTAMP.

integer_exp These arguments can be the name of a column, the result of


another scalar function, or a numeric literal, where the
underlying data type can be represented as SQL_TINYINT,
SQL_SMALLINT, SQL_INTEGER, or SQL_BIGINT

Values returned are represented as ODBC data types

List of System Functions


Table 190. List of System Functions

Function Description

DATABASE( ) Returns the name of the database corresponding to the


connection handle. (The name of the database is also available
(ODBC 1.0) by calling SQLGetConnectOption with the
SQL_CURRENT_QUALIFIER connection option.)

IFNULL(exp, value) If exp is null, value is returned. If exp is not null, exp is
returned. The possible data type(s) of value must be
(ODBC 1.0) compatible with the data type of exp

USER( ) Returns the user's name in the DBMS. (The user's


authorization name is also available via SQLGetInfo by
(ODBC 1.0) specifying the information type: SQL_USER_NAME.) This can
be different from the login time.

Appendix F. Scalar functions 283


Explicit data type conversion
Explicit data type conversion is specified in terms of SQL data type definitions.

The ODBC syntax for the explicit data type conversion function does not restrict
conversions. The validity of specific conversions of one data type to another data
type is dependent on each driver-specific implementation. The driver, as it
translates the ODBC syntax into the native syntax, reject those conversions that,
although legal in the ODBC syntax, are not supported by the data source.
Applications can call the ODBC function SQLGetInfo to inquire about conversions
supported by the data source.

The format of the CONVERT function is:

CONVERT(value_exp, data_type)

The function returns the value specified by value_exp converted to the specified
data_type, where data_type is one of the following keywords:
v SQL_BIGINT
v SQL_SMALLINT
v SQL_BINARY
v SQL_DATE
v SQL_CHAR
v SQL_TIME
v SQL_DECIMAL
v SQL_TIMESTAMP
v SQL_DOUBLE
v SQL_TINYINT
v SQL_FLOAT
v SQL_VARBINARY
v SQL_INTEGER
v SQL_VARCHAR
v SQL_LONGVARBINARY
v SQL_WCHAR
v SQL_LONGVARCHAR
v SQL_WLONGVARCHAR
v SQL_NUMERIC
v SQL_WVARCHAR
v SQL_REAL

The ODBC syntax for the explicit data type conversion function does not support
specification of conversion format. If specification of explicit formats is supported
by the underlying data source, a driver must specify a default value or implement
format specification.

The argument value_exp can be a column name, the result of another scalar
function, or a numeric or string literal. The following example converts the output
of the CURDATE scalar function to a character string:
{ fn CONVERT( { fn CURDATE() }, SQL_CHAR) }

284 IBM solidDB: Programmer Guide


ODBC does not require a data type for return values from scalar functions
(because the functions are often data source-specific); applications should use the
CONVERT scalar function whenever possible to force data type conversion.

The following two examples illustrate the use of the CONVERT function. These
examples assume the existence of a table called EMPLOYEES, with an EMPNO
column of type SQL_SMALLINT and an EMPNAME column of type SQL_CHAR.

If an application specifies the following:


SELECT EMPNO FROM EMPLOYEES WHERE {fn CONVERT(EMPNO,SQL_CHAR)}LIKE ’1%’

solidDB ODBC driver translates the request to:


SELECT EMPNO FROM EMPLOYEES WHERE CONVERT_CHAR(EMPNO) LIKE ’1%’

SQL-92 CAST function


The ODBC CONVERT function has an equivalent function in SQL-92: the CAST
function.

The syntax for these equivalent functions is as follows::


{ fn CONVERT (value_exp, data_type)} /* ODBC */
CAST (value_exp AS data_type) /* SQL 92 */

Support for the CAST function is at the FIPS Transitional level. For details on data
type conversion in the CAST function, see the SQL-92 specification.

To determine application support for the CAST function, call SQLGetInfo with the
SQL_SQL_CONFORMANCE information type. The CAST function is supported if
the return value for the information type is:
v SQL_SC_FIPS127_2_TRANSITIONAL
v SQL_SC_SQL92_INTERMEDIATE
v SQL_SC_SQL92_FULL

If the return value is SQL_SC_ENTRY or 0, call SQLGetInfo with the


SQL_SQL92_VALUE_EXPRESSIONS information type. If the SQL_SVE_CAST bit is
set, the CAST function is supported.

Appendix F. Scalar functions 285


286 IBM solidDB: Programmer Guide
Appendix G. Timeout controls
In solidDB, some actions can get timed out. A timeout can be activated by the
main server, the client drivers, the Primary or Secondary server, or the Master or
Replica server.

Timeouts have factory default values and they can usually be set with different .ini
parameters. Some startup defaults can be dynamically changed with different
controls, by using SQL, or by using the driver interfaces and connection string
parameters.

Client timeouts
Timeouts related to the database client are introduced in this topic.

Login timeout

This timeout refers to the number of seconds the driver waits for the login
(SQLConnect) to succeed. The default value is driver-dependent. If the value (or
ValuePtr in ODBC) is 0, the timeout is disabled and a connection attempt will wait
indefinitely. If the specified timeout exceeds the maximum login timeout in the
data source, the driver substitutes that value and returns SQLSTATE 01S02 (Option
value changed).

This timeout applies for the TCP protocol only.


Table 191. Login timeouts

Overridden Connection
INI parameter with SQL Driver string

Client-side: ODBC: -c
[Com] milliseconds
ConnectTimeout=milliseconds SQL_ATTR_LOGIN_TIMEOUT (in
seconds)
or:
SQL_ATTR_LOGIN_TIMEOUT_MS (in
[Link] parameter with option milliseconds, non-standard)
-cmilliseconds
JDBC:
For example:
Method (JDBC 2.0)
[Com]
Connect=tcp -c1000 1315 [Link](seconds);

Connection property (non-standard)

"solid_login_timeout_ms" (milliseconds)

Timeout error code and message:

ODBC:

HYT00, Timeout expired

287
Connection timeout

This timeout refers to the number of seconds (or milliseconds) the driver waits for
any request on the connection to complete. This timeout is not associated with the
query execution or login. Upon timeout, the driver disconnects from the solidDB
server.

If the client can detect reliably that the server is not reachable, it does not wait for
the timeout to expire. This can happen, for example, if the server is expected to
run on the same host, and the client detects that the server is not running.

The driver returns SQLSTATE HYT00 (Timeout expired) if it is possible to time out
in a situation not associated with query execution or login. If the value (or
ValuePtr in ODBC) is 0 (the default value), there is no timeout.

This timeout applies to all ODBC functions (ODBC 3.5 specifications) except the
following:
SQLDrivers
SQLDataSources
SQLGetEnvAttr
SQLSetEnvAttr

Table 192. Connection timeout

Overridden Connection
INI parameter with SQL Driver string
Client-side: ODBC:
-r milliseconds
[Com]
ClientReadTimeout=milliseconds SQL_ATTR_CONNECTION_TIMEOUT (in
seconds)
or:
SQL_ATTR_CONNECTION_TIMEOUT_MS
[Link] parameter with option (in milliseconds, non-standard)
-rmilliseconds
JDBC:
For example:
Non-standard connection property:
[Com]
Connect=tcp -r1000 1315 "solid_connection_timeout_ms" (milliseconds)

or method:

[Link]()
(milliseconds)

Timeout error code and message:

ODBC:

HYT01, Connection timeout expired

See also:
SOLID Server Error 14518:
Connection to the server is broken, connection lost.

SOLID Communication Error 21328 and SOLID Session Error 20024:


Timeout while resolving host name.

288 IBM solidDB: Programmer Guide


SOLID Communication Error 21329 and SOLID Session Error 20025:
Timeout while connecting to a remote host.

Query timeout

This timeout refers to the number of seconds the driver waits for an SQL statement
to execute. If the value (or ValuePtr in ODBC) is 0 (the default value), there is no
timeout.

If the specified timeout exceeds the maximum timeout in the data source, or if the
specified timeout is smaller than the minimum timeout, SQLSetStmtAttr substitutes
that value and returns SQLSTATE 01S02 (Option value changed).

This timeout applies to the ODBC functions (ODBC 3.5 specifications) as follows:

SQLBrowseConnect

SQLBulkOperations

SQLColumnPrivileges

SQLColumns

SQLConnect

SQLDriverConnect

SQLExecDirect

SQLExecute

SQLExtendedFetch

SQLForeignKeys

SQLGetTypeInfo

SQLParamData

SQLPrepare

SQLPrimaryKeys

SQLProcedureColumns

SQLProcedures

SQLSetPos

SQLSpecialColumns

SQLStatistics

SQLTablePrivileges

Appendix G. Timeout controls 289


SQLTables

Note: The application need not call SQLCloseCursor to reuse the statement if a
SELECT statement timed out. The query timeout set in this statement attribute is
valid in both synchronous and asynchronous modes.
Table 193. Query Timeout

INI Overridden
parameter with SQL Driver Connection string

ODBC:

SQL_ATTR_QUERY_TIMEOUT (in
seconds)

SQL_ATTR_QUERY_TIMEOUT_MS (in
milliseconds, non-standard)

Timeout error code and message:

ODBC:

HYT00, Timeout expired

Server timeouts
Timeouts related to the database server are introduced in this topic.

SQL Statement Execution Timeout

The server can control the amount of time spent on the execution of one SQL
statement. When the time expires, the server terminates the statements and returns
a corresponding error code. This timeout applies to the following calls (ODBC 3.5
specifications):
v SQLExecute()
v SQLExecDirect()
v SQLPrepare()
v SQLForeignKeys()
v SQLColumns()
v SQLProcedureColumns()
v SQLSpecialColumns()
v SQLStatistics()
v SQLPrimaryKeys()
v SQLProcedures()
v SQLTables()
v SQLTablePrivileges()
v SQLColumnPrivileges()
v SQLGetTypeInfo()

The timeout also applies to the corresponding JDBC calls.

290 IBM solidDB: Programmer Guide


Table 194. SQL statement execution timeouts

INI Connection
parameter Overridden with SQL Driver string

SET STATEMENT ODBC:


MAXTIME minutes
SQL_ATTR_QUERY_TIMEOUT (in
seconds)

SQL_ATTR_QUERY_TIMEOUT_MS
(in milliseconds, non-standard)

JDBC:

[Link]()
Note:
v In versions prior to V6.5 Fix Pack
12, the timeout unit in SMA
connections is milliseconds.
v As of V6.5 Fix Pack 12, the
timeout unit in SMA connections
is seconds.

Timeout error code and message:

HYT00, Timeout expired

See also:
SOLID Server Error 14518:
Connection to the server is broken, connection lost.

SOLID Server Error 14529:


The operation timed out.

Lock wait timeout

The lock wait timeout specifies the time in seconds (or milliseconds) that the engine
waits for a lock to be released. When the timeout interval is reached, solidDB
terminates the timed-out transaction. The default value is 30 seconds.

Lock wait timeout is used in deadlock resolution. In that case, the oldest
transaction participating in a deadlock is aborted.
Table 195. Lock wait timeout

Connection
INI parameter Overridden with SQL Driver string
[General]
LockWaitTimeOut=seconds SET LOCK TIMEOUT
{seconds | milliseconds MS}

Timeout error code and message:


SOLID Database Error 10006:
Concurrency conflict, two transactions updated or deleted the same row.

Appendix G. Timeout controls 291


Optimistic lock timeout

The optimistic lock timeout specifies the time in seconds (or milliseconds) for
optimistic lock timeout. Optimistic lock is an additional lock that can be enacted in
order to ensure that SELECT FOR UPDATE will always lead to successful updates
in the optimistic concurrency mode. The default is zero; no optimistic lock is used,
and a transaction may be aborted after each statement as a result of early
transaction validation. When the timeout is set to a non-zero value, SELECT FOR
UPDATE will wait until the lock is obtained, or it is timed-out and aborted. When
set, the timeout affects also all DELETE and UPDATE statements.
Table 196. Optimistic lock wait timeout

INI
parameter Overridden with SQL Driver Connection string

SET OPTIMISTIC LOCK TIMEOUT


{seconds | milliseconds MS}

Timeout error code and message:


SOLID Database Error 10006:
Concurrency conflict, two transactions updated or deleted the same row.

Table lock wait timeout

Occasionally, the transaction will acquire an exclusive lock to a table. This may be
result of a lock escalation, an attempt to execute the ALTER TABLE statement, or
as a side effect of some advanced replication commands. If there is a table-level
conflict, this setting provides the transaction's wait period until the exclusive or
shared lock is released. The unit is seconds, the default value is 30 seconds, and
the parameter access mode is read/write.

To be more specific, table level locks are used when the PESSIMISTIC keyword is
explicitly provided in the following commands:
IMPORT SUBSCRIPTIONMESSAGE message_name EXECUTE
(only with NO EXECUTE option)
MESSAGE message_name FORWARD
MESSAGE message_name GET REPLY
DROP SUBSCRIPTION.

Table 197. Table lock wait timeout

Overridden with
INI parameter SQL Driver Connection string
[General]
TableLockWaitTimeout=seconds

Timeout error code and message:


SOLID Database Error 10006:
Concurrency conflict, two transactions updated or deleted the same row.

Transaction idle timeout

The transaction idle timeout specifies the time in minutes after an idle transaction is
aborted; a negative or zero value means infinite. The default value is 120 minutes.

292 IBM solidDB: Programmer Guide


Table 198. Transaction Idle Timeout

Overridden with
INI parameter SQL Driver Connection string
[Srv]
AbortTimeOut

Timeout error code and message:


SOLID Database Error 10026:
Transaction is timed out.

Connection idle timeout

The connection idle timeout specifies the continuous idle time in minutes (or
seconds/milliseconds in a statement) after which a connection is dropped (by the
server); negative or zero value indicates an infinite value. The default value is 480
minutes.
Table 199. connection idle timeout

Connection
INI parameter Overridden with SQL Driver string

[Srv]
ConnectTimeOut=minutes SET IDLE TIMEOUT JDBC:
{seconds | milliseconds MS}
Connection property
(non-standard):

"solid_idle_timeout_min"

Timeout error code and message:


SOLID Communication Error 21308:
Connection is broken (protocol read/write
operation failed with code internal code).

See also the [Link] file.

If the SET IDLE TIMEOUT has been set and the transaction is idle for the given
period, the error below is given:
SOLID Database Error 10026:
Transaction is timed out

HotStandby timeouts
Timeouts related to the HotStandby server are introduced in this topic.

Connect timeout

By specifying a connect timeout value with the [Link]


parameter, you can set the maximum time in milliseconds that a HotStandby
connect operation waits for a connection to a remote machine. The
[Link] parameter is only used with the following subset of
ADMIN COMMANDs:

Appendix G. Timeout controls 293


hotstandby connect
hotstandby switch primary
hotstandby switch secondary
Table 200. Connect timeout

Overridden with
INI parameter SQL Driver Connection string
[HotStandby]
ConnectTimeout=milliseconds

Ping timeout

The [Link] parameter specifies in milliseconds how long a server


waits before concluding that the other server is down or inaccessible.
Table 201. Ping timeout

Overridden with
INI parameter SQL Driver Connection string
[HotStandby]
PingTimeout=milliseconds

Transparent connection timeout

The [Link] parameter specifies how long (in


milliseconds) the driver should wait until it tries to reconnect to the primary in
case of TF switchover or failover.

The [Link] parameter specifies how long (in


milliseconds) the driver should wait for the server to switch state.
Table 202. Transparent connection timeout
Overridden Connection
INI parameter with SQL Driver string
[TransparentFailover] ODBC:
ReconnectTimeout=milliseconds
SQL_ATTR_TF_RECONNECT_TIMEOUT

JDBC:

solid_tf1_reconnect_timeout
[TransparentFailover] ODBC:
WaitTimeout=milliseconds
SQL_ATTR_TF_WAIT_TIMEOUT

JDBC:

solid_tf_wait_timeout

294 IBM solidDB: Programmer Guide


Appendix H. Client-side configuration parameters
The client-side configuration parameters are stored in the client-side [Link]
configuration file and are read when the client starts.

Generally, the factory value settings offer the best performance and operability, but
in some special cases modifying a parameter will improve performance. You can
change the parameters by editing the [Link] configuration file.

The parameter values set in the client side configuration file come to effect each
time an application issues a call to the SqlConnect ODBC function. If the values are
changed in the file during the program's run time, they affect the connections
established thereafter.

Setting client-side parameters through the [Link] configuration file


This topic provides details about the [Link] configuration file.

When solidDB is started, it attempts to open the configuration file [Link]. If the
file does not exist, solidDB uses the factory values for the parameters. If the file
exists, but a value for a particular parameter is not set, solidDB will use a factory
value for that parameter. The factory values may depend on the operating system
you are using.

By default, the client looks for the [Link] file in the current working directory,
which is normally the directory from which you started the client. When searching
for the file, solidDB uses the following precedence (from high to low):
v location specified by the SOLIDDIR environment variable (if this environment
variable is set)
v current working directory

Rules for formatting the client-side [Link] file

When you format the client-side [Link] file, the same rules apply as for the
server-side [Link] file. For more information, refer to section Rules for
formatting the [Link] file in IBM solidDB Administrator Guide.

Client-side [Link] file


[Com]
;use this connect string of no data source given
Listen = tcp [Link] 1315

[Client]
;at SQLConnect, timeout after this time (ms)
ConnectTimeout = 5000

;at any ODBC network request, timeout after this time (ms)
ClientReadTimeout = 10000

[Data Sources]
Primary_Server = tcp irix1 1315, The Primary Server
Secondary_Server = tcp irix2 1315, The Secondary Server

295
Client section
Table 203. Client parameters

[Client] Description Factory Value


This parameter specifies how many result decided by the server
ExecRowsPerMessage rows are sent (pre-fetched) to the client
driver in response to the SQLExecute call
with a SELECT statement. The result rows
are subsequently returned to the
application with the first SQLFetch calls
issued by the application. The value 2
allows for prefetching of single-row
results. If your SELECT statements
usually return larger number of rows,
setting this to an appropriate value can
improve performance significantly.

See also the RowsPerMessage parameter.


If set to yes, the Windows runtime error no
NoAssertMessages dialog is not shown.

This parameter is relevant to the Windows


platform only.
ODBCCharBinding Defines the binding method for character locale
data.

The options are:


v raw (binary)
v locale (the current client locale is used)
v locale:<locale name> (specific code
page is used)

The convention for <locale name> depends


on the operating system. For example, in
Linux environments, the locale name for
the code page GB18030 in Chinese/China
is zh_CN.gb18030. In Windows
environments, the locale name for Latin1
code page in Finnish/Finland is
fin_fin.1252.

The value raw can be used when you


want your database to use the binding
used in the 6.3 or earlier versions of
solidDB.
This parameter switches ODBC handle no
ODBCHandleValidation validation on or off.

See also section ODBC handle validation in


IBM solidDB Programmer Guide for more
information about the
SQL_ATTR_HANDLE_VALIDATION ODBC
attribute.
Specifies the number of rows returned decided by the server
RowsPerMessage from the server in one network message
when an SQLFetch call is executed and
there are no pre-fetched rows.

See also the ExecRowsPerMessage


parameter.

296 IBM solidDB: Programmer Guide


Table 203. Client parameters (continued)

[Client] Description Factory Value


6
StatementCache Statement cache is an internal memory
storing a few previously prepared SQL
statements. With this parameter, you can
set the number of cached statements per
session.
This parameter defines whether yes
UseEncryption passwords are encrypted. If set to no,
passwords are not encrypted.

Communication section
Table 204. Communication parameters

[Com] Description Factory Value


This parameter defines the connection (or read) timeout in milliseconds. A 0 (infinite)
ClientReadTimeout network request fails if no response is received during the time specified.
The value 0 sets the timeout to infinite. This value can be overridden with
the connect string option -r and, further on, with the ODBC attribute
SQL_ATTR_CONNECTION_TIMEOUT.
Note: This parameter applies only to the TCP protocol.
The client-side [Link] parameter defines the default network name tcp localhost 1964
Connect (connect string) for a client to connect to when it establishes a connection (Windows)
to a server.
upipe SOLID (Linux
The format of the connect string is: and UNIX)
protocol_name [options] [host_comput
er_name] server_name

The options and server_name depend on the communication protocol. For


details, see Managing network connections in the IBM solidDB Administrator
Guide.

This value is used also when the SQLConnect() call is issued with an
empty data source name.
The client-side [Link] parameter defines the login timeout in
ConnectTimeout milliseconds. OS-specific

The value of the parameter can be overridden with the connect string
option -c or the ODBC attribute SQL_ATTR_LOGIN_TIMEOUT.
Note: This parameter applies for the TCP protocol only.
This parameter controls the TCP socket linger (SO_LINGER) behavior no
SocketLinger after a close on the socket connection is issued. It indicates if the system
attempts to deliver any buffered data (yes), or if the system discards it
(no), when a close() is issued.
This parameter defines the length of the time interval (in seconds) the
SocketLingerTime socket lingers after a close is issued. If the time interval expires before the 0
graceful shutdown sequence completes, an abortive shutdown sequence
occurs (the data is discarded). The default value zero indicates that the
system default is used (typically, 1 second)

Trace If this parameter is set to yes, trace information about network messages no
for the established network connection is written to a file specified with
the TraceFile parameter.

Appendix H. Client-side configuration parameters 297


Table 204. Communication parameters (continued)

[Com] Description Factory Value

TraceFile If the Trace parameter is set to yes, trace information about network [Link]
messages is written to a file specified with this TraceFile parameter. (written to the
current working
directory of the
server or client
depending on which
end the tracing is
started)

Data Sources section


Table 205. Data Sources parameters

[Data Sources] Description Factory Value Access Mode

logical name = network name, These parameters can be used to give a logical name to a N/A
Description solidDB server in a [Link] file of the client
application.

SharedMemoryAccess section
Table 206. Shared memory access parameters (client-side)
[SharedMemoryAccess] Description Factory value Startup
SignalHandler The SignalHandler parameter controls the SMA signal yes NA
handler functionality.

When set to yes, the SMA driver signal handler handles


the signals defined with the Signals parameter.

The SMA driver signal handler enables the SMA system to


survive the most common application failures, such as
killing or interrupting the applications from outside, or
when one of the application threads runs within the
server code, and another thread running application code
causes application to crash.

Upon the capture of certain signals, the signal handler


closes the SMA connections safely and exits the SMA
application. This means that in most cases, the SMA
server continues to run despite abnormal application exits.

The SMA driver signal handler installs itself when the first
SMA connection is established and uninstalls itself when
the last SMA connection is closed. Previously installed
signal handlers are retained.

298 IBM solidDB: Programmer Guide


Table 206. Shared memory access parameters (client-side) (continued)
[SharedMemoryAccess] Description Factory value Startup
Signals This parameter defines the signals that can break the SMA Linux and UNIX: NA
connection and should be handled by the SMA driver. SIGINT, SIGTERM

The signals are defined as integers or with the following Windows: SIGINT
mnemonics: SIGSTOP, SIGKILL, SIGINT, SIGTERM,
SIGQUIT, SIGABORT.
Note: If the SMA application loops outside of the SMA
driver (for example, does not call any functions), the
signal can fail to terminate the application. In such a case:
1. Throw out the connections at the server.
admin command ’throwout <userid>’
2. Use SIGKILL signal to force the SMA application to
exit.
kill -SIGKILL <pid>

TransparentFailover section
Table 207. TransparentFailover parameters
[TransparentFailover] Description Factory value
ReconnectTimeout This parameter specifies how long (in milliseconds) the driver 10000
should wait until it tries to reconnect to the primary in case of
TF switchover or failover. If the driver cannot find the new
primary (reconnect), an error is returned and the TF connection
becomes broken.
WaitTimeout This parameter specifies how long (in milliseconds) the driver 10000
should wait for the server to switch state. When the driver tries
to reconnect to the servers, it might connect to the server being
in an intermediate (switching or uncertain) state.

Appendix H. Client-side configuration parameters 299


300 IBM solidDB: Programmer Guide
Index
A configuration file
client-side 5, 295
ABS (function) 276 configuring
ACOS (function) 276 client-side configuration file 5
ad hoc query example 41 default settings 5
APD (Application Parameter Descriptor) 230 factory values 5
APIs parameter settings 5
JDBC Driver 51 [Link] 5
application development Connect (parameter) 297
HotStandby connect string 3
creation 41 using 16
testing and debugging 49 Connect Timeout 293
Application Parameter Descriptor (APD) 230 connecting to solidDB
Application Row Descriptor (ARD) 230 with sample application 94
ARD (Application Row Descriptor) 230 connection idle timeout 293
Array interface 56 connection interface 56
ASCII (function) 272 connection timeout 288
ASIN (function) 276 ConnectionPoolDataSource API Functions
ATAN (function) 276 Constructor 68
ATAN2 (function) 276 getConnectionURL 68
autocommit getDescription 68
warnings about SELECT statements 24 getLoginTimeout 68
autocommit mode getLogWriter 68
cursors 24 getPassword 68
JDBC Driver 54 getPooledConnection 68
transactions 24 getURL 68
getUser 68
setConnectionURL 68
B setDescription 68
binding setLoginTimeout 68
assigning storage for rowsets 32 setLogWriter 68
column-wise 32 setPassword 68
row-wise 32 setURL 68
Unicode 166 setUser 68
BIT connections
SQL_BIT 243, 256 terminating 40
BIT_LENGTH (function) 272 ConnectTimeOut (parameter) 297
BLOBs (Binary Large Objects) constraints
interface 56 Gregorian calendar 242
block cursor 31 conversion
bookmarks explicit data type 284
description 38 CONVERT (function)
using 38 description 284
converting data
from C to SQL data types 256
C from SQL to C data types 243
COS (function) 276
CallableStatement interface 56 COT (function) 276
calling procedures 27 CURDATE (function) 279
CAST (function) CURRENT_CATALOG() scalar function 15
description 285 CURRENT_SCHEMA() scalar function 15
CEILING (function) 276 CURRENT_TIMESTAMP (function) 279
CHAR (function) 272 CURRENTTIME (function) 278
CHAR_LENGTH (function) 272 cursors
CHARACTER_LENGTH (function) 273 autocommit 24
Client timeouts 287 block cursor 31
client-side configuration parameters 295 dynamic 33
ClientReadTimeout (parameter) 297 forward 33
CLOB data type scrollable 33
JDBC interface 56 specifying the type 33
CONCAT (function) 273 static 33

301
cursors (continued) functions (continued)
types supported 33 CURRENT_TIMESTAMP 279
using 31 CURRENTTIME 278
CURTIME (function) 279 CURTIME 279
DATABASE 283
DAYNAME 279
D DAYOFMONTH 279
DAYOFWEEK 279
Data Sources
DAYOFYEAR 279
configuring for Windows 20
DEGREES 276
connecting to 15
DIFFERENCE 273
defining in [Link] 18
executing asynchronously 26
empty data source name 19
EXP 277
retrieving catalog information 26
EXTRACT 279
data types 225
FLOOR 277
explicit conversion 284
guidelines for calling 14
DATABASE (function) 283
HOUR 280
DatabaseMetaData interface
IFNULL 283
methods 56
INSERT 273
DAYNAME (function) 279
LCASE 273
DAYOFMONTH (function) 279
LEFT 273
DAYOFWEEK (function) 279
LENGTH 273
DAYOFYEAR (function) 279
LOCATE 274
debugging
LOG 277
applications 49
LOG10 277
DEGREES (function) 276
LTRIM 274
DIFFERENCE (function) 273
MINUTE 280
driver interface (JDBC) 56
MOD 277
dynamic libraries 9
MONTH 280
MONTHNAME 280
NOW 280
E OCTET_LENGTH 274
END LOOP 219 PI 277
errors POSITION 274
JDBC Driver 54 POWER 277
processing messages 40 prototypes 14
SA functions 95 QUARTER 280
sample messages 38 RADIANS 277
ExecRowsPerMessage (parameter) 296 REPEAT 274
EXP (function) 277 REPLACE 274
EXTRACT (function) 279 return codes 15
RIGHT 274
ROUND 277
F RTRIM 275
scalar 14
FLOOR (function) 277
Scalar 271
fn
SECOND 280
usage in {fn func_name} 14, 281
SIGN 277
forward cursor 33
SIN 277
functions
SOUNDEX 275
ABS 276
SPACE 275
ACOS 276
SQLAllocConnect 177
additional extensions to SQL 29
SQLAllocEnv 177
ASCII 272
SQLAllocHandle 177
ASIN 276
SQLAllocStmt 179
ATAN 276
SQLBindCol 181
ATAN2 276
SQLBindParameter 179
BIT_LENGTH 272
SQLBrowseConnect 177
CAST 285
SQLBulkOperations 182
CEILING 276
SQLCancel 184
CHAR 272
SQLCloseCursor 184
CHAR_LENGTH 272
SQLColAttribute 181
CHARACTER_LENGTH 273
SQLColAttributes 181
CONCAT 273
SQLColumnPrivileges 183
CONVERT 284
SQLColumns 183
COS 276
SQLConnect 177
COT 276
SQLCopyDesc 179
CURDATE 279

302 IBM solidDB: Programmer Guide


functions (continued) functions (continued)
SQLDataSources 178 TIMESTAMPDIFF 282
SQLDescribeCol 181 TRIM 275
SQLDescribeParam 180 TRUNCATE 278
SQLDisconnect 184 UCASE 275
SQLDriverConnect 177 Unicode strings 166
SQLDrivers 178 USER 283
SQLEndTran 184 WEEK 282
SQLError 182 YEAR 282
SQLExecDirect 180
SQLExecute 180
SQLExtendedFetch 182
SQLFetch 181
H
header files 14
SQLFetchScroll 182
hints 28
SQLForeignKeys 183
HotStandby
SQLFreeConnect 184
timeouts 293
SQLFreeEnv 184
HOUR (function) 280
SQLFreeHandle 184
SQLFreeStmt 184
SQLGetConnectAttr 178
SQLGetConnectOption 179 I
SQLGetCursorName 180 IFNULL (system function) 283
SQLGetData 182 INSERT (string function) 273
SQLGetDescField 179
SQLGetDescRec 179
SQLGetDiagField 182
SQLGetDiagRec 182
J
Java interfaces
SQLGetEnvAttr 179
Array 56
SQLGetFunctions 178
Blob 56
SQLGetInfo 177
CallableStatement 56
SQLGetStmtAttr 179
Clob 56
SQLGetStmtOption 179
Connection 56
SQLGetTypeInfo 178
database access 51
SQLMoreResults 182
DatabaseMetaData 56
SQLNativeSQL 180
Driver 56
SQLNumParams 180
Naming and directory interface 78
SQLNumResultCols 181
PreparedStatement 56
SQLParamData 180
Ref 56
SQLParamOptions 180
ResultSet 56
SQLPrepare 179
ResultSet class 56
SQLPrimaryKeys 183
ResultSetMetaData 56
SQLProcedureColumns 183
SQLData 56
SQLProcedures 183
SQLInput 56
SQLPutData 180
SQLOutput 56
SQLRowCount 181
Statement 56
SQLSetConnectAttr 178
Struct 56
SQLSetConnectOption 179
Java Transaction API (JTA) 63
SQLSetCursorName 180
JDBC Connection Pooling 68
SQLSetDescField 179
ConnectionPoolDataSource 68
SQLSetDescRec 179
PooledConnection 68
SQLSetEnvAttr 179
JDBC Driver 78
SQLSetParam 180
JNDI 78
SQLSetPos 182
JTA (Java Transaction API) 63
SQLSetScrollOptions 180
SQLSetStmtAttr 179
SQLSetStmtOption 179
SQLSpecialColumns 183 L
SQLStatistics 183 LCASE (function) 273
SQLTablePrivileges 184 LEFT (function) 273
SQLTables 184 LENGTH (function) 273
SQLTransact 184 listen name 16
SQRT 277 LOCATE (function) 274
SUBSTRING 275 lock wait timeout 291
system functions 283 LOG (function) 277
TAN 277 LOG10 (function) 277
time and date 278 login
TIMESTAMPADD 281 timeout 287

Index 303
LOGIN_CATALOG() scalar function
LOOP 219
15
R
LTRIM (function) 274 RADIANS (function) 277
Ref interface
methods 56
REPEAT (function) 274
M REPLACE (function) 274
MaxSpace (parameter) 171 ResultSet interface
MINUTE (function) 280 methods 56
MOD (function) 277 ResultSetMetaData interface
MONTH (function) 280 methods 56
MONTHNAME (function) 280 return code
for functions 15
RIGHT (function) 274
N ROUND (function) 277
native scalar functions 14 rowset 32
network names 16 RowsPerMessage (parameter) 296
NoAssertMessages (parameter) 296 RTRIM (function) 275
non-standard behavior
ODBC 6
NOW (function) 280 S
numeric functions SA
ODBC 275 sample program 94
SaErrorInfo
solidDB SA 95
O scalar functions 14
octet length 240 native 14
OCTET_LENGTH (function) 274 ODBC 271
ODBC SQL-92 271
additional functions to SQL 29 scrollable cursors 33
Driver 14 SECOND (function) 280
extensions 26 server timeouts 290
function support 177 SET LOGREADER BATCH (statement) 176
non-standard behavior 6 SIGN (function) 277
solidDB extensions for ODBC API 29 SIN (function) 277
ODBC handles 23 SocketLinger (parameter) 297
ODBCCharBinding (parameter) 296 SocketLingerTime (parameter) 297
ODBCHandleValidation (parameter) 296 [Link] 295
optimistic lock timeout 292 configuration parameters 295
optimizer hints 28 [Link] 77
solidDB Data Dictionary
Unicode 163
solidDB Export
P Unicode 163
parameters solidDB JDBC Driver
client-side 295 classes and methods 56
PI (function) 277 connection to the database 54
Ping Timeout 293 conversion matrix 90
PooledConnection API Functions DatabaseMetaData interface 56
addConnectionEventListener 68 description 6, 51
close 68 Driver class 56
getConnection 68 getting started 51
removeConnectionEventListener 68 PreparedStatement interface 56
POSITION (function) 274 Ref interface 56
POWER (function) 277 registering 53
PreparedStatement interface ResultSet interface 56
methods 56 ResultSetMetaData interface 56
procedures SQLData interface 56
calling in ODBC 27 SQLInput interface 56
SQLOutput interface 56
Statement interface 56
Q Struct interface 56
QUARTER (function) 280 Unicode 166
query timeout 289 solidDB ODBC API
Unicode 166
solidDB ODBC Driver
description 12

304 IBM solidDB: Programmer Guide


solidDB ODBC Driver (continued) SQLDisconnect (function) 184
driver manager 14 SQLDriverConnect (function) 177
files 12 SQLDrivers (function) 178
installing 11 SQLEndTran (function) 184
on Microsoft Windows 12 SQLError (function) 182
Unicode 166 SQLExecDirect (function) 180
using 11 SQLExecute (function) 180
solidDB ODBC functions 177 SQLExtendedFetch (function) 31, 33, 182
solidDB SA 103 SQLFetch (function) 31, 181
building a sample program 94 SQLFetchScroll (function) 31, 33, 182
connection to the database 94 SQLForeignKeys (function) 183
delete 95 SQLFreeConnect (function) 184
description 93 SQLFreeEnv (function) 184
getting started 94 SQLFreeHandle (function) 184
handling database errors 95 SQLFreeStmt (function) 31, 184
reading data without SQL 95 SQLGetConnectAttr (function) 178
running SQL statements 95 SQLGetConnectOption (function) 179
setting up the development environment 94 SQLGetCursorName (function) 180
transactions and autocommit mode 95 SQLGetData (function) 182
update 95 SQLGetDescField (function) 179
writing data without SQL 95 SQLGetDescRec (function) 179
solidDB SQL Editor 163 SQLGetDiagField (function) 182
SOUNDEX (function) 275 SQLGetDiagRec (function) 182
SPACE (function) 275 SQLGetEnvAttr (function) 179
Speed Loader SQLGetFunctions (function) 178
Unicode 163 SQLGetInfo (function) 177
SQL statements SQLGetStmtAttr (function) 179
execution timeout 290 SQLGetStmtOption (function) 179
SQL_C_BIT SQLGetTypeInfo (function) 178
binding C variable of type SQL_C_BIT 243, 256 SQLInput interface
SQL_C_DEFAULT methods 56
avoid use of 234 SQLMoreResults (function) 182
SQL_CLOSE SQLNativeSQL (function) 180
option in SQLFreeStmt() function call 31 SQLNumParams (function) 180
SQL_DELETE SQLNumResultCols (function) 181
option in SQLSetPos() function call 31 SQLOutput interface
SQL_NTS methods 56
null-terminated string 269 SQLParamData (function) 180
SQL_POSITION SQLParamOptions (function) 180
option in SQLSetPos() function call 31 SQLPrepare (function) 179
SQL_ROWSET_SIZE SQLPrimaryKeys (function) 183
option in SQLSetStmtAttr() function call 32 SQLProcedureColumns (function) 183
SQL_UPDATE SQLProcedures (function) 183
option in SQLSetPos() function call 31 SQLPutData (function) 180
SQLAllocConnect (function) 177 SQLRowCount (function) 181
SQLAllocEnv (function) 177 SQLSetConnectAttr (function) 178
SQLAllocHandle (function) 177 SQLSetConnectOption (function) 179
SQLAllocStmt (function) 179 SQLSetCursorName (function) 180
SQLBindCol SQLSetDescField (function) 179
function description 32 SQLSetDescRec (function) 179
SQLBindCol (function) 181 SQLSetEnvAttr (function) 179
SQLBindParameter (function) 179 SQLSetParam (function) 180
SQLBrowseConnect (function) 177 SQLSetPos (function) 31, 182
SQLBulkOperations (function) 182 SQLSetScrollOptions (function) 180
SQLCancel (function) 184 SQLSetStmtAttr (function) 32, 179
SQLCloseCursor (function) 184 dynamic cursors 33
SQLColAttribute (function) 181 SQLSetStmtOption (function) 179
SQLColAttributes (function) 181 SQLSpecialColumns (function) 183
SQLColumnPrivileges (function) 183 SQLStatistics (function) 183
SQLColumns (function) 183 SQLTablePrivileges (function) 184
SQLConnect (function) 177 SQLTables (function) 184
SQLCopyDesc (function) 179 SQLTransact (function) 184
SQLData interface SQRT (function) 277
methods 56 Statement interface
SQLDataSources (function) 178 methods 56
SQLDescribeCol (function) 181 StatementCache (parameter) 297
SQLDescribeParam (function) 180 static cursor 33

Index 305
static library 9 UTF-8
static SQL description 160
code example 41
stored procedures
JDBC Driver 56
string functions
V
Variables
ODBC 272
Unicode 166
struct interface
solidDB JDBC Driver 56
SUBSTRING (function) 275
W
WebSphere
T compatibility 63
WEEK (function) 282
table lock wait timeout 292
TAN (function) 277
TC Info 16
testing Y
applications 49 YEAR (function) 282
Timeout controls 287
TIMESTAMPADD (function) 281
TIMESTAMPDIFF (function) 282
Trace (parameter) 297
TraceFile (parameter) 298
transaction idle timeout 292
transactions
autocommit mode 24
committing read-only 24
JDBC Driver 54
terminating 40
Transfer Octet Length 240
translation
effect on Unicode columns 166
TRIM (function) 275
TRUNCATE (function) 278

U
UCASE (function) 275
Unicode
character translation 166
compliance 159
converting 164
creating columns for storing data 161
description 159
encoding forms 160
loading data 161, 163
setting up 161, 166
solidDB Data Dictionary 163
solidDB Export 163
solidDB JDBC Driver 166
solidDB ODBC API 166
solidDB ODBC Driver 166
solidDB Remote Control 163
solidDB SQL Editor 163
Speed Loader 163
standard 160
string functions 166
user names and passwords 161
using in database entity names 161
variables and binding 166
unixODBC 20
UseEncryption (parameter) 297
USER (function) 283
UTF-16
description 160

306 IBM solidDB: Programmer Guide


Notices
© Copyright Oy IBM Finland Ab 1993, 2013.

All rights reserved.

No portion of this product may be used in any way except as expressly authorized
in writing by IBM.

This product is protected by U.S. patents 6144941, 7136912, 6970876, 7139775,


6978396, 7266702, 7406489, 7502796, and 7587429.

This product is assigned the U.S. Export Control Classification Number


ECCN=5D992b.

This information was developed for products and services offered in the U.S.A.

IBM may not offer the products, services, or features discussed in this document in
other countries. Consult your local IBM representative for information on the
products and services currently available in your area. Any reference to an IBM
product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product,
program, or service that does not infringe any IBM intellectual property right may
be used instead. However, it is the user's responsibility to evaluate and verify the
operation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matter
described in this document. The furnishing of this document does not grant you
any license to these patents. You can send license inquiries, in writing, to:

IBM Director of Licensing


IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.

For license inquiries regarding double-byte (DBCS) information, contact the IBM
Intellectual Property Department in your country or send inquiries, in writing, to:

Intellectual Property Licensing


Legal and Intellectual Property Law
IBM Japan Ltd.
1623-14, Shimotsuruma, Yamato-shi
Kanagawa 242-8502 Japan

The following paragraph does not apply to the United Kingdom or any other
country where such provisions are inconsistent with local law: INTERNATIONAL
BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION "AS IS"
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE. Some states do not allow disclaimer of express or implied warranties in
certain transactions, therefore, this statement may not apply to you.

307
This information could include technical inaccuracies or typographical errors.
Changes are periodically made to the information herein; these changes will be
incorporated in new editions of the publication. IBM may make improvements
and/or changes in the product(s) and/or the program(s) described in this
publication at any time without notice.

Any references in this information to non-IBM Web sites are provided for
convenience only and do not in any manner serve as an endorsement of those Web
sites. The materials at those Web sites are not part of the materials for this IBM
product and use of those Web sites is at your own risk.

IBM may use or distribute any of the information you supply in any way it
believes appropriate without incurring any obligation to you.

Licensees of this program who wish to have information about it for the purpose
of enabling: (i) the exchange of information between independently created
programs and other programs (including this one) and (ii) the mutual use of the
information which has been exchanged, should contact:

IBM Canada Limited


Office of the Lab Director
8200 Warden Avenue
Markham, Ontario
L6G 1C7
CANADA

Such information may be available, subject to appropriate terms and conditions,


including in some cases, payment of a fee.

The licensed program described in this document and all licensed material
available for it are provided by IBM under terms of the IBM Customer Agreement,
IBM International Program License Agreement or any equivalent agreement
between us.

Any performance data contained herein was determined in a controlled


environment. Therefore, the results obtained in other operating environments may
vary significantly. Some measurements may have been made on development-level
systems and there is no guarantee that these measurements will be the same on
generally available systems. Furthermore, some measurements may have been
estimated through extrapolation. Actual results may vary. Users of this document
should verify the applicable data for their specific environment.

Information concerning non-IBM products was obtained from the suppliers of


those products, their published announcements or other publicly available sources.
IBM has not tested those products and cannot confirm the accuracy of
performance, compatibility or any other claims related to non-IBM products.
Questions on the capabilities of non-IBM products should be addressed to the
suppliers of those products.

All statements regarding IBM's future direction or intent are subject to change or
withdrawal without notice, and represent goals and objectives only.

This information contains examples of data and reports used in daily business
operations. To illustrate them as completely as possible, the examples include the

308 IBM solidDB: Programmer Guide


names of individuals, companies, brands, and products. All of these names are
fictitious and any similarity to the names and addresses used by an actual business
enterprise is entirely coincidental.

COPYRIGHT LICENSE:

This information contains sample application programs in source language, which


illustrate programming techniques on various operating platforms. You may copy,
modify, and distribute these sample programs in any form without payment to
IBM, for the purposes of developing, using, marketing or distributing application
programs conforming to the application programming interface for the operating
platform for which the sample programs are written. These examples have not
been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or
imply reliability, serviceability, or function of these programs. The sample
programs are provided "AS IS", without warranty of any kind. IBM shall not be
liable for any damages arising out of your use of the sample programs.

Each copy or any portion of these sample programs or any derivative work, must
include a copyright notice as follows:

© your company name) (year). Portions of this code are derived from IBM Corp.
Sample Programs.

© Copyright IBM Corp. _enter the year or years_. All rights reserved.

If you are viewing this information softcopy, the photographs and color
illustrations may not appear.

Trademarks

IBM, the IBM logo, [Link]®, Solid, solidDB, InfoSphere, DB2®, Informix®, and
WebSphere are trademarks or registered trademarks of International Business
Machines Corp., registered in many jurisdictions worldwide. Other product and
service names might be trademarks of IBM or other companies. A current list of
IBM trademarks is available on the Web at “Copyright and trademark information”
at [Link]/legal/[Link].

Java and all Java-based trademarks and logos are trademarks or registered
trademarks of Oracle and/or its affiliates.

Linux is a registered trademark of Linus Torvalds in the United States, other


countries, or both.

Microsoft and Windows are trademarks of Microsoft Corporation in the United


States, other countries, or both.

UNIX is a registered trademark of The Open Group in the United States and other
countries.

Other product and service names might be trademarks of IBM or other companies.

Notices 309
310 IBM solidDB: Programmer Guide


Printed in USA

SC23-9870-06

You might also like