ODBC access to the database (reprint)

使用ODBC API之前要用到的头文件和LIB库
#include "sql.h"              // This is the the main include for ODBC Core functions.
#include "sqlext.h"         // This is the include for applications using the Microsoft SQL Extensions
#include "sqltypes.h"    // This file defines the types used in ODBC
#include "sqlucode.h"   // This is the the unicode include for ODBC Core functions
#include "odbcss.h"      // This is the application include file for the SQL Server driver specific defines.
#pragma coment(lib, "odbc32.lib")

The return value of the ODBC API
         ODBC API return value is defined as: SQLRETURN. Upon successful return value: SQL_SUCCESS, SQL_SUCCESS_WITH_INFO; return error code on failure. One thing to note is that if ODBC return value: SQL_SUCCESS_WITH_INFO does not mean that you perform a full success, but indicated that the successful implementation but with a certain error messages. When performing bug in the ODBC returns a result set with an error message, you need to iterate all rows in the result set, the result set of ideas execution mentioned this and the following SQL query statement is very similar.

SQLAllocHandle create ODBC handles
        SQLRETURN SQLAllocHandle (
              SQL SMALLINT HandleType, // handle types need to apply
              SQLHANDLE InputHandle, // input handle
              SQLHANDLE * OutputHandlePtr); // output handle that specifies the need to apply in the first parameter handle
        the first parameter of HandleType value can be:
            1. the SQL_HANDLE_ENV
            2. the SQL_HANDLE_DBC
            3. the SQL_HANDLE_STMT

SQLConnect connection database
        SQLRETURN SQLConnect (
              SQLHDBC ConnectionHandle, the DBC // handle, hdbc
              SQLCHAR * ServerName, // the name of the ODBC DSN
              SQLSMALLINT NameLength1, // ServerName parameter specifies the total length (optionally SQL_NTS)
              SQLCHAR * UserName, // database username
              SQLSMALLINT NameLength2, // UserName parameters specified length (can SQL_NTS)
              SQLCHAR * Authentication, // user password database
              SQLSMALLINT NameLength3) // Authentication parameters specified length (may be SQL_NTS)
    For example:
        the SQLConnect (
                hdbc,
                (SQLTCHAR *) szDSN , SQL_NTS,
                (SQLTCHAR *) szUserId, SQL_NTS,
                (SQLTCHAR*)szPassword, SQL_NTS);

SQLExecDirect to execute SQL statements directly
        SQLRETURN SQLExecDirect (
            SQLHSTMT StatementHandle, // handle STMT
            SQLCHAR * StatementText, // SQL statement
            SQLINTEGER TextLength) // StatementText length parameter, you can use SQL_NTS
        if the function is successful, you will get a result set, or else will return an error message.

Getting SQL statement executed results
        for SQL queries, ODBC returns a cursor, the cursor is a corresponding result set (can be understood as a form). Developers use the cursor to see all the results, you can use the ODBC API function to move the cursor, and get the value of the current cursor to the column field row. Further modifications may also be data cursor by the cursor is currently pointing, the changes will be reflected directly into the database.

SQLFetch move the cursor
        SQLRETURN SQLFetch (SQLHSTMT StatementHandle);
        after you call the SQLExecDirect to execute SQL statements, you need to traverse the result set to get the data. StatementHandle is STMT handle, it must be enforced. When SQLFetch function call, the cursor is moved to the next record, the record set when the cursor to the last one, the function will return SQL_NO_DATA.

 SQLGetData cursor obtained at a column value
        SQLRETURN SQLGetData (
            SQLHSTMT StatementHandlem, // STMT handle
            SQLUSMALLINT ColumnNumber, // column number starts at 1
            SQLSMALLINT TargetType, // data buffer (the TargetValuePtr) a C language type
            SQLPOINTER TargetValuePtr, // data buffer
            SQLINTEGER BufferLength, // data buffer length (the TargetValuePtr) of
            SQLINTEGER * StrLen_or_IndPtr); // returns the byte length of the current field obtained

SQLBindCol to bind obtain field data by column
        SQLRETURN SQLBindCol (
            SQLHSTMT StatementHandle, // STMT statement
            SQLUSMALLINT ColumnNumber, // column number, starting at 1
            SQLSMALLINT TargetType, // data buffer (TargetValuePtr) of the C language type
            SQLPOINTER TargetValuePtr, // data buffer
            SQLINTEGER BufferLength, // data buffer (the TargetValuePtr) byte length
            SQLINTEGER * StrLen_or_IndPtr); // returns the byte length of the current field obtained
        when reading the field values from the result set can be used SQLGetData, but may be utilized for speed column binding (SQLBindCol) manner, so that after each movement of the cursor ODBC transmit data to specified variable

SQLNumResultCols number of columns in the result set obtained
        SQLRETURN SQLNumResultCols (
            SQLHSTMT the StatementHandle, // STMT handle
            SQLSMALLINT * ColumnCountPtr); // returns the number of columns

Been affected after SQLRowCount execute SQL statements rows
        SQLRETURN SQLRowCount (
            SQLHSTMT StatementHandle, // handle STMT
            SQLINTEGER * RowCountPtr); // number of rows affected data
        you can insert SQL statements executed by SQLExecDirect, modify, and delete data in the number of rows insert, modify, and delete SQL statements can be obtained after the data affected by SQLRowCount function.

Of columns in the result obtained SQLDescribeCol described
        SQLRETURN SQLDescribeCol (
            SQLHSTMT the StatementHandle, // STMT handle
            SQLSMALLINT ColumnNumber, // number of columns need to be counted from the start. 1
            SQLCHAR * ColumnName, // the name of the column to give
            SQLSMALLINT BufferLength, // specified ColumnName the maximum length parameter
            SQLSMALLINT * NameLengthPtr, // returns the length of the column names
            SQLSMALLINT * DataTypePtr, // return the ODBC data type of a column in Table
            SQLUINTEGER * ColumnSizePtr, // returns the length of the column
            SQLSMALLINT * DecimalDigitsPtr, // number as when after the decimal point when return data type bits
            SQLSMALLINT * NullablePtr); // indicates whether the column allows nulls

SQLSetStmtAttr provided ODBC cursor type
        SQLRETURN SQLSetStmtAttr (
            SQLHSTMT the StatementHandle, // STMT handle
            SQLINTEGER Attribute, // attribute type to be set
            SQLPOINTER ValuePtr, parameter values provide //
            SQLINTEGER StringLength); // specified length parameter, when the parameter is an integer when set
                                                // SQL_IS_INTEGER, is set when the parameter is a string
                                                // is a string or SQL_NTS

SQLSetStmtAttr can function so that we can use in different ODBC cursor type
the Attribute
 ValuePtr
 role
 
SQL_ATTR_ASYNC_ENABLE integer value of:
SQL_ASYNC_ENABLE_OFF,
SQL_ASYNC_ENABLE_ON whether to use asynchronous execution function
 
timeout in seconds when SQL_ATTR_QUERY_TIMEOUT set a valid integer execution of SQL statements, set to 0 It indicates no timeout
 
SQL_ATTR_CURSOR_TYPE integer value of:
SQL_CURSOR_FORWARD_ONLY,
SQL_CURSOR_STATIC,
SQL_CURSOR_DYNAMIC, cursor type SQL_CURSOR_KEYSET_DRIVEN provided
 
        1. cursor forward: SQL_CURSOR_FORWARD_ONLY, only the scroll cursor forward.
        2. Static cursor: SQL_CURSOR_STATIC, the resulting data set is static, which is explained after the query is executed, the data returned result set will not change, even if there is another program to update the records in the database, the result set record it will not change.
        3. Dynamic cursor: SQL_CURSOR_DYNAMIC, after the cursor is opened, when the result set of data values corresponding to the row is changed, the change can be reflected in the result set corresponding to the cursor, changes include: field modifications, additions, results change the order of rows in. However, note that if the row is deleted can not be reflected in the result set in the present, because of the deleted rows no longer appear focused on the current result. Dynamic cursor result set corresponding to a change in the data is rebuilt. For example, suppose a dynamic cursor has acquired two lines, then another application updates two rows in a row, and remove another row, if the dynamic cursor and then trying to get those lines, it will not detect the deleted rows ( because the current result set is only one line, but do not use this approach to detect rows are deleted, because this situation may also be because the data line is changed can no longer satisfy the query), but returns the new value of the updated row .
        4. Set Cursor keys: SQL_CURSOR_KEYSET_DRIVEN, and dynamic cursor except that the above set of cursor keys and modifications to detect the removal line, but can not detect the line and adding the result set sequence variation. Because when the cursor is created on the entire result set is created, the result set records and order have been fixed, and this is the same as static cursor. Keyset cursor so to speak, a cursor type is interposed between the static and dynamic cursor cursor.
        Such as: SQLSetStmtAttr (hstmt, SQL_ATTR_CURSOR_TYPE, ( SQLPOINTER) SQL_CURSOR_KEYSET_DRIVEN, 0);

SQLFetchScroll use scrollable cursor query
        SQLRETURN SQLFetchScroll (
            SQLHSTMT StatementHandle, // STMT statement
            SQLSMALLINT FetchOrientation, // cursor scroll all the way, the table below
            SQLINTEGER FetchOffset); // scroll cursor position
        described in the previous SQLFetch function can only make the cursor before moving, but in many cases we need to be able to move the cursor back and forth. We need to use another function SQLFetchScroll, but before you use it again SQLSetStmtAttr correctly set the cursor type.
FetchOrientation
 meaning
 
SQL_FETCH_NEXT scroll to the next line, this time calling equivalent to SQLFetch, parameters FetchOffset is ignored (with a value of 0)
SQL_FETCH_PRIOR scroll to the previous line, parameter FetchOffset is ignored (with a value of 0)
SQL_FETCH_FIRST scroll to the first line, parameter FetchOffset will be ignored (with a value of 0)
SQL_FETCH_LAST scroll to the last line, FetchOffset parameter is ignored (with a value of 0)
SQL_FETCH_ABSOLUTE FetchOffset scroll to the parameters specified absolute row
SQL_FETCH_RELATIVE scroll the current position to the specified parameter FetchOffset opposite rows, in rolling forward FetchOffset greater than 0, less than 0 indicates rolling backwards FetchOffset


Using C / C ++ language development, then there must convert the data of the problem will exist between language and ODBC, because some ODBC data types that exist in the C language does not exist. So do not use int, float the actual type of the C language and the like in the ODBC of the development process should be used to define the variables ODBC defined data type to define variables such as SQLINTEGER, SQLFLOAT. In the way ODBC macro definition defines the data type of C language and ODBC used:
C of the type identifier The
 ODBC C typedef
 C of the type
 
SQL_C_CHAR
 SQLCHAR *
 unsigned char *
 
SQL_C_SSHORT
 SQLSMALLINT
 Short int
 
SQL_C_USHORT
 SQLUSMALLINT
 unsigned Short int
SQL_C_SLONG
 SQLINTEGER Long int
SQL_C_ULONG
 SQLUINTEGER
 unsigned Long int
SQL_C_FLOAT SQLREAL
 float
SQL_C_DOUBLE
 SqlDouble, SQLFLOAT
 Double
 
SQL_C_BIT SQLCHAR
 unsigned char
SQL_C_STINYINT SQLSCHAR
 signed char
 
SQL_C_UTINYINT
 SQLCHAR
 unsigned char
 
SQL_C_SBIGINT SQLBIGINT
 _int64
 
SQL_C_UBIGINT
 SQLUBIGINT
 unsigned _int64
 
SQL_C_BINARY
 SQLCHAR *
 unsigned char *
 
SQL_C_XML
 SQLCHAR *
 unsigned char *
SQL_C_BOOKMARK BOOKMARK unsigned long int
 
SQL_C_VARBOOKMARK SQLCHAR *
 unsigned char *
 
SQL_C_TYPE_DATE SQL_DATE_STRUCT
 struct tagDATE_STRUCT
{
        SQLSMALLINT        year;
        SQLUSMALLINT     month;
        SQLUSMALLINT     day;
} DATE_STRUCT;
SQL_C_TYPE_TIME
 SQL_TIME_STRUCT
 struct tagTIME_STRUCT
{
         SQLUSMALLINT hour;
         SQLUSMALLINT minute;
         SQLUSMALLINT second;
} TIME_STRUCT;
 
SQL_C_TYPE_TIMESTAMP
 SQL_TIMESTAMP_STRUCT
 struct tagTIMESTAMP_STRUCT
{
         SQLSMALLINT     year;
         SQLUSMALLINT  month;
         SQLUSMALLINT  day;
         SQLUSMALLINT  hour;
         SQLUSMALLINT  minute;
         SQLUSMALLINT  second;
         SQLUINTEGER      fraction;
} TIMESTAMP_STRUCT
 
SQL_C_NUMERIC
 SQL_NUMERIC_STRUCT struct tagSQL_NUMERIC_STRUCT
{
         SQLCHAR     precision;
         SQLSCHAR   scale;
         SQLCHAR     sign;
         SQLCHAR     val[SQL_MAX_NUMERIC_LEN];
} SQL_NUMERIC_STRUCT;
 
SQL_C_GUID
 SQLGUID
 struct tagSQLGUID {
        DWORD  Data1;
        WORD     Data2;
        WORD     Data3;
        BYTE        Data4[8];
} SQLGUID;
 
All C interval data types
 SQL_INTERVAL_STRUCT
 See the "C Interval Structure" section, later in this appendix.
 

Reproduced in: https: //www.cnblogs.com/shelvenn/archive/2008/01/15/1039714.html

Guess you like

Origin blog.csdn.net/weixin_33920401/article/details/94184498