Access the database using ODBC (1)

Source: Internet
Author: User
Tags sql server driver

Header files and Lib libraries used before using ODBC APIs
# Include "SQL. H" // This is 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 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 ")

Odbc api Return Value
The return value of odbc api is defined as sqlreturn. The returned values are SQL _success, SQL _success_with_info, and the error code is returned when the operation fails. Note that if the ODBC return value is SQL _success_with_info, it does not indicate that the execution is completely successful, but it indicates that the execution is successful but contains a certain error message. When an error occurs, ODBC returns a result set of the error message. You need to traverse all rows in the result set. This is similar to the query of the SQL statement execution result set described later.

Sqlallochandle create ODBC handle
Sqlreturn sqlallochandle (
SQL smallint handletype, // handle type to be applied
Sqlhandle inputhandle, // input handle
Sqlhandle * outputhandleptr); // output handle, that is, specify the handle to be applied in the first parameter
The value of handletype can be:
1. SQL _handle_env
2. SQL _handle_dbc
3. SQL _handle_stmt

Connect to the database using sqlconnect
Sqlreturn sqlconnect (
Sqlhdbc connectionhandle, // DBC handle, hdbc
Sqlchar * servername, // The odbc dsn name
Sqlsmallint namelength1, // specify the length of the servername parameter (SQL _cnt can be used)
Sqlchar * username, // database username
Sqlsmallint nameleng22. // specify the length of the username parameter (SQL _cnt can be used)
Sqlchar * authentication, // Database User Password
Sqlsmallint namelength3) // specify the length of the authentication parameter (you can use SQL _nt)
For example:
Sqlconnect (
Hdbc,
(Sqltchar *) szdsn, SQL _cnt,
(Sqltchar *) szuserid, SQL _cnt,
(Sqltchar *) szpassword, SQL _cnt );

Sqlexecdirect directly executes SQL statements
Sqlreturn sqlexecdirect (
Sqlhstmt statementhandle, // stmt handle
Sqlchar * statementtext, // SQL statement
Sqlinteger textlength) // specifies the length of the statementtext parameter.
If the function is successfully executed, you will get a result set. Otherwise, an error message will be returned.

Obtain the SQL statement execution result
For SQL query statements, ODBC returns a cursor, which corresponds to a result set (which can be understood as a table ). Developers can use the cursor to view all the results. You can use the odbc api function to move the cursor and obtain the value of the column field pointed to by the current cursor. In addition, you can use the cursor to modify the data pointed to by the cursor, which is directly reflected in the database.

Sqlfetch move cursor
Sqlreturn sqlfetch (sqlhstmt statementhandle );
After you call sqlexecdirect to execute an SQL statement, you need to traverse the result set to obtain data. Statementhandle is the stmt handle, which must have been executed. When the sqlfetch function is called, The cursor will be moved to the next record. When the cursor moves to the last record set, the function will return SQL _no_data.

Sqlgetdata: obtain the value of a column at the cursor.
Sqlreturn sqlgetdata (
Sqlhstmt statementhandlem, // stmt handle
Sqlusmallint columnnumber, // column number, starting with 1
Sqlsmallint targettype, // the C language type of the data buffer (targetvalueptr)
Sqlpointer targetvalueptr, // data buffer
Sqlinteger bufferlength, // The length of the data buffer (targetvalueptr)
Sqlinteger * strlen_or_indptr); // returns the byte length of the current field.

Sqlbindcol obtains field data through Column Binding
Sqlreturn sqlbindcol (
Sqlhstmt statementhandle, // stmt statement
Sqlusmallint columnnumber, // column number, starting with 1
Sqlsmallint targettype, // the C language type of the data buffer (targetvalueptr)
Sqlpointer targetvalueptr, // data buffer
Sqlinteger bufferlength, // The length of the data buffer (targetvalueptr) in bytes
Sqlinteger * strlen_or_indptr); // returns the byte length of the current field.
Sqlgetdata can be used to read field values from the result set. However, for speed purposes, you can use the Column Binding (sqlbindcol) method to send data to the specified variable after each cursor movement.

Sqlnumresultcols
Sqlreturn sqlnumresultcols (
Sqlhstmt statementhandle, // stmt handle
Sqlsmallint * columncountptr); // The number of returned Columns

Sqlrowcount: number of rows affected after SQL statement execution
Sqlreturn sqlrowcount (
Sqlhstmt statementhandle, // stmt handle
Sqlinteger * rowcountptr); // Number of affected data rows
You can use sqlexecdirect to execute SQL statements to insert, modify, and delete data. After executing the insert, modify, and delete SQL statements, you can use the sqlrowcount function to obtain the number of affected data rows.

Sqldescribecol
Sqlreturn sqldescribecol (
Sqlhstmt statementhandle, // stmt handle
Sqlsmallint columnnumber, // the sequence number of the expected column, which is calculated from 1
Sqlchar * columnname, // get the column name
Sqlsmallint bufferlength, // specify the maximum length of the columnname Parameter
Sqlsmallint * namelengthptr, // returns the length of the column name
Sqlsmallint * datatypeptr, // ODBC Data Type of the returned column, see table
Sqluinteger * columnsizeptr, // returns the length of the column
Sqlsmallint * decimaldigitsptr, // The number of digits after the decimal point returned when the column is of the numeric type
Sqlsmallint * nullableptr); // specifies whether the column allows null values.

Sqlsetstmtattr: Set ODBC cursor type
Sqlreturn sqlsetstmtattr (
Sqlhstmt statementhandle, // stmt handle
Sqlinteger attribute, // specify the attribute type to be set
Sqlpointer valueptr, // provided parameter value
Sqlinteger stringlength); // specify the length of the parameter. If the parameter is an integer, set it
// SQL _is_integer. When the parameter is a string
// It is the string length or SQL _cnt
The sqlsetstmtattr function allows us to use different cursor types in ODBC.

Attribute

Valueptr

Function

SQL _attr_async_enable Integer. value:
SQL _async_enable_off,
SQL _async_enable_on
Whether asynchronous execution is used
SQL _attr_query_timeout Set a valid integer Time-out seconds for SQL statement execution. If it is set to 0, no time-out occurs.
SQL _attr_cursor_type Integer. value:
SQL _cursor_forward_only,
SQL _cursor_static,
SQL _cursor_dynamic, SQL _cursor_keyset_driven
Set the cursor type

1. Forward cursor: SQL _cursor_forward_only. The cursor only scrolls forward.
2. static cursor: SQL _cursor_static. The data in the result set is static. This means that the data in the returned result set will not change after the query is executed, even if other programs update the records in the database, the records in the result set will not change.
3. dynamic Cursor: SQL _cursor_dynamic. After the cursor is opened, when the data value of the row in the result set changes, the changes can be reflected in the result set corresponding to the cursor. These changes include: modify, add, and change the order of rows in the result set. However, note that if a row is deleted, it cannot be reflected in the current result set because the deleted row no longer appears in the current result set. The result set corresponding to the dynamic cursor is rebuilt when the data changes. For example, assume that the dynamic cursor has obtained two rows, and then the other application updates one row in the two rows and deletes the other row. If the Dynamic Cursor tries to get those rows, it cannot detect deleted rows (because there is only one row in the current result set, but do not use this method to detect deleted rows, this may also occur because the row data cannot meet the query conditions after being changed), but returns the new value of the updated row.
4. key set cursor: SQL _cursor_keyset_driven. Unlike the above dynamic cursor, the key set cursor can detect row deletion and modification, but cannot detect row addition and result set order changes. Because the entire result set is created when the cursor is created, the records and sequence in the result set have been fixed, which is the same as the static cursor. Therefore, the keyset cursor is a type between a static cursor and a dynamic cursor.
For example, sqlsetstmtattr (hstmt, SQL _attr_cursor_type, (sqlpointer) SQL _cursor_keyset_driven, 0 );

Sqlfetchscroll queries with a scroll cursor
Sqlreturn sqlfetchscroll (
Sqlhstmt statementhandle, // stmt statement
Sqlsmallint fetchorientation, // The method of cursor scrolling, as shown in the table below
Sqlinteger fetchoffset); // cursor scroll position
The sqlfetch function described above only allows the cursor to move forward, but in many cases we need the cursor to move forward and backward. We need to use another function sqlfetchscroll, but before that, please use sqlsetstmtattr to correctly set the cursor type.

Fetchorientation

Meaning

SQL _fetch_next Scroll to the next line. At this time, the call is equivalent to sqlfetch. The fetchoffset parameter will be ignored (0 value)
SQL _fetch_prior Scroll to the previous row. The fetchoffset parameter is ignored (0 value)
SQL _fetch_first Scroll to the first line. The fetchoffset parameter is ignored (0 value)
SQL _fetch_last Scroll to the last row. The fetchoffset parameter is ignored (0 value)
SQL _fetch_absolute Scroll to the absolute line specified by the fetchoffset parameter.
SQL _fetch_relative From the current position to the relative row specified by the fetchoffset parameter, fetchoffset greater than 0 indicates rolling forward, fetchoffset less than 0 indicates rolling backward

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.