示例
此示例将演示如何基于GaussDB 100提供的ODBC接口开发应用程序。
#if WIN32 #include <windows.h> #endif #include <stdlib.h> #include <stdio.h> #include "sql.h" #include "sqlext.h" int main() { SQLHANDLE h_env = NULL; SQLHANDLE h_conn = NULL; SQLHANDLE h_stmt = NULL; SQLINTEGER ret; SQLCHAR *dsn = (SQLCHAR *)"myzenith";/*数据源名称*/ SQLCHAR *username = (SQLCHAR *)"omm";/*用户名*/ SQLCHAR *password = (SQLCHAR *)"gaussdb_123";/*密码*/ SQLSMALLINT dsn_len = (SQLSMALLINT)strlen((const char *)dsn); SQLSMALLINT username_len = (SQLSMALLINT)strlen((const char *)username); SQLSMALLINT password_len = (SQLSMALLINT)strlen((const char *)password); //申请句柄资源 ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &h_env); if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO)) { return SQL_ERROR; } //设置环境句柄属性 if (SQL_SUCCESS != SQLSetEnvAttr(h_env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0)) { SQLFreeHandle(SQL_HANDLE_ENV, h_env); return SQL_ERROR; } //分配链接句柄 if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, h_env, &h_conn)) { return SQL_ERROR; } //设置链接句柄自动提交属性 if (SQL_SUCCESS != SQLSetConnectAttr(h_conn, SQL_ATTR_AUTOCOMMIT, (void *)1, 0)) { SQLFreeHandle(SQL_HANDLE_DBC, h_conn); SQLFreeHandle(SQL_HANDLE_ENV, h_env); return SQL_ERROR; } //链接数据源 SQLConnect(h_conn, dsn, dsn_len, username, username_len, password, password_len); //申请执行句柄 if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, h_conn, &h_stmt)) { SQLFreeHandle(SQL_HANDLE_DBC, h_conn); SQLFreeHandle(SQL_HANDLE_ENV, h_env); return SQL_ERROR; } //创建表,并插入一条记录 SQLCHAR* create_table_sql = (SQLCHAR*)"create table test(col int)"; SQLExecDirect(h_stmt, create_table_sql, strlen(create_table_sql)); SQLCHAR* insert_sql = (SQLCHAR*)"insert into test (col) values(:col)"; SQLPrepare(h_stmt, insert_sql, strlen(insert_sql)); int col = 1; SQLBindParameter(h_stmt, 1, SQL_PARAM_INPUT, SQL_C_SSHORT, SQL_INTEGER, sizeof(int), 0, &col, 0, NULL); SQLExecute(h_stmt); //查询记录,并打印 SQLCHAR* select_sql = (SQLCHAR*)"select col from test"; SQLPrepare(h_stmt, select_sql, strlen(select_sql)); int colvalue = 0; SQLBindCol(h_stmt, 1, SQL_C_SSHORT, &colvalue, sizeof(colvalue), NULL); SQLExecute(h_stmt); do { ret = SQLFetch(h_stmt); if (ret != SQL_SUCCESS && ret != SQL_NO_DATA) { break; } if (ret == SQL_SUCCESS) { printf("get %d from table 'test'.\n", colvalue); } } while (ret != SQL_NO_DATA); SQLINTEGER row = 0; SQLRowCount(h_stmt, &row); printf("get %d rows table 'test'.\n", row); //断开数据库链接 SQLDisconnect(h_conn); //释放句柄资源 SQLFreeHandle(SQL_HANDLE_STMT, h_stmt); SQLFreeHandle(SQL_HANDLE_DBC, h_conn); SQLFreeHandle(SQL_HANDLE_ENV, h_env); return SQL_SUCCESS; }
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。