/*-----------------------------------------------------------------*/ int main() { SQLCHAR InputParam[25] = "Special Instructions"; SQLINTEGER Indicator = SQL_DATA_AT_EXEC; GET_LOGIN_VARS(); VERBOSE("calling SQLAllocHandle(EnvHandle) \n"); rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvHandle); assert(rc == SQL_SUCCESS); assert(EnvHandle != (SQLHANDLE) NULL); rc = SQLSetEnvAttr(EnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER); assert(rc == SQL_SUCCESS); VERBOSE("calling SQLAllocHandle(ConHandle) \n"); rc = SQLAllocHandle(SQL_HANDLE_DBC, EnvHandle, &ConHandle); assert(ConHandle != (SQLHANDLE) NULL); assert(rc == SQL_SUCCESS); if (dsn[0]) rc = SQLDriverConnect(ConHandle, NULL, dsn, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); else rc = SQLConnect(ConHandle, twoTask, SQL_NTS, (SQLCHAR *) userName, SQL_NTS, (SQLCHAR *) pswd, SQL_NTS); assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO); VERBOSE("connected to database %s\n", twoTask); rc = SQLAllocStmt(ConHandle, &StmtHandle); assert(rc == SQL_SUCCESS); sprintf(SQLStmt, "drop table blob_test"); rc = SQLExecDirect(StmtHandle, SQLStmt, SQL_NTS); sprintf(SQLStmt, "create table blob_test (an_int integer primary key, a_blob"); if (strstr(dsn, "DSN=psql")) strcat(SQLStmt, " bytea ) "); else if (strstr(dsn, "DSN=mysql")) strcat(SQLStmt, " blob ) "); else strcat(SQLStmt, " long raw ) "); rc = SQLExecDirect(StmtHandle, SQLStmt, SQL_NTS); //if(rc == SQL_SUCCESS) // VERBOSE("success: executed statement: %s \n", SQLStmt); // Define An INSERT SQL Statement That Contains A // Data-At-Execution Parameter strcpy((char *)SQLStmt, "INSERT INTO blob_test "); strcat((char *)SQLStmt, "(an_int, a_blob"); strcat((char *)SQLStmt, " ) VALUES "); strcat((char *)SQLStmt, "(1, ?)"); // Prepare The SQL Statement rc = SQLPrepare(StmtHandle, SQLStmt, SQL_NTS); // Bind The Parameter Marker In The SQL Statement To A // Local Application Variable - This Parameter Will Use // SQLParamData() And SQLPutData() To Send Data In Pieces // (Note: The Column Size Is 200 Characters) rc = SQLBindParameter(StmtHandle, 1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_CHAR, 200, 0, (SQLPOINTER) InputParam, CHUNKSIZE, &Indicator); // Execute The SQL Statement rc = SQLExecute(StmtHandle); // The Return Code SQL_NEED_DATA Should Be Returned, // Indicating That SQLParamData() And SQLPutData() Need // To Be Called assert(rc == SQL_NEED_DATA); rc = SendLongData(); assert(rc == SQL_SUCCESS); // Free The SQL Statement Handle if (StmtHandle != NULL) SQLFreeHandle(SQL_HANDLE_STMT, StmtHandle); // Disconnect From The Northwind Sample Database rc = SQLDisconnect(ConHandle); return rc; }
// Main Program int main (int argc, char **argv) { SQLCHAR *dsnName; SQLCHAR *user; SQLCHAR *password; SQLRETURN returnCode; bool testPassed = true; SQLCHAR InConnStr[MAX_CONNECT_STRING]; SQLCHAR OutConnStr[MAX_CONNECT_STRING]; SQLSMALLINT ConnStrLength; int c, errflag = 0; optarg = NULL; if (argc != 7) errflag++; while (!errflag && (c = getopt(argc, argv, ARGS)) != -1) switch (c) { case 'd': dsnName = (SQLCHAR*)optarg; break; case 'u': user = (SQLCHAR*)optarg; break; case 'p': password = (SQLCHAR*)optarg; break; default : errflag++; } if (errflag) { printf("Command line error.\n"); printf("Usage: %s [-d <datasource>] [-u <userid>] [-p <password>]\n", argv[0] ); return FALSE; } // Initialize handles to NULL henv = SQL_NULL_HANDLE; hstmt = SQL_NULL_HANDLE; hdbc = SQL_NULL_HANDLE; // Allocate Environment Handle returnCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv)",returnCode); // Set ODBC version to 3.0 returnCode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0)",returnCode,false); // Allocate Connection handle returnCode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc)", returnCode); //Connect to the database sprintf((char*)InConnStr,"DSN=%s;UID=%s;PWD=%s;%c",(char*)dsnName, (char*)user, (char*)password,'\0'); printf("Using Connect String: %s\n", InConnStr); returnCode = SQLDriverConnect(hdbc,hWnd,InConnStr,SQL_NTS,OutConnStr,sizeof(OutConnStr),&ConnStrLength,SQL_DRIVER_NOPROMPT); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLDriverConnect",returnCode); //Allocate Statement handle returnCode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt)", returnCode); //Free Statement handle returnCode = SQLFreeHandle(SQL_HANDLE_STMT, hstmt); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLFreeHandle(SQL_HANDLE_STMT, hstmt)", returnCode); hstmt = SQL_NULL_HANDLE; //Disconnect returnCode = SQLDisconnect(hdbc); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLDisconnect(hdbc)", returnCode); //Free Connection handle returnCode = SQLFreeHandle(SQL_HANDLE_DBC, hdbc); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLFreeHandle(SQL_HANDLE_DBC, hdbc)", returnCode); hdbc = SQL_NULL_HANDLE; //Free Environment handle returnCode = SQLFreeHandle(SQL_HANDLE_ENV, henv); if(returnCode != SQL_SUCCESS) LogDiagnostics("SQLFreeHandle(SQL_HANDLE_ENV, henv)", returnCode); henv = SQL_NULL_HANDLE; printf("\nConnect Test Passed...\n"); exit(EXIT_SUCCESS); }
int main() { SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; // Aloocate an environment handle ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env); checkrc(ret,__LINE__); //we need odbc3 support SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0); //ALLOCATE A Connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc); checkrc(ret,__LINE__); // connect to the DSN mydsn ret = SQLConnect (dbc, (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); if(SQL_SUCCEEDED(ret)) { printf("\nConnected to the Data Source..\n"); } else { printf("error in conenction\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 1; } //***************************************************** // TABLE CREATED ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt); checkrc(ret,__LINE__); SQLCHAR table[200]= "CREATE TABLE T1(F1 INT,F2 SMALLINT,F3 CHAR(30),F4 FLOAT,F5 FLOAT,F6 DATE,F7 TIME,F8 TIMESTAMP,F9 TINYINT,F10 BIGINT, PRIMARY KEY(F2));"; ret = SQLPrepare(stmt,table,SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("\nTABLE CREATED\n"); //*************************** FetchTest(env,dbc,stmt,"T1"); //************************************************** SQLCHAR drop[100]="DROP TABLE T1"; ret = SQLPrepare(stmt,drop,SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); if(ret!=SQL_SUCCESS && ret !=SQL_SUCCESS_WITH_INFO) { printf("Statement failed\n"); return 1; } printf("Tables dropped successfully\n"); ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt); checkrc(ret,__LINE__); ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 0; }
int test_fun_odbc_api_Oracle__DBPOOL() { SQLHENV henv; SQLHDBC hdbc; int nIndex=0; SQLRETURN retcode; try { /*Enable connection pooling .. this must be done before any ADO calls are made. Only needs to occur one time per process*/ retcode = SQLSetEnvAttr(0, SQL_ATTR_CONNECTION_POOLING, (SQLPOINTER) SQL_CP_ONE_PER_DRIVER, SQL_IS_INTEGER); if (!SQL_SUCCEEDED(retcode)) { printf("SQLSetEnvAttr/SQL_ATTR_CONNECTION_POOLING error\n"); return retcode; } } catch (std::exception& e) { int a = 0; } catch (...) { int a = 0; } retcode = SQLAllocHandle(SQL_HANDLE_ENV, NULL, &henv); if (!SQL_SUCCEEDED(retcode)) { printf("SQLAllocHandle error\n"); return retcode; } // Set the ODBC behavior version. retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,(SQLPOINTER) SQL_OV_ODBC2, SQL_IS_INTEGER); if (!SQL_SUCCEEDED(retcode)) { printf("SQLSetEnvAttr/SQL_ATTR_ODBC_VERSION error\n"); return retcode; } // Set the matching condition for using an existing // connection in the pool retcode = SQLSetEnvAttr(henv,SQL_ATTR_CP_MATCH,(SQLPOINTER)SQL_CP_RELAXED_MATCH, SQL_IS_INTEGER); if (!SQL_SUCCEEDED(retcode)) { printf("SQLSetEnvAttr/SQL_ATTR_CP_MATCH error\n"); return retcode; } while (nIndex < 10) { if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc))) printf("SQLAllocHandle error\n"); if (!SQL_SUCCEEDED(SQLConnect(hdbc, (unsigned char*)"Oracle12343DYN\0", SQL_NTS, (unsigned char*)"IT271350_5\0", SQL_NTS, (unsigned char*)"IT271350_5\0", SQL_NTS))) printf("SQLConnect error\n"); else printf("Connect successfully %d times\n", nIndex); //When the ODBC application calls SQLDisconnect the first time, the connection is saved to the pool. //Any subsequent SQLConnect/SQLDisconnect that matches the required condition will reuse the first connection. //the first time, the application calls SQLDisconenct, it will return //the connection to the //pool SQLDisconnect(hdbc); if (!SQL_SUCCEEDED(SQLFreeHandle(SQL_HANDLE_DBC, hdbc))) printf("SQLFreeHandle error\n"); nIndex++; } SQLFreeHandle(SQL_HANDLE_ENV, henv); return 0; }
int main() { int an_int; SQLUSMALLINT num_cols; float a_float; SQLCHAR buf1[MAX_LEN]; SQLCHAR buf2[MAX_LEN]; SQLUSMALLINT col; SQLSMALLINT col_len; SQLSMALLINT type; SQLUINTEGER sz; SQLSMALLINT scale; SQLSMALLINT can_null; GET_LOGIN_VARS(); VERBOSE("calling SQLAllocHandle(EnvHandle) \n"); rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvHandle); assert(rc == SQL_SUCCESS); assert(EnvHandle != (SQLHANDLE) NULL); rc = SQLSetEnvAttr(EnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER); assert(rc == SQL_SUCCESS); VERBOSE("calling SQLAllocHandle(ConHandle) \n"); rc = SQLAllocHandle(SQL_HANDLE_DBC, EnvHandle, &ConHandle); assert(ConHandle != (SQLHANDLE) NULL); assert(rc == SQL_SUCCESS); if (dsn[0]) rc = SQLDriverConnect(ConHandle, NULL, dsn, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); else rc = SQLConnect(ConHandle, twoTask, SQL_NTS, (SQLCHAR *) userName, SQL_NTS, (SQLCHAR *) pswd, SQL_NTS); assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO); VERBOSE("connected to database %s\n", twoTask); VERBOSE("allocing handle\n"); rc = SQLAllocStmt(ConHandle, &StmtHandle); assert(rc == SQL_SUCCESS); sprintf(SQLStmt, "select max(an_int) from some_types"); VERBOSE("executing %s\n", SQLStmt); rc = SQLExecDirect(StmtHandle, SQLStmt, SQL_NTS); assert(rc == SQL_SUCCESS); rc = SQLNumResultCols(StmtHandle, &num_cols); assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO); assert(num_cols == 1); for (col = 1; col <= num_cols; col++) { rc = SQLDescribeCol(StmtHandle, col, buf1, MAX_LEN, &col_len, &type, &sz, &scale, &can_null); assert(rc == SQL_SUCCESS); VERBOSE ("col=%d name:%s len=%d type=%d size=%d scale=%d nullable=%d\n", col, buf1, col_len, type, sz, scale, can_null); /* if(col==1)assert(type==SQL_INTEGER); if(col==2)assert(type==SQL_C_DOUBLE); if(col==3)assert(type==SQL_VARCHAR); */ rc = SQLColAttribute(StmtHandle, col, SQL_DESC_NAME, buf2, sizeof(buf2), &type, NULL); assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO); assert(strcmp(buf1, buf2) == 0); } rc = SQLBindCol(StmtHandle, 1, SQL_C_SLONG, &an_int, sizeof(an_int), NULL); assert(rc == SQL_SUCCESS); do { rc = SQLFetch(StmtHandle); VERBOSE("an_int=%d \n", an_int); } while (rc == SQL_SUCCESS); assert(rc == SQL_NO_DATA); assert(an_int > 0); rc = SQLDisconnect(ConHandle); assert(rc == SQL_SUCCESS); VERBOSE("disconnected from database\n"); VERBOSE("calling SQLFreeHandle(ConHandle) \n"); assert(ConHandle != (SQLHANDLE) NULL); rc = SQLFreeHandle(SQL_HANDLE_DBC, ConHandle); assert(rc == SQL_SUCCESS); VERBOSE("calling SQLFreeHandle(EnvHandle) \n"); assert(EnvHandle != (SQLHANDLE) NULL); rc = SQLFreeHandle(SQL_HANDLE_ENV, EnvHandle); assert(rc == SQL_SUCCESS); return (rc); }
/* Connect to the DBMS for database-resource/db-objects access. */ int cllConnectDbr(icatSessionStruct *icss, char *odbcEntryName) { RETCODE stat; RETCODE stat2; SQLCHAR buffer[SQL_MAX_MESSAGE_LENGTH + 1]; SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; SQLINTEGER sqlcode; SQLSMALLINT length; HDBC myHdbc; stat = SQLAllocConnect(icss->environPtr, &myHdbc); if (stat != SQL_SUCCESS) { rodsLog(LOG_ERROR, "cllConnect: SQLAllocConnect failed: %d, stat"); return (-1); } stat = SQLSetConnectOption(myHdbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF); if (stat != SQL_SUCCESS) { rodsLog(LOG_ERROR, "cllConnect: SQLSetConnectOption failed: %d", stat); return (-1); } stat = SQLConnect(myHdbc, (unsigned char *)odbcEntryName, SQL_NTS, (unsigned char *)icss->databaseUsername, SQL_NTS, (unsigned char *)icss->databasePassword, SQL_NTS); if (stat != SQL_SUCCESS) { rodsLog(LOG_ERROR, "cllConnect: SQLConnect failed: %d", stat); rodsLog(LOG_ERROR, "cllConnect: SQLConnect failed:odbcEntry=%s,user=%s,pass=%s\n", odbcEntryName,icss->databaseUsername, icss->databasePassword); while (SQLError(icss->environPtr,myHdbc , 0, sqlstate, &sqlcode, buffer, SQL_MAX_MESSAGE_LENGTH + 1, &length) == SQL_SUCCESS) { rodsLog(LOG_ERROR, "cllConnect: SQLSTATE: %s\n", sqlstate); rodsLog(LOG_ERROR, "cllConnect: Native Error Code: %ld\n", sqlcode); rodsLog(LOG_ERROR, "cllConnect: %s \n", buffer); } stat2 = SQLDisconnect(myHdbc); stat2 = SQLFreeConnect(myHdbc); return (-1); } icss->connectPtr=myHdbc; if (icss->databaseType == DB_TYPE_MYSQL) { /* MySQL must be running in ANSI mode (or at least in PIPES_AS_CONCAT mode) to be able to understand Postgres SQL. STRICT_TRANS_TABLES must be st too, otherwise inserting NULL into NOT NULL column does not produce error. */ cllExecSqlNoResult ( icss, "SET SESSION autocommit=0" ) ; cllExecSqlNoResult ( icss, "SET SESSION sql_mode='ANSI,STRICT_TRANS_TABLES'" ); } return(0); }
int test_fun_odbc_api_Oracle__dynDNS() { int nFunRes = 0; // Drop and re-create a Msorcl10.dll (version 1.0) data source. nFunRes = SQLConfigDataSource( NULL, ODBC_REMOVE_DSN, "Microsoft ODBC for Oracle", "DSN=Oracle12343DYN\0"); nFunRes = SQLConfigDataSource( NULL, ODBC_ADD_DSN, "Microsoft ODBC for Oracle", "Description=My Description Text\0" "Server=TRANSACT\0" "DSN=Oracle12343DYN\0" "PWD=IT271350_5\0" "UID=IT271350_5\0" ); SQLHENV m_hEnviroment; SQLHDBC m_hDatabaseConnection; SQLHSTMT m_hStatement; SQLRETURN retcode; /*Allocate environment handle */ retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnviroment); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { return nFunRes; } /* Set the ODBC version environment attribute */ retcode = SQLSetEnvAttr(m_hEnviroment, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* Allocate connection handle */ retcode = SQLAllocHandle(SQL_HANDLE_DBC, m_hEnviroment, &m_hDatabaseConnection); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* Set login timeout to 5 seconds. */ //SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, 5, 0); /* Connect to data source */ retcode = SQLConnect(m_hDatabaseConnection, (SQLCHAR*) "Oracle12343DYN", SQL_NTS, (SQLCHAR*) "IT271350_5", SQL_NTS, (SQLCHAR*) "IT271350_5", SQL_NTS); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* Allocate statement handle */ retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hDatabaseConnection, &m_hStatement); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } retcode = SQLExecDirect(m_hStatement,(SQLCHAR*)"select pkey from recipient_info", SQL_NTS); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* get return data Row count */ SQLINTEGER l_siIdCount = 0; retcode = SQLRowCount(m_hStatement, &l_siIdCount); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } while (true) { //fecth data use SQLFetch() return SQL_SUCCESS then no data retcode = SQLFetch(m_hStatement); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { break; } SQLINTEGER l_siID; SQLINTEGER l_siIDLength = 0; retcode = SQLGetData(m_hStatement, 1, SQL_C_ULONG, &l_siID, 0, &l_siIDLength); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { break; } }//while (true) /* Process data */ retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); nFunRes = SQLConfigDataSource( NULL, ODBC_REMOVE_DSN, "Microsoft ODBC for Oracle", "DSN=Oracle12343DYN\0"); return nFunRes; }
int main(int argc, char *argv[]) { SQLHENV henv; SQLHDBC hdbc; SQLHSTMT hstmt; SQLRETURN ret; SQLCHAR dbms_name[256], dbms_ver[256]; SQLSMALLINT columns; int table_cnt; // container *V = vector_container( custom_container(sizeof(table_info), NULL) ); container *V = vector_container( pair_container( string_container(), string_container() ) ); ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); if (!SQL_SUCCEEDED(ret)) { display_error(SQL_HANDLE_ENV, henv); exit(-1); } ret = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); if (!SQL_SUCCEEDED(ret)) { display_error(SQL_HANDLE_ENV, henv); SQLFreeHandle(SQL_HANDLE_ENV, henv); exit(-1); } ret = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); if (!SQL_SUCCEEDED(ret)) { display_error(SQL_HANDLE_ENV, henv); SQLFreeHandle(SQL_HANDLE_ENV, henv); exit(-1); } // FreeTDS krasjer på SQLDriverConnect! Derfor bruker vi SQLConnect istedet. ret = SQLConnect(hdbc, (SQLCHAR*) "adventure", SQL_NTS, (SQLCHAR*) "ax", SQL_NTS, (SQLCHAR*) "Ju13brz;", SQL_NTS); if (ret==SQL_SUCCESS_WITH_INFO) display_error(SQL_HANDLE_DBC, hdbc); if (!SQL_SUCCEEDED(ret)) { display_error(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_ENV, henv); exit(-1); } fprintf(stderr, "ODBC Crawler: Connected to '%s'!\n", "adventure"); SQLGetInfo(hdbc, SQL_DBMS_NAME, (SQLPOINTER)dbms_name, sizeof(dbms_name), NULL); SQLGetInfo(hdbc, SQL_DBMS_VER, (SQLPOINTER)dbms_ver, sizeof(dbms_ver), NULL); fprintf(stderr, "DBMS Name: %s\n", dbms_name); fprintf(stderr, "DBMS Version: %s\n", dbms_ver); STMT_CATCH( SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt) ); // Å spesifisere "TABLE" direkte fungerer ikke :\ (FreeTDS?) // Derfor er vi nødt til å sortere ut tabellene etterpå. STMT_CATCH( SQLTables(hstmt, NULL, 0, NULL, 0, NULL, 0, NULL, 0) ); STMT_CATCH( SQLNumResultCols(hstmt, &columns) ); while (SQL_SUCCEEDED(ret = SQLFetch(hstmt))) { char buf[3][256]; SQLINTEGER indicator; char *catalog, *schema, *table_name; ret = SQLGetData(hstmt, 4, SQL_C_CHAR, buf[0], sizeof(buf[0]), &indicator); if (SQL_SUCCEEDED(ret) && !strcmp(buf[0], "TABLE")) { ret = SQLGetData(hstmt, 1, SQL_C_CHAR, buf[0], sizeof(buf), &indicator); if (SQL_SUCCEEDED(ret) && indicator!=SQL_NULL_DATA) catalog = buf[0]; else catalog = NULL; ret = SQLGetData(hstmt, 2, SQL_C_CHAR, buf[1], sizeof(buf), &indicator); if (SQL_SUCCEEDED(ret) && indicator!=SQL_NULL_DATA) schema = buf[1]; else schema = NULL; ret = SQLGetData(hstmt, 3, SQL_C_CHAR, buf[2], sizeof(buf), &indicator); if (SQL_SUCCEEDED(ret) && indicator!=SQL_NULL_DATA) table_name = buf[2]; else table_name = NULL; vector_pushback(V, schema, table_name); } } for (table_cnt=0; table_cnt<vector_size(V); table_cnt++) { char query[1024]; char *schema = (char*)pair(vector_get(V,table_cnt)).first.ptr; char *table_name = (char*)pair(vector_get(V,table_cnt)).second.ptr; printf("%s.%s:\n", schema, table_name); STMT_CATCH( SQLFreeHandle(SQL_HANDLE_STMT, hstmt) ); STMT_CATCH( SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt) ); // STMT_CATCH( SQLColumns(hstmt, NULL, 0, schema, SQL_NTS, table_name, SQL_NTS, NULL, 0) ); // STMT_CATCH( SQLExecDirect(hstmt, "select FirstName, LastName from Person.Contact;", SQL_NTS) ); snprintf(query, 1023, "SELECT * FROM %s.%s;", schema, table_name); // printf("%s\n", query); STMT_CATCH( SQLExecDirect(hstmt, (SQLCHAR*)query, SQL_NTS) ); STMT_CATCH( SQLNumResultCols(hstmt, &columns) ); while (SQL_SUCCEEDED(ret = SQLFetch(hstmt))) { char buf[512]; SQLUSMALLINT i; SQLINTEGER indicator; for (i=1; i<=columns; i++) { ret = SQLGetData(hstmt, i, SQL_C_CHAR, buf, sizeof(buf), &indicator); if (SQL_SUCCEEDED(ret)) { if (indicator==SQL_NULL_DATA) strcpy(buf, "NULL"); } printf("| %s ", buf); } printf("|\n"); } } destroy(V); quit: SQLFreeHandle(SQL_HANDLE_STMT, hstmt); SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_ENV, henv); }
OdbcHandle odbcConnect(const char* dbname, const char* servername, const char* username, const char* driver, const char* password) { OdbcHandle handle = new OdbcControlStruct; if (handle) { if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &handle->mEnvironmentHandle))) { OsSysLog::add(FAC_ODBC, PRI_ERR, "odbcConnect: Failed to allocate " "environment handle"); delete handle; handle = NULL; } else { SQLSetEnvAttr(handle->mEnvironmentHandle, SQL_ATTR_ODBC_VERSION, (void*) SQL_OV_ODBC3, 0); if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC, handle->mEnvironmentHandle, &handle->mConnectionHandle))) { OsSysLog::add(FAC_ODBC, PRI_ERR, "odbcConnect: Failed to allocate " "connection handle"); SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle); delete handle; handle = NULL; } else { // Connect - contruct connection string UtlString connectionString; char temp[128]; if (dbname) { sprintf(temp, "DATABASE=%s;", dbname); connectionString.append(temp); } if (servername) { sprintf(temp, "SERVER=%s;", servername); connectionString.append(temp); } if (username) { sprintf(temp, "UID=%s;", username); connectionString.append(temp); } if (password) { sprintf(temp, "PWD=%s;", password); connectionString.append(temp); } else { connectionString.append("PWD=;"); } if (driver) { sprintf(temp, "DRIVER=%s;", driver); connectionString.append(temp); } // Connect in read/write mode connectionString.append("READONLY=0;"); SQLRETURN sqlRet = SQLDriverConnect(handle->mConnectionHandle, NULL, (SQLCHAR*)connectionString.data(), SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (!SQL_SUCCEEDED(sqlRet)) { OsSysLog::add(FAC_ODBC, PRI_ERR, "odbcConnect: Failed to connect %s, error code %d", connectionString.data(), sqlRet); SQLFreeHandle(SQL_HANDLE_DBC, handle->mConnectionHandle); SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle); delete handle; handle = NULL; } else { // Connected to database, now alloc a statement handle if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_STMT, handle->mConnectionHandle, &handle->mStatementHandle))) { OsSysLog::add(FAC_ODBC, PRI_ERR, "odbcConnect: Failed to allocate " "statement handle"); // Disconnect from database SQLDisconnect(handle->mConnectionHandle); // Free resources SQLFreeHandle(SQL_HANDLE_DBC, handle->mConnectionHandle); SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle); delete handle; handle = NULL; } else { OsSysLog::add(FAC_ODBC, PRI_DEBUG, "odbcConnect: Connected to database " "%s, OdbcHandle %p", connectionString.data(), handle); } } } } } else { OsSysLog::add(FAC_ODBC, PRI_ERR, "odbcConnect: Couldn't create OdbcHandle"); } return handle; }
//int __cdecl wmain(int argc, _In_reads_(argc) WCHAR **argv) //int __cdecl wmain(int argc, WCHAR **argv) int __cdecl wmain2(int argc, WCHAR **argv) { SQLHENV hEnv = NULL; SQLHDBC hDbc = NULL; SQLHSTMT hStmt = NULL; WCHAR* pwszConnStr; WCHAR wszInput[SQL_QUERY_SIZE]; // Allocate an environment if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv) == SQL_ERROR) { fwprintf(stderr, L"Unable to allocate an environment handle\n"); exit(-1); } // Register this as an application that expects 3.x behavior, // you must register something if you use AllocHandle TRYODBC(hEnv, SQL_HANDLE_ENV, SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)); // Allocate a connection TRYODBC(hEnv, SQL_HANDLE_ENV, SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc)); if (argc > 1) { pwszConnStr = *++argv; } else { pwszConnStr = L""; } // Connect to the driver. Use the connection string if supplied // on the input, otherwise let the driver manager prompt for input. TRYODBC(hDbc, SQL_HANDLE_DBC, SQLDriverConnect(hDbc, GetDesktopWindow(), pwszConnStr, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE)); fwprintf(stderr, L"Connected!\n"); TRYODBC(hDbc, SQL_HANDLE_DBC, SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt)); wprintf(L"Enter SQL commands, type (control)Z to exit\nSQL COMMAND>"); // Loop to get input and execute queries while(_fgetts(wszInput, SQL_QUERY_SIZE-1, stdin)) { RETCODE RetCode; SQLSMALLINT sNumResults; // Execute the query if (!(*wszInput)) { wprintf(L"SQL COMMAND>"); continue; } RetCode = SQLExecDirect(hStmt,wszInput, SQL_NTS); switch(RetCode) { case SQL_SUCCESS_WITH_INFO: { HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode); // fall through } case SQL_SUCCESS: { // If this is a row-returning query, display // results TRYODBC(hStmt, SQL_HANDLE_STMT, SQLNumResultCols(hStmt,&sNumResults)); if (sNumResults > 0) { DisplayResults(hStmt,sNumResults); } else { SQLLEN cRowCount; TRYODBC(hStmt, SQL_HANDLE_STMT, SQLRowCount(hStmt,&cRowCount)); if (cRowCount >= 0) { wprintf(L"%Id %s affected\n", cRowCount, cRowCount == 1 ? L"row" : L"rows"); } } break; } case SQL_ERROR: { HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode); break; } default: fwprintf(stderr, L"Unexpected return code %hd!\n", RetCode); } TRYODBC(hStmt, SQL_HANDLE_STMT, SQLFreeStmt(hStmt, SQL_CLOSE)); wprintf(L"SQL COMMAND>"); } Exit: // Free ODBC handles and exit if (hStmt) { SQLFreeHandle(SQL_HANDLE_STMT, hStmt); } if (hDbc) { SQLDisconnect(hDbc); SQLFreeHandle(SQL_HANDLE_DBC, hDbc); } if (hEnv) { SQLFreeHandle(SQL_HANDLE_ENV, hEnv); } wprintf(L"\nDisconnected."); return 0; }
int main() { SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; //Allocate an environment handle ret = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env); checkrc(ret,__LINE__); //we need ODBC3 support SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0); //Allocate a Connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc); checkrc(ret,__LINE__); //connect to Data source ret = SQLConnect (dbc, (SQLCHAR *) "test", (SQLSMALLINT) strlen ("test"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); /* //connect using unixODBC Driver Manager ret = SQLDriverConnect(dbc, NULL, (SQLCHAR*) "DSN=mycsql;USER=root;PASSWORD=manager;", SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_NOPROMPT); */ if(SQL_SUCCEEDED(ret)) { printf("Connected to CSQL\n"); } else { printf("error in connection\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 2; } // Allocation of statement handle for DDL nad DML Operation ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt); checkrc(ret,__LINE__); // create table 'T1' with two fields, F1 INTEGER AND F2 CHAR. SQLCHAR table[200]= "CREATE TABLE T1(F1 INT,F2 CHAR(20))"; ret = SQLPrepare(stmt,table,SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("Table T1 created\n"); //Insert 10 Tuples into the table 'T1' int id=10; char name[20]="THIRU"; char names[10][20]={"Gopal", "Aruna", "Kanchana", "Vijay", "Ganga", "XieLiang", "Rajesh", "Steve", "Veda", "Jitendra" }; SQLINTEGER slen = SQL_NTS; ret = SQLPrepare(stmt,(unsigned char*)"INSERT INTO T1 VALUES(?,?);",SQL_NTS); checkrc(ret,__LINE__); ret = SQLBindParameter(stmt,1,SQL_PARAM_INPUT,SQL_C_SLONG,SQL_INTEGER,0,0,&id,0,NULL); checkrc(ret,__LINE__); ret = SQLBindParameter(stmt,2,SQL_PARAM_INPUT,SQL_C_CHAR,SQL_CHAR,196,0,(void*)name,0,&slen); checkrc(ret,__LINE__); int i,count=0; for(i=0;i<10;i++) { id++; strcpy(name,names[i]); ret = SQLExecute(stmt); checkrc(ret,__LINE__); ret = SQLTransact(env,dbc,SQL_COMMIT); checkrc(ret,__LINE__); count++; } printf("%d Rows inserted\n",count); //Fetch rows from the table 'T1' int id1=10; ret = SQLPrepare(stmt,(unsigned char*)"SELECT * FROM T1;",SQL_NTS); checkrc(ret,__LINE__); ret = SQLBindCol(stmt,1,SQL_C_SLONG,&id1,0,NULL); checkrc(ret,__LINE__); ret = SQLBindCol(stmt,2,SQL_C_CHAR,name,sizeof(name),NULL); checkrc(ret,__LINE__); count=0; ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("Fetching starts on table T1 :\n"); while(SQL_SUCCEEDED(ret=SQLFetch(stmt))) { printf("F1:%d\tF2:%s\n",id1,name); count++; } ret = SQLCloseCursor(stmt); checkrc(ret,__LINE__); ret = SQLTransact(env,dbc,SQL_COMMIT); checkrc(ret,__LINE__); printf("%d rows fetched\n",count); //Delete all the rows from the table 'T1' ret = SQLPrepare(stmt,(unsigned char*)"DELETE FROM T1 WHERE F1=?;",SQL_NTS); checkrc(ret,__LINE__); ret = SQLBindParameter(stmt,1,SQL_PARAM_INPUT,SQL_C_SLONG,SQL_INTEGER,0,0,&id1,0,NULL); checkrc(ret,__LINE__); count=0; for(i=0;i<10;i++) { id++; ret = SQLExecute(stmt); checkrc(ret,__LINE__); count++; } ret = SQLTransact(env,dbc,SQL_COMMIT); checkrc(ret,__LINE__); printf("%d Rows deleted\n",count); // drop the table 'T1' SQLCHAR drop[50]="DROP TABLE T1"; ret = SQLPrepare(stmt,drop,SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("Table T1 dropped\n"); //Free the statement handle ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt); checkrc(ret,__LINE__); //Disconnect from the Data source ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); printf("Disconnected from CSQL\n"); //Free the connection handle ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); //Free the environment handle ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 0; }
int main() { SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; // Aloocate an environment handle ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env); checkrc(ret,__LINE__); //we need odbc3 support SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0); //ALLOCATE A Connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc); checkrc(ret,__LINE__); // connect to the DSN mydsn ret = SQLConnect (dbc, (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); if(SQL_SUCCEEDED(ret)) { printf("\nConnected to the Data Source..\n"); } else { printf("error in connection\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 1; } //****************************************************************** // TABLE CREATED ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt); checkrc(ret,__LINE__); SQLCHAR table[200]= "CREATE TABLE T1(F1 INT,F2 char(30))"; ret = SQLPrepare(stmt,table,SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("\nTABLE CREATED\n"); //**************************************************************** // INSERT FUNCTION InsertTest(env,dbc,stmt); //***************************************************************** // DELETE FROM T1; printf("delete from T1 where F1=10\n"); SQLCHAR delete1[50]="DELETE FROM T1 WHERE F1=10;"; ret = SQLPrepare(stmt,delete1,SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); SQLINTEGER nor; ret = SQLRowCount(stmt,&nor); printf("sqlrowcount() returns=%d\n",nor); // nor should return 1. if(nor!=1)return 1; ret = SQLFreeStmt(stmt,SQL_RESET_PARAMS); checkrc(ret,__LINE__); //************************************************ printf("\ndelete from T1 where F1 > 900\n"); ret = SQLPrepare(stmt,(unsigned char*)"DELETE FROM T1 WHERE F1 > 900",SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); SQLINTEGER nor1; ret = SQLRowCount(stmt,&nor1); printf("sqlrowcount() returns=%d\n",nor1); if(nor1!=100)return 1; ret = SQLFreeStmt(stmt,SQL_RESET_PARAMS); checkrc(ret,__LINE__); //************************************************************* printf("\ninsert into T1 values(1001,'1000')\n"); ret = SQLPrepare(stmt,(unsigned char*)"INSERT INTO T1 VALUES(1001,'1000')",SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); SQLINTEGER nor2; ret = SQLRowCount(stmt,&nor2); checkrc(ret,__LINE__); printf("sqlrowcount() returns=%d\n",nor2); if(nor2!=1)return 1; ret = SQLFreeStmt(stmt,SQL_RESET_PARAMS); //***************************************************** printf("\nUPDATE T1 SET F2='THOUSAND' WHERE F1<10\n"); ret = SQLPrepare(stmt,(unsigned char*)"UPDATE T1 SET F2='THOUSAND' WHERE F1<10",SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); SQLINTEGER nor3; ret = SQLRowCount(stmt,&nor3); checkrc(ret,__LINE__); printf("sqlrowcount() returns=%d\n",nor3); if(nor3!=9)return 1; /*ret = SQLFreeStmt(stmt,SQL_RESET_PARAMS); checkrc(ret,__LINE__);*/ //*********************************************** //FetchTest(env,dbc,stmt); //**************************************************************** //drop the table ret = SQLPrepare(stmt,(unsigned char*)"drop table T1;",SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("Table 'T1' dropped\n"); ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt); checkrc(ret,__LINE__); ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 0; }
/* * Class: org_jboss_odbc_OdbcClient * Method: disconnect * Signature: ()V */ JNIEXPORT void JNICALL Java_org_jboss_odbc_OdbcClient_disconnect(JNIEnv *jnienv, jobject obj) { int h = getStaticHandle(jnienv, obj); SQLDisconnect(dbc[h]); SQLFreeHandle(SQL_HANDLE_DBC, dbc[h]); }
int main() { SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; // Aloocate an environment handle ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env); checkrc(ret,__LINE__); //we need odbc3 support SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0); //ALLOCATE A Connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc); checkrc(ret,__LINE__); // connect to the DSN mydsn ret = SQLConnect (dbc, (SQLCHAR *) "DSN=mycsql;MODE=GATEWAY;SERVER=localhost;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=GATEWAY;SERVER=localhost;PORT=5678;"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); if(SQL_SUCCEEDED(ret)) { printf("\nConnected to the Data Source successfully..\n"); } else { printf("error in connection\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 1; } //****************************************************************** // TABLE CREATED ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt); checkrc(ret,__LINE__); SQLCHAR table[200]= "CREATE TABLE T1(F1 INT,F2 INT)"; ret = SQLPrepare(stmt,table,SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("\nTABLE CREATED\n"); //**************************************************************** // insert tuple into table ret = SQLPrepare(stmt,(unsigned char*)"INSERT INTO T1 VALUES(100,200)",SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); //***************************************************************** // FETCHING ROWS FROM TABLE int f1=1; int f2=2; ret = SQLPrepare(stmt,(unsigned char*)"SELECT * FROM T1",SQL_NTS); checkrc(ret,__LINE__); ret = SQLBindCol(stmt,1,SQL_C_LONG,&f1,0,NULL); checkrc(ret,__LINE__); ret = SQLBindCol(stmt,2,SQL_C_LONG,&f2,0,NULL); checkrc(ret,__LINE__); int j,count=0; ret = SQLExecute(stmt); checkrc(ret,__LINE__); //close the connection ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); // after closing call fetch. int rettype; while(SQL_SUCCEEDED(ret =SQLFetch(stmt))) { if(ret ) printf("After disconnect, Fetch failed\n"); else count++; } rettype=ret; printf("Number of rows are fetched=%d\n",count); // ***************************************************************** // again connect for drop the table ret = SQLConnect (dbc, (SQLCHAR *) "DSN=mycsql;MODE=GATEWAY;SERVER=localhost;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=GATEWAY;SERVER=localhost;PORT=5678;"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); if(SQL_SUCCEEDED(ret)) { printf("\nagain Connected to the Data Source successfully..\n"); } else { printf("error in connection\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 1; } ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt); checkrc(ret,__LINE__); ret = SQLPrepare(stmt,(unsigned char*)"drop table T1;",SQL_NTS); checkrc(ret,__LINE__); ret = SQLExecute(stmt); checkrc(ret,__LINE__); printf("Table dropped\n"); //**************************************************************** ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt); checkrc(ret,__LINE__); ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); if(rettype == 0) return 1; printf("After closing the connection, fetch does not work\n"); return 0; }
/* --------------------------------------------------------- TestSQLBrowseConnect --------------------------------------------------------- */ PassFail TestSQLBrowseConnect(TestInfo *pTestInfo) { TEST_DECLARE; RETCODE returncode; SQLHANDLE henv = (SQLHANDLE)NULL, henv1[NUM_ENV_HND]; SQLHANDLE hdbc = (SQLHANDLE)NULL, badhdbc, hdbc1[NUM_ENV_HND * NUM_CONN_HND]; SQLHANDLE hstmt = (SQLHANDLE)NULL; SQLCHAR szConnStrIn[BRWS_LEN], szConnStrOut[BRWS_LEN]; char connstr[BRWS_LEN]; char tstConnStr[BRWS_LEN]; SWORD cbConnStrOut; int i = 0, j = 0; LogMsg(LINEBEFORE+SHORTTIMESTAMP,"Begin testing API => SQLBrowseConnect | SQLBrowseConnect | browse.c\n"); TEST_INIT; //========================================================================================== TESTCASE_BEGIN("Test Negative Functionality of SQLBrowseConnect: Invalid CONN handle pointer\n"); badhdbc = (SQLHANDLE)NULL; //strcpy(connstr,""); //strcat(connstr,"DSN="); //strcat(connstr,pTestInfo->DataSource); //strcat(connstr,";"); //strcat(connstr,"UID="); //strcat(connstr,pTestInfo->UserID); //strcat(connstr,";"); //strcat(connstr,"PWD="); //strcat(connstr,pTestInfo->Password); //strcat(connstr,";"); strcpy(connstr,""); sprintf(connstr, "DSN=%s;UID=%s;PWD=%s;",pTestInfo->DataSource,pTestInfo->UserID,pTestInfo->Password); strcpy((char*)szConnStrIn,""); strcat((char*)szConnStrIn,connstr); returncode = SQLBrowseConnect(badhdbc, szConnStrIn, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_INVALID_HANDLE,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } SQLDisconnect(badhdbc); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Negative Functionality of SQLBrowseConnect: NULL szConnStrIn\n"); returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc, NULL, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_ERROR,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Negative Functionality of SQLBrowseConnect: Invalid szConnStrIn length\n"); returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc, szConnStrIn, (SWORD)(strlen(pTestInfo->DataSource)+4), szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_NEED_DATA,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Negative Functionality of SQLBrowseConnect: zero length\n"); returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc, szConnStrIn,0, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_ERROR,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Negative Functionality of SQLBrowseConnect: Invalid DSN\n"); returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } strcpy(connstr,""); strcat(connstr,"DSN="); strcat(connstr,"baddsn"); strcat(connstr,";"); strcat(connstr,"UID="); strcat(connstr,pTestInfo->UserID); strcat(connstr,";"); strcat(connstr,"PWD="); strcat(connstr,pTestInfo->Password); strcat(connstr,";"); returncode = SQLBrowseConnect(hdbc,(SQLCHAR*)connstr,SQL_NTS,szConnStrOut,BRWS_LEN,&cbConnStrOut); if(!CHECKRC(SQL_ERROR,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Positive Functionality of SQLBrowseConnect with SQL_NTS\n"); returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc,szConnStrIn,SQL_NTS,szConnStrOut,BRWS_LEN,&cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBrowseConnect")){ TEST_FAILED; printf("\nIn string = %s\n",szConnStrIn); printf("Out string = %s\n",szConnStrOut); LogAllErrors(henv,hdbc,hstmt); } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Positive Functionality of SQLBrowseConnect with strlen\n"); returncode = SQLAllocEnv(&henv); // Environment handle if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); // Connection handle if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc,szConnStrIn,(SWORD)strlen((char*)szConnStrIn),szConnStrOut,BRWS_LEN,&cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Positive Functionality of SQLBrowseConnect to check need data\n"); returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ TEST_FAILED; TEST_RETURN; } sprintf(tstConnStr,"DSN=%s;",pTestInfo->DataSource); //printf("\nIn string = %s\n",tstConnStr); returncode = SQLBrowseConnect(hdbc, (SQLCHAR*)tstConnStr, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_NEED_DATA,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } strcat(tstConnStr,"UID="); strcat(tstConnStr,pTestInfo->UserID); strcat(tstConnStr,";"); //printf("\nIn string = %s\n",tstConnStr); returncode = SQLBrowseConnect(hdbc, (SQLCHAR*)tstConnStr, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if((returncode != SQL_NEED_DATA) && (returncode != SQL_SUCCESS)){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } if(returncode == SQL_NEED_DATA) { strcat(tstConnStr,"PWD="); strcat(tstConnStr,pTestInfo->Password); strcat(tstConnStr,";"); //printf("\nIn string = %s\n",tstConnStr); returncode = SQLBrowseConnect(hdbc, (SQLCHAR*)tstConnStr, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBrowseConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Positive Functionality of SQLBrowseConnect, SQLDisconnect then SQLBrowseConnect.\n"); for (i = 0; i < 3; i++) { returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")) { TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc, szConnStrIn, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } switch (i) { case 0: returncode = SQLDisconnect(hdbc); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } returncode = SQLBrowseConnect(hdbc, szConnStrIn, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } break; case 1: returncode = SQLDisconnect(hdbc); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } returncode = SQLFreeConnect(hdbc); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc, szConnStrIn, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } break; case 2: returncode = SQLDisconnect(hdbc); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } returncode = SQLFreeConnect(hdbc); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } returncode = SQLFreeEnv(henv); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } returncode = SQLAllocEnv(&henv); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")) { TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect(henv, &hdbc); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc, szConnStrIn, SQL_NTS, szConnStrOut, BRWS_LEN, &cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } break; default: // End break; } SQLDisconnect(hdbc); SQLFreeConnect(hdbc); SQLFreeEnv(henv); } TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Positive Functionality of SQLBrowseConnect with different connection handles\n"); returncode = SQLAllocEnv(&henv); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")){ TEST_FAILED; TEST_RETURN; } for (i = 0; i < NUM_CONN_HND; i++){ returncode = SQLAllocConnect(henv, &hdbc1[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")){ LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc1[i],szConnStrIn,SQL_NTS,szConnStrOut,BRWS_LEN,&cbConnStrOut); //printf("\n\nret=%d i=%d %s\n%s\n\n", returncode, i, szConnStrIn, szConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBrowseConnect")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt); } } for (i = 0; i < NUM_CONN_HND; i++){ //printf("%d %d\n", i, NUM_CONN_HND); SQLDisconnect(hdbc1[i]); SQLFreeConnect(hdbc1[i]); } SQLFreeEnv(henv); TESTCASE_END; //========================================================================================== TESTCASE_BEGIN("Test Positive Functionality of SQLBrowseConnect with different env & conn handles\n"); for (j = 0; j < NUM_ENV_HND / 5; j++) { returncode = SQLAllocEnv(&henv1[j]); /* Environment handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")) { TEST_FAILED; TEST_RETURN; } for (i = 0; i < NUM_CONN_HND / 2; i++) { returncode = SQLAllocConnect(henv1[j], &hdbc1[j * NUM_CONN_HND + i]); /* Connection handle */ if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")) { LogAllErrors(henv1[j],hdbc1[j * NUM_CONN_HND + i],hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBrowseConnect(hdbc1[j * NUM_CONN_HND + i],szConnStrIn,SQL_NTS,szConnStrOut,BRWS_LEN,&cbConnStrOut); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBrowseConnect")) { TEST_FAILED; LogAllErrors(henv1[j],hdbc1[j * NUM_CONN_HND + i],hstmt); } } } for (j = 0; j < NUM_ENV_HND / 5; j++) { for (i = 0; i < NUM_CONN_HND / 2; i++) { //printf("%d %d %d \n", j, i, NUM_CONN_HND); SQLDisconnect(hdbc1[j * NUM_CONN_HND + i]); SQLFreeConnect(hdbc1[j * NUM_CONN_HND + i]); } SQLFreeEnv(henv1[j]); } TESTCASE_END; LogMsg(SHORTTIMESTAMP+LINEAFTER,"End of testing API ===> SQLBrowseConnect \n"); //========================================================================================== TEST_RETURN; }
/* connect to two databases using a Type 1 connection */ int TwoConnType1Use(SQLHANDLE henv, char dbAlias1[], char dbAlias2[], char user1[], char pswd1[], char user2[], char pswd2[]) { SQLRETURN cliRC = SQL_SUCCESS; int rc = 0; SQLHANDLE hdbc1, hdbc2; /* connection handles */ SQLHANDLE hstmt1, hstmt2, hstmt3, hstmt4; /* statement handles */ printf("\n-----------------------------------------------------------"); printf("\nUSE THE CLI FUNCTIONS\n"); printf(" SQLAllocHandle\n"); printf(" SQLSetConnectAttr\n"); printf(" SQLConnect\n"); printf(" SQLExecDirect\n"); printf(" SQLEndTran\n"); printf(" SQLDisconnect\n"); printf(" SQLFreeHandle\n"); printf("TO PERFORM TRANSACTIONS ON TWO CONNECTIONS\n"); printf("USING TYPE 1 CONNECT:\n"); /* allocate the first database connection handle */ cliRC = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc1); DBC_HANDLE_CHECK(hdbc1, cliRC); /* allocate the second database connection handle */ cliRC = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc2); DBC_HANDLE_CHECK(hdbc2, cliRC); /* set TYPE 1 CONNECT for the both connections */ printf("\n Set TYPE 1 CONNECT for both connections.\n"); cliRC = SQLSetConnectAttr(hdbc1, SQL_ATTR_CONNECTTYPE, (SQLPOINTER)SQL_CONCURRENT_TRANS, SQL_NTS); DBC_HANDLE_CHECK(hdbc1, cliRC); cliRC = SQLSetConnectAttr(hdbc2, SQL_ATTR_CONNECTTYPE, (SQLPOINTER)SQL_CONCURRENT_TRANS, SQL_NTS); DBC_HANDLE_CHECK(hdbc2, cliRC); printf("\n Connect to '%s' database.\n", dbAlias1); /* connect to the first database */ cliRC = SQLConnect(hdbc1, (SQLCHAR *)dbAlias1, SQL_NTS, (SQLCHAR *)user1, SQL_NTS, (SQLCHAR *)pswd1, SQL_NTS); DBC_HANDLE_CHECK(hdbc1, cliRC); printf(" Connect to '%s' database.\n", dbAlias2); /* connect to the second database */ cliRC = SQLConnect(hdbc2, (SQLCHAR *)dbAlias2, SQL_NTS, (SQLCHAR *)user2, SQL_NTS, (SQLCHAR *)pswd2, SQL_NTS); DBC_HANDLE_CHECK(hdbc2, cliRC); /********* Start using the connections ************************/ /* set AUTOCOMMIT OFF for the both connections */ printf("\n Enable transactions for connection 1.\n"); cliRC = SQLSetConnectAttr(hdbc1, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS); DBC_HANDLE_CHECK(hdbc1, cliRC); printf(" Enable transactions for connection 2.\n"); cliRC = SQLSetConnectAttr(hdbc2, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS); DBC_HANDLE_CHECK(hdbc2, cliRC); /* allocate the handle for statement 1 */ cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt1); DBC_HANDLE_CHECK(hdbc1, cliRC); /* allocate the handle for statement 2 */ cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt2); DBC_HANDLE_CHECK(hdbc1, cliRC); /* allocate the handle for statement 3 */ cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc2, &hstmt3); DBC_HANDLE_CHECK(hdbc2, cliRC); /* allocate the handle for statement 4 */ cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc2, &hstmt4); DBC_HANDLE_CHECK(hdbc2, cliRC); printf("\n Perform statements on both connections.\n"); printf("\n executing statement 1 on connection 1...\n"); /* execute statement 1 on connection 1 */ cliRC = SQLExecDirect(hstmt1, (SQLCHAR *)"CREATE TABLE table1(col1 INTEGER)", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt1, henv, cliRC); printf(" executing statement 2 on connection 1...\n"); /* execute statement 2 on connection 1 */ cliRC = SQLExecDirect(hstmt2, (SQLCHAR *)"DROP TABLE table1", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt2, henv, cliRC); printf(" commit the transaction on connection 1\n"); /* end the transaction */ cliRC = SQLEndTran(SQL_HANDLE_DBC, hdbc1, SQL_COMMIT); DBC_HANDLE_CHECK(hdbc1, cliRC); printf("\n executing statement 3 on connection 2...\n"); /* execute statement 3 on connection 2 */ cliRC = SQLExecDirect(hstmt3, (SQLCHAR *)"CREATE TABLE table1(col1 INTEGER)", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt3, henv, cliRC); printf(" executing statement 4 on connection 2...\n"); /* execute statement 4 on connection 2 */ cliRC = SQLExecDirect(hstmt4, (SQLCHAR *)"DROP TABLE table1", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt4, henv, cliRC); printf(" commit the transaction on connection 2\n"); /* end the transaction */ cliRC = SQLEndTran(SQL_HANDLE_DBC, hdbc2, SQL_COMMIT); DBC_HANDLE_CHECK(hdbc2, cliRC); /* free the handle for statement 1 */ cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt1); MC_STMT_HANDLE_CHECK(hstmt1, henv, cliRC); /* free the handle for statement 2 */ cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt2); MC_STMT_HANDLE_CHECK(hstmt2, henv, cliRC); /* free the handle for statement 3 */ cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt3); MC_STMT_HANDLE_CHECK(hstmt3, henv, cliRC); /* free the handle for statement 4 */ cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt4); MC_STMT_HANDLE_CHECK(hstmt4, henv, cliRC); /********* Stop using the connections *************************/ printf("\n Disconnect from '%s' database.\n", dbAlias1); /* disconnect from the first database */ cliRC = SQLDisconnect(hdbc1); DBC_HANDLE_CHECK(hdbc1, cliRC); printf(" Disconnect from '%s' database.\n", dbAlias2); /* disconnect from the second database */ cliRC = SQLDisconnect(hdbc2); DBC_HANDLE_CHECK(hdbc2, cliRC); /* free the handle for connection 1 */ cliRC = SQLFreeHandle(SQL_HANDLE_DBC, hdbc1); DBC_HANDLE_CHECK(hdbc1, cliRC); /* free the handle for connection 2 */ cliRC = SQLFreeHandle(SQL_HANDLE_DBC, hdbc2); DBC_HANDLE_CHECK(hdbc2, cliRC); return 0; } /* TwoConnType1Use */
/* --------------------------------------------------------- TestSQLTransact --------------------------------------------------------- */ PassFail TestSQLTransact(TestInfo *pTestInfo) { TEST_DECLARE; RETCODE returncode; char Heading[MAX_STRING_SIZE]; SQLHANDLE henv; SQLHANDLE hdbc; SQLHANDLE hstmt; CHAR *ExecDirStr[6]; UWORD fType[] = { SQL_ROLLBACK,SQL_COMMIT }; CHAR *TypeDesc[] = { "SQL_ROLLBACK","SQL_COMMIT" }; CHAR *Output; SQLLEN OutputLen; struct { SWORD ExeRes[2]; SWORD FetchRes[2]; CHAR *DataRes[2]; } CheckRes[] = { {SQL_ERROR,SQL_SUCCESS,SQL_NO_DATA_FOUND,SQL_NO_DATA_FOUND,"",""}, {SQL_SUCCESS,SQL_SUCCESS,SQL_NO_DATA_FOUND,SQL_SUCCESS,"","--"}, {SQL_SUCCESS,SQL_SUCCESS,SQL_SUCCESS,SQL_SUCCESS,"--","--"}, {SQL_SUCCESS,SQL_SUCCESS,SQL_SUCCESS,SQL_NO_DATA_FOUND,"--",""}, {SQL_SUCCESS,SQL_ERROR,SQL_NO_DATA_FOUND,SQL_NO_DATA_FOUND,"",""} }; int i = 0, j = 0, iend = 5, jend = 1, commit_on_off = 0; //=========================================================================================================== var_list_t *var_list; var_list = load_api_vars("SQLTransact", charset_file); if (var_list == NULL) return FAILED; ExecDirStr[0] = var_mapping("SQLTransact_ExecDirStr_0", var_list); ExecDirStr[1] = var_mapping("SQLTransact_ExecDirStr_1", var_list); ExecDirStr[2] = var_mapping("SQLTransact_ExecDirStr_2", var_list); ExecDirStr[3] = var_mapping("SQLTransact_ExecDirStr_3", var_list); ExecDirStr[4] = var_mapping("SQLTransact_ExecDirStr_4", var_list); ExecDirStr[5] = var_mapping("SQLTransact_ExecDirStr_5", var_list); CheckRes[1].DataRes[1] = var_mapping("SQLTransact_Insert", var_list); CheckRes[2].DataRes[0] = var_mapping("SQLTransact_Insert", var_list); CheckRes[2].DataRes[1] = var_mapping("SQLTransact_Update", var_list); CheckRes[3].DataRes[0] = var_mapping("SQLTransact_Update", var_list); //======================================================================================================== LogMsg(LINEBEFORE+SHORTTIMESTAMP,"Begin testing API => SQLTransact | SQLTransact | transact.c\n"); TEST_INIT; TESTCASE_BEGIN("Initializing SQLTransact test environment\n"); // if(!FullConnect(pTestInfo)) { LogMsg(NONE,"Unable to connect\n"); TEST_FAILED; TEST_RETURN; } henv = pTestInfo->henv; hdbc = pTestInfo->hdbc; hstmt = (SQLHANDLE)pTestInfo->hstmt; returncode = SQLAllocStmt((SQLHANDLE)hdbc, &hstmt); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocStmt")) { LogAllErrors(henv,hdbc,hstmt); FullDisconnect(pTestInfo); TEST_FAILED; TEST_RETURN; } for (commit_on_off = 0; commit_on_off < 10; commit_on_off++) { returncode = SQLSetConnectOption((SQLHANDLE)hdbc,SQL_AUTOCOMMIT,SQL_AUTOCOMMIT_ON); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetConnectOption")) { LogAllErrors(henv,hdbc,hstmt); FullDisconnect(pTestInfo); TEST_FAILED; TEST_RETURN; } TESTCASE_END; SQLExecDirect(hstmt,(SQLCHAR*)ExecDirStr[4],SQL_NTS); /* CLEANUP */ for (i = 0; i <= (iend-1); i++) { sprintf(Heading,"Test Positive Functionality of SQLTransact while Autocommit is ON and executing\n"); strcat(Heading, ExecDirStr[i]); strcat(Heading, "\n"); TESTCASE_BEGIN(Heading); returncode = SQLExecDirect(hstmt,(SQLCHAR*)ExecDirStr[i],SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; } } SQLExecDirect(hstmt,(SQLCHAR*)ExecDirStr[4],SQL_NTS); /* CLEANUP */ returncode = SQLSetConnectOption((SQLHANDLE)hdbc,SQL_AUTOCOMMIT,SQL_AUTOCOMMIT_OFF); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetConnectOption")) { LogAllErrors(henv,hdbc,hstmt); FullDisconnect(pTestInfo); TEST_FAILED; TEST_RETURN; } TESTCASE_END; for (i = 0; i <= (iend-1); i++) { for (j = 0; j <= jend; j++) { sprintf(Heading,"Test Positive Functionality of SQLTransact while Autocommit is OFF and executing\n"); strcat(Heading, ExecDirStr[i]); strcat(Heading, " & "); strcat(Heading, TypeDesc[j]); strcat(Heading, "\n"); TESTCASE_BEGIN(Heading); returncode = SQLExecDirect(hstmt,(SQLCHAR*)ExecDirStr[i],SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; } else { returncode=SQLTransact((SQLHANDLE)henv,(SQLHANDLE)hdbc,fType[j]); Sleep(2); // tmf rollback is slower. if(!CHECKRC(SQL_SUCCESS,returncode,"SQLTransact")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; } returncode = SQLExecDirect(hstmt,(SQLCHAR*)ExecDirStr[iend],SQL_NTS); if(!CHECKRC(CheckRes[i].ExeRes[j],returncode,"SQLExecDirect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; } else { if (returncode == SQL_SUCCESS || returncode == SQL_SUCCESS_WITH_INFO) { Output = (char *)malloc(NAME_LEN); returncode=SQLBindCol(hstmt,1,SQL_C_CHAR,Output,NAME_LEN,&OutputLen); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindCol")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; } else { returncode = SQLFetch(hstmt); if(!CHECKRC(CheckRes[i].FetchRes[j],returncode,"SQLFetch")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; } else { if (returncode != SQL_NO_DATA_FOUND && returncode != SQL_ERROR) { if (strcspn(CheckRes[i].DataRes[j],Output) == 0) { LogMsg(NONE,"expect: %s and actual: %s are matched\n",Output,CheckRes[i].DataRes[j]); } else { LogMsg(NONE,"expect: %s and actual: %s are not matched\n",Output,CheckRes[i].DataRes[j]); TEST_FAILED; } } } free(Output); SQLFreeStmt(hstmt,SQL_CLOSE); } } } } TESTCASE_END; }/* end j loop */ }/* end i loop */ } //======================================================================================================== SQLExecDirect(hstmt,(SQLCHAR*)ExecDirStr[4],SQL_NTS); /* CLEANUP */ returncode = SQLDisconnect((SQLHANDLE)hdbc); if(!CHECKRC(SQL_ERROR,returncode,"SQLDisconnect")) { LogAllErrorsVer3(henv,hdbc,hstmt); TEST_FAILED; } // Free the open transactions. returncode=SQLTransact((SQLHANDLE)henv,(SQLHANDLE)hdbc,SQL_ROLLBACK); Sleep(2); returncode=FullDisconnect(pTestInfo); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFullDisconnect")) { LogAllErrorsVer3(henv,hdbc,hstmt); TEST_FAILED; } LogMsg(SHORTTIMESTAMP+LINEAFTER,"End testing API => SQLTransact.\n"); free_list(var_list); TEST_RETURN; }
/* connect to two databases using a Type 2 connection with two-phase commit */ int TwoConnType2TwoPhaseUse(SQLHANDLE henv, char dbAlias1[], char dbAlias2[], char user1[], char pswd1[], char user2[], char pswd2[]) { SQLRETURN cliRC = SQL_SUCCESS; int rc = 0; SQLHANDLE hdbc1, hdbc2; /* connection handles */ SQLHANDLE hstmt1, hstmt2, hstmt3, hstmt4; /* statement handles */ SQLHANDLE hstmt5, hstmt6, hstmt7, hstmt8; /* statement handles */ struct { SQLINTEGER ind; SQLSMALLINT val; } rownumber; /* variable to be bound to the ROW column */ struct { SQLINTEGER ind; SQLCHAR val[10]; } value; /* variable to be bound to the VALUE column */ printf("\n-----------------------------------------------------------"); printf("\nUSE THE CLI FUNCTIONS\n"); printf(" SQLAllocHandle\n"); printf(" SQLSetConnectAttr\n"); printf(" SQLConnect\n"); printf(" SQLExecDirect\n"); printf(" SQLEndTran\n"); printf(" SQLBindCol\n"); printf(" SQLFetch\n"); printf(" SQLDisconnect\n"); printf(" SQLFreeHandle\n"); printf("TO PERFORM TRANSACTIONS ON TWO CONNECTIONS\n"); printf("USING TYPE 2 CONNECT WITH TWO-PHASE COMMIT:\n"); /* allocate the first database connection handle */ cliRC = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc1); DBC_HANDLE_CHECK(hdbc1, cliRC); /* allocate the second database connection handle */ cliRC = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc2); DBC_HANDLE_CHECK(hdbc2, cliRC); /* set TYPE 2 CONNECT with two-phase commit for the both connections */ printf("\n Set TYPE 2 CONNECT two-phase commit for both connections.\n"); cliRC = SQLSetConnectAttr(hdbc1, SQL_ATTR_CONNECTTYPE, (SQLPOINTER)SQL_COORDINATED_TRANS, SQL_NTS); DBC_HANDLE_CHECK(hdbc1, cliRC); cliRC = SQLSetConnectAttr(hdbc1, SQL_ATTR_SYNC_POINT, (SQLPOINTER)SQL_TWOPHASE, SQL_NTS); DBC_HANDLE_CHECK(hdbc1, cliRC); cliRC = SQLSetConnectAttr(hdbc2, SQL_ATTR_CONNECTTYPE, (SQLPOINTER)SQL_COORDINATED_TRANS, SQL_NTS); DBC_HANDLE_CHECK(hdbc2, cliRC); cliRC = SQLSetConnectAttr(hdbc2, SQL_ATTR_SYNC_POINT, (SQLPOINTER)SQL_TWOPHASE, SQL_NTS); DBC_HANDLE_CHECK(hdbc2, cliRC); printf("\n Connect to '%s' database on connection 1.\n", dbAlias1); /* connect to the first database */ cliRC = SQLConnect(hdbc1, (SQLCHAR *)dbAlias1, SQL_NTS, (SQLCHAR *)user1, SQL_NTS, (SQLCHAR *)pswd1, SQL_NTS); DBC_HANDLE_CHECK(hdbc1, cliRC); printf(" Connect to '%s' database on connection 2.\n", dbAlias2); /* connect to the second database */ cliRC = SQLConnect(hdbc2, (SQLCHAR *)dbAlias2, SQL_NTS, (SQLCHAR *)user2, SQL_NTS, (SQLCHAR *)pswd2, SQL_NTS); DBC_HANDLE_CHECK(hdbc2, cliRC); /********* Start using the connections ************************/ /* set AUTOCOMMIT OFF for both connections */ printf("\n Turn auto-commit OFF for connection 1.\n"); cliRC = SQLSetConnectAttr(hdbc1, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS); DBC_HANDLE_CHECK(hdbc1, cliRC); printf(" Turn auto-commit OFF for connection 2.\n"); cliRC = SQLSetConnectAttr(hdbc2, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS); DBC_HANDLE_CHECK(hdbc2, cliRC); /* allocate all statement handles */ cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt1); DBC_HANDLE_CHECK(hdbc1, cliRC); cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc2, &hstmt2); DBC_HANDLE_CHECK(hdbc2, cliRC); cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt3); DBC_HANDLE_CHECK(hdbc1, cliRC); cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc2, &hstmt4); DBC_HANDLE_CHECK(hdbc2, cliRC); cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt5); DBC_HANDLE_CHECK(hdbc1, cliRC); cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc2, &hstmt6); DBC_HANDLE_CHECK(hdbc2, cliRC); cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc1, &hstmt7); DBC_HANDLE_CHECK(hdbc1, cliRC); cliRC = SQLAllocHandle(SQL_HANDLE_STMT, hdbc2, &hstmt8); DBC_HANDLE_CHECK(hdbc2, cliRC); printf("\n Perform statements on both connections:\n"); printf("\n Create table1 on connection 1.\n"); /* create a table on connection 1 */ cliRC = SQLExecDirect(hstmt1, (SQLCHAR *)"CREATE TABLE table1(row INTEGER, value CHAR(10))", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt1, henv, cliRC); printf(" Create table1 on connection 2.\n"); /* create a table on connection 2 */ cliRC = SQLExecDirect(hstmt2, (SQLCHAR *)"CREATE TABLE table1(row INTEGER, value CHAR(10))", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt2, henv, cliRC); printf(" Commit the transaction.\n"); /* end the transaction */ cliRC = SQLEndTran(SQL_HANDLE_DBC, hdbc1, SQL_COMMIT); DBC_HANDLE_CHECK(hdbc1, cliRC); /* insert values into both tables */ printf("\n Insert values (1, 'abc') into table1 on connection 1.\n"); cliRC = SQLExecDirect(hstmt3, (SQLCHAR *)"INSERT INTO table1 VALUES (1, 'abc')", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt3, henv, cliRC); printf(" Insert values (1, 'def') into table1 on connection 2.\n"); cliRC = SQLExecDirect(hstmt4, (SQLCHAR *)"INSERT INTO table1 VALUES (1, 'def')", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt4, henv, cliRC); printf(" Commit the transaction.\n"); /* end the transaction */ cliRC = SQLEndTran(SQL_HANDLE_DBC, hdbc1, SQL_COMMIT); DBC_HANDLE_CHECK(hdbc1, cliRC); printf("\n Check values inserted on both connections:\n"); /* check values successfully inserted on connection 1 */ cliRC = SQLExecDirect(hstmt5, (SQLCHAR *)"SELECT * FROM table1", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt5, henv, cliRC); /* bind column 1 to variable */ cliRC = SQLBindCol(hstmt5, 1, SQL_C_SHORT, &rownumber.val, 0, &rownumber.ind); MC_STMT_HANDLE_CHECK(hstmt5, henv, cliRC); /* bind column 2 to variable */ cliRC = SQLBindCol(hstmt5, 2, SQL_C_CHAR, value.val, 10, &value.ind); MC_STMT_HANDLE_CHECK(hstmt5, henv, cliRC); printf("\n CONNECTION 1"); printf("\n Fetch each row and display.\n"); printf(" ROW # VALUE \n"); printf(" -------- -------------\n"); /* fetch each row and display */ cliRC = SQLFetch(hstmt5); MC_STMT_HANDLE_CHECK(hstmt5, henv, cliRC); if (cliRC == SQL_NO_DATA_FOUND) { printf("\n Data not found.\n"); } while (cliRC != SQL_NO_DATA_FOUND) { printf(" %-8d %-10.10s \n", rownumber.val, value.val); /* fetch next row */ cliRC = SQLFetch(hstmt5); MC_STMT_HANDLE_CHECK(hstmt5, henv, cliRC); } /* Check values successfully inserted on connection 2 */ cliRC = SQLExecDirect(hstmt6, (SQLCHAR *)"SELECT * FROM table1", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt6, henv, cliRC); /* bind column 1 to variable */ cliRC = SQLBindCol(hstmt6, 1, SQL_C_SHORT, &rownumber.val, 0, &rownumber.ind); MC_STMT_HANDLE_CHECK(hstmt6, henv, cliRC); /* bind column 2 to variable */ cliRC = SQLBindCol(hstmt6, 2, SQL_C_CHAR, value.val, 10, &value.ind); MC_STMT_HANDLE_CHECK(hstmt6, henv, cliRC); printf("\n CONNECTION 2\n"); printf(" Fetch each row and display.\n"); printf(" ROW # VALUE \n"); printf(" -------- -------------\n"); /* fetch each row and display */ cliRC = SQLFetch(hstmt6); MC_STMT_HANDLE_CHECK(hstmt6, henv, cliRC); if (cliRC == SQL_NO_DATA_FOUND) { printf("\n Data not found.\n"); } while (cliRC != SQL_NO_DATA_FOUND) { printf(" %-8d %-10.10s \n", rownumber.val, value.val); /* fetch next row */ cliRC = SQLFetch(hstmt6); MC_STMT_HANDLE_CHECK(hstmt6, henv, cliRC); } printf("\n Drop table1 on connection 1.\n"); cliRC = SQLExecDirect(hstmt7, (SQLCHAR *)"DROP TABLE table1", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt7, henv, cliRC); printf(" Drop table1 on connection 2.\n"); cliRC = SQLExecDirect(hstmt8, (SQLCHAR *)"DROP TABLE table1", SQL_NTS); MC_STMT_HANDLE_CHECK(hstmt8, henv, cliRC); printf(" Commit the transaction.\n"); /* end the transaction */ cliRC = SQLEndTran(SQL_HANDLE_DBC, hdbc1, SQL_COMMIT); DBC_HANDLE_CHECK(hdbc1, cliRC); /* free all statement handles */ cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt1); MC_STMT_HANDLE_CHECK(hstmt1, henv, cliRC); cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt2); MC_STMT_HANDLE_CHECK(hstmt2, henv, cliRC); cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt3); MC_STMT_HANDLE_CHECK(hstmt3, henv, cliRC); cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt4); MC_STMT_HANDLE_CHECK(hstmt4, henv, cliRC); cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt5); MC_STMT_HANDLE_CHECK(hstmt5, henv, cliRC); cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt6); MC_STMT_HANDLE_CHECK(hstmt6, henv, cliRC); cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt7); MC_STMT_HANDLE_CHECK(hstmt7, henv, cliRC); cliRC = SQLFreeHandle(SQL_HANDLE_STMT, hstmt8); MC_STMT_HANDLE_CHECK(hstmt8, henv, cliRC); /********* Stop using the connections *************************/ printf("\n Disconnect from '%s' database.\n", dbAlias1); /* disconnect from the first database */ cliRC = SQLDisconnect(hdbc1); DBC_HANDLE_CHECK(hdbc1, cliRC); printf(" Disconnect from '%s' database.\n", dbAlias2); /* disconnect from the second database */ cliRC = SQLDisconnect(hdbc2); DBC_HANDLE_CHECK(hdbc2, cliRC); /* free the handle for connection 1 */ cliRC = SQLFreeHandle(SQL_HANDLE_DBC, hdbc1); DBC_HANDLE_CHECK(hdbc1, cliRC); /* free the handle for connection 2 */ cliRC = SQLFreeHandle(SQL_HANDLE_DBC, hdbc2); DBC_HANDLE_CHECK(hdbc2, cliRC); return 0; } /* TwoConnType2TwoPhaseUse */
/* --------------------------------------------------------- TestHash2 --------------------------------------------------------- */ PassFail TestHash2(TestInfo *pTestInfo) { TEST_DECLARE; SQLRETURN returncode; SQLHENV henv = 0; SQLHDBC hdbc = 0; SQLHSTMT hstmt= 0; SQLUSMALLINT ParamStatusArray[ARRAY_SIZE]; SQLUSMALLINT expParamStatusArray[ARRAY_SIZE]; SQLUSMALLINT lastExpParamStatusArray[ARRAY_SIZE]; SQLULEN lastParamsProcessed=ARRAY_SIZE, ParamsProcessed = 0; SQLLEN rowcount = 0, expRowcount = 0, lastExpRowcount = 0; int i,j,k,counter = 1, loopcount = 0; TCHAR buffer[256]; typedef struct { TCHAR num[15]; SQLLEN numLenOrInd; TCHAR val[15]; SQLLEN valLenOrInd; }nameStruct; nameStruct nameArray1[ARRAY_SIZE]; SQLUINTEGER mode = 1; SQLUINTEGER startnode = 2; SQLUINTEGER streams_per_node = 4; SQLUINTEGER delay_error = 1; SQLUINTEGER suggested_rowset_size=0; SQLTCHAR *sqlDrvInsert = (SQLTCHAR*)_T("PLANLOADTABLE HASH2_TABLE"); SQLTCHAR *dropTbl = (SQLTCHAR *)_T("DROP TABLE HASH2_TABLE cascade"); SQLTCHAR *crtTbl = (SQLTCHAR *)_T("CREATE TABLE HASH2_TABLE (A int NOT NULL NOT DROPPABLE, B varchar(10), PRIMARY KEY (A))"); SQLTCHAR *insTbl = (SQLTCHAR *)_T("INSERT INTO HASH2_TABLE values (?,?)"); // SQLTCHAR *selTbl = (SQLTCHAR *)_T("SELECT * HASH2_TABLE"); //================================================================================================== LogMsg(LINEBEFORE+SHORTTIMESTAMP,_T("Begin testing feature => Hash2.\n")); TEST_INIT; returncode = SQLAllocEnv(&henv); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocEnv")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLAllocConnect( henv, &hdbc); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocConnect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_ON,0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetConnectAttr")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } //================================================================================================== // Set Mode to Loader returncode = SQLSetConnectAttr(hdbc, SQL_MODE_LOADER, (void *) mode, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_MODE_LOADER")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } // Set Start mode returncode = SQLSetConnectAttr(hdbc, SQL_START_NODE, (void *) startnode, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_START_NODE")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } // Set Desired Streams Per Node returncode = SQLSetConnectAttr(hdbc, SQL_STREAMS_PER_SEG, (void *) streams_per_node, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_STREAMS_PER_SEG")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } // Set delay_error mode returncode = SQLSetConnectAttr(hdbc, SQL_LOADER_DELAYERROR, (void *) delay_error, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_LOADER_DELAYERROR")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } //================================================================================================== returncode = SQLConnect(hdbc, (SQLTCHAR*)pTestInfo->DataSource,(SWORD)_tcslen(pTestInfo->DataSource), (SQLTCHAR*)pTestInfo->UserID,(SWORD)_tcslen(pTestInfo->UserID), (SQLTCHAR*)pTestInfo->Password,(SWORD)_tcslen(pTestInfo->Password) ); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLAllocStmt(hdbc, &hstmt); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLConnect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLExecDirect(hstmt, dropTbl, SQL_NTS); returncode = SQLExecDirect(hstmt, crtTbl, SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLPrepare(hstmt, (SQLTCHAR *) sqlDrvInsert, SQL_NTS); if (returncode != SQL_SUCCESS) { LogMsg(ERRMSG,_T("PLANLOADTABLE is expected to return SQL_SUCCESS, actual is %d\n"), returncode); LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLGetConnectAttr(hdbc, SQL_ATTR_SUG_ROWSET_SIZE, &suggested_rowset_size, 0, NULL); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_SUG_ROWSET_SIZE")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } LogMsg(LINEAFTER,_T("suggested_rowset_size=%d\n"), suggested_rowset_size); //================================================================================================== // Set the SQL_ATTR_PARAM_BIND_TYPE statement attribute to use row-wise binding. returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_BIND_TYPE, (void *)sizeof(nameStruct), 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAM_BIND_TYPE")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } // Specify the number of elements in each parameter array. returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMSET_SIZE, (void *)ARRAY_SIZE, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAMSET_SIZE")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } // Specify an array in which to return the status of each set of parameters. returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAM_STATUS_PTR, ParamStatusArray, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAM_STATUS_PTR")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } // Specify an SQLUINTEGER value in which to return the number of sets of parameters processed. returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMS_PROCESSED_PTR, &ParamsProcessed, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAMS_PROCESSED_PTR")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLPrepare(hstmt, insTbl, SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLPrepare")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_TCHAR, SQL_INTEGER, 10, 0, &nameArray1[0].num, 300, &nameArray1[0].numLenOrInd); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindParameter")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } returncode = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_TCHAR, SQL_WCHAR, 10, 0, &nameArray1[0].val, 300, &nameArray1[0].valLenOrInd); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLBindParameter")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } for (j=0; j<ARRAY_SIZE; j++) { lastExpParamStatusArray[j] = SQL_PARAM_SUCCESS; expParamStatusArray[j] = SQL_PARAM_SUCCESS; } //================================================================================================== TESTCASE_BEGIN("Test the positive functionality of Hash2, with delay_error mode ON.\n"); loopcount = 4; k = 0; while ( k < (loopcount+1)) { expRowcount = 0; if (k==loopcount) { //Send a dummy rowsets to get the status array of the previous rowsets in delay-mode LogMsg(LINEAFTER,_T("Insert dummy rowsets with size=0\n")); returncode = SQLSetStmtAttr(hstmt, SQL_ATTR_PARAMSET_SIZE, (void *)0, 0); if(!CHECKRC(SQL_SUCCESS,returncode,"SQL_ATTR_PARAMSET_SIZE")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } } else { _stprintf(buffer, _T("Data inserted: ")); for (j=0; j<ARRAY_SIZE; j++) { if ((j+1)%(3+2*k) == 0) { counter--; expParamStatusArray[j] = SQL_PARAM_ERROR; } else { expParamStatusArray[j] = SQL_PARAM_SUCCESS; expRowcount++; } _stprintf(nameArray1[j].num,_T("%d"),counter++); nameArray1[j].numLenOrInd = SQL_NTS; _stprintf(nameArray1[j].val,_T("%s"),_T("chochet")); nameArray1[j].valLenOrInd = SQL_NTS; _tcscat(buffer,nameArray1[j].num); _tcscat(buffer,_T(" ")); } _tcscat(buffer,_T("\n")); } LogMsg(NONE,_T("%s\n"), buffer); returncode = SQLExecute(hstmt); if (delay_error == 1 && k != 0) { if(returncode != SQL_SUCCESS_WITH_INFO) { LogMsg(ERRMSG,_T("SQLExecute: returncode expected: SQL_SUCCESS_WITH_INFO, actual: %d at line=%d\n"), returncode, __LINE__); LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } } else { if(returncode != SQL_SUCCESS) { LogMsg(ERRMSG,_T("SQLExecute: returncode expected: SQL_SUCCESS, actual: %d at line=%d\n"), returncode, __LINE__); LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; TEST_RETURN; } } if ((k == loopcount && ParamsProcessed != 0) || (k != loopcount && ParamsProcessed != ARRAY_SIZE)) { LogMsg(ERRMSG,_T("ParamsProcessed is not the same as rowset size from client, at line=%d\n"), __LINE__); TEST_FAILED; } returncode = SQLRowCount(hstmt, &rowcount); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLRowCount")) { LogAllErrors(henv,hdbc,hstmt); TEST_FAILED; } if (delay_error == 1) { if (lastExpRowcount != rowcount) { TEST_FAILED; LogMsg(ERRMSG,_T("Expected Rowcount=%d, Actual Rowcount=%d\n"), expRowcount, rowcount); } lastExpRowcount = expRowcount; LogMsg(NONE,_T("\n%d last rows processed, %d current rows processed, rowcount=%d\n"), lastParamsProcessed, ParamsProcessed, rowcount); for (i = 0; i < (int)lastParamsProcessed; i++) { LogMsg(NONE,_T("Parameter Set Status\n")); LogMsg(NONE,_T("------------- -------------\n")); if (ParamStatusArray[i] != lastExpParamStatusArray[i]) { TEST_FAILED; LogMsg(ERRMSG,_T("Param status array at row #%d is expected: %d, actual %d\n"), i, lastExpParamStatusArray[i], ParamStatusArray[i]); continue; } switch (ParamStatusArray[i]) { case SQL_PARAM_SUCCESS: case SQL_PARAM_SUCCESS_WITH_INFO: LogMsg(NONE,_T("%13d Success\n"), i); break; case SQL_PARAM_ERROR: LogMsg(NONE,_T("%13d Error <-------\n"), i); break; case SQL_PARAM_UNUSED: LogMsg(NONE,_T("%13d Not processed\n"), i); break; case SQL_PARAM_DIAG_UNAVAILABLE: LogMsg(NONE,_T("%13d Unknown\n"), i); break; } } LogMsg(NONE,_T("\n============================================================\n")); lastParamsProcessed = ParamsProcessed; for (j=0; j<ARRAY_SIZE; j++) { lastExpParamStatusArray[j] = expParamStatusArray[j]; } } else { if (expRowcount != rowcount) { TEST_FAILED; LogMsg(ERRMSG,_T("Expected Rowcount=%d, Actual Rowcount=%d\n"), expRowcount, rowcount); } LogMsg(NONE,_T("\n%d current rows processed, rowcount=%d\n"), ParamsProcessed, rowcount); for (i = 0; i < (int)ParamsProcessed; i++) { LogMsg(NONE,_T("Parameter Set Status\n")); LogMsg(NONE,_T("------------- -------------\n")); if (ParamStatusArray[i] != expParamStatusArray[i]) { TEST_FAILED; LogMsg(ERRMSG,_T("Param status array at row #%d is expected: %d, actual %d\n"), i, expParamStatusArray[i], ParamStatusArray[i]); continue; } switch (ParamStatusArray[i]) { case SQL_PARAM_SUCCESS: case SQL_PARAM_SUCCESS_WITH_INFO: LogMsg(NONE,_T("%13d Success\n"), i); break; case SQL_PARAM_ERROR: LogMsg(NONE,_T("%13d Error <-------\n"), i); break; case SQL_PARAM_UNUSED: LogMsg(NONE,_T("%13d Not processed\n"), i); break; case SQL_PARAM_DIAG_UNAVAILABLE: LogMsg(NONE,_T("%13d Unknown\n"), i); break; } } LogMsg(NONE,_T("\n============================================================\n")); } k++; } TESTCASE_END; SQLFreeStmt( hstmt, SQL_CLOSE ); SQLFreeStmt( hstmt, SQL_UNBIND ); SQLDisconnect( hdbc ); SQLFreeConnect( hdbc ); SQLFreeEnv( henv ); //================================================================================================== LogMsg(SHORTTIMESTAMP+LINEAFTER,_T("End testing feature => Hash2.\n")); TEST_RETURN; }
//************************************************************************* int main() { SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; // Aloocate an environment handle ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env); checkrc(ret,__LINE__); //we need odbc3 support SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0); //ALLOCATE A Connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc); checkrc(ret,__LINE__); // connect to the DSN mydsn ret = SQLConnect (dbc, (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=localhost;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=localhost;PORT=5678;"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); if(SQL_SUCCEEDED(ret)) { printf("\nConnected to the Data Source..\n"); } else { printf("conenction failed\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 1; } ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt); checkrc(ret,__LINE__); SQLCHAR table[100]="CREATE TABLE EMP(EID INT,SALARY INT)"; ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); //AFTER CLOSE THE CONNECTION ,CALL PREPARE ret = SQLPrepare(stmt,table,SQL_NTS); int rettype = ret; if(ret!=SQL_SUCCESS && ret !=SQL_SUCCESS_WITH_INFO) printf("After closing the connection, prepare failed \n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); if(rettype == 0) { printf("Test script failed\n"); return 1; } return 0; }
int test_fun_odbc_api_Oracle__getdata() { int nFunRes = 0; SQLHENV m_hEnviroment; SQLHDBC m_hDatabaseConnection; SQLHSTMT m_hStatement; SQLRETURN retcode; /*Allocate environment handle */ retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnviroment); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { return nFunRes; } /* Set the ODBC version environment attribute */ retcode = SQLSetEnvAttr(m_hEnviroment, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* Allocate connection handle */ retcode = SQLAllocHandle(SQL_HANDLE_DBC, m_hEnviroment, &m_hDatabaseConnection); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* Set login timeout to 5 seconds. */ //SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, 5, 0); /* Connect to data source */ //Oracle12343DYN retcode = SQLConnect(m_hDatabaseConnection, (SQLCHAR*) "Oracle12343DYN", SQL_NTS, (SQLCHAR*) "IT271350_5", SQL_NTS, (SQLCHAR*) "IT271350_5", SQL_NTS); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* Allocate statement handle */ retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hDatabaseConnection, &m_hStatement); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } retcode = SQLExecDirect(m_hStatement,(SQLCHAR*)"select pkey from recipient_info", SQL_NTS); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* get return data Row count */ SQLINTEGER l_siIdCount = 0; retcode = SQLRowCount(m_hStatement, &l_siIdCount); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } while (true) { //fecth data use SQLFetch() return SQL_SUCCESS then no data retcode = SQLFetch(m_hStatement); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { break; } SQLINTEGER l_siID; SQLINTEGER l_siIDLength = 0; retcode = SQLGetData(m_hStatement, 1, SQL_C_ULONG, &l_siID, 0, &l_siIDLength); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { break; } }//while (true) /* Process data */ retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; }
/* ****** Updated by CHENYH at 2004-4-9 10:06:44 ****** 增加pArrays: 为了能够接收处理多请求记录的情况 */ int CallBDFunc(int fno,TRUSERID *handle,ST_CPACK *rpack,ST_PACK *pArrays,int *iRetCode, char *szMsg) { int r=0; int rtn=0; int sendtype=0; char param[101]=""; #ifdef _DEBUG1 CMemoryState cm1, cm2, cm3; #endif APPFUNC pFunc = g_BDefines[fno].pFunc; #ifdef _DEBUG1 cm1.Checkpoint(); #endif *iRetCode=0; *szMsg=0; //判断是否是结帐时刻,如果是则等待处理 sendtype=rpack->head.RequestType/10000; switch(sendtype) { case 93: case 95: rtn = (*pFunc)(handle,rpack->head.RequestType,&rpack->pack,iRetCode,szMsg); break; default: rtn=GetSysParaVal(GLOBE_FLAG_BALANCE,param); if(rtn) { *iRetCode=rtn; break; } else if(strncmp(param,"0",1)!=0) { rtn=E_DAYEND_STATUS; *iRetCode=rtn; break; } rtn = (*pFunc)(handle,rpack->head.RequestType,&rpack->pack,iRetCode,szMsg); break; } if(rtn) { char sErrMsg[101]=""; char sRetMsg[256]=""; if(*szMsg) snprintf(sRetMsg,256," %s",szMsg); r=get_errcode_msg(*iRetCode, sErrMsg); db_rollback(); snprintf(szMsg,256,"%s%s",sErrMsg,sRetMsg); writelog(LOG_ERR,"Func[%d]ecode[%d]msg[%s]",rpack->head.RequestType,*iRetCode,szMsg); ERR_DEAL(szMsg,*iRetCode); if(r) { AnswerData(handle,*iRetCode,szMsg); db_disconnect(); writelog(LOG_ERR,"数据库错误,系统退出"); exit(1); } } else { r=db_commit(); if(r) { *iRetCode=E_DB_COMMIT; strcpy(szMsg,"数据库事务提交失败"); writelog(LOG_ERR,"Func[%d]Msg[%s]",rpack->head.RequestType,szMsg); db_rollback(); ERR_DEAL( szMsg,*iRetCode); } } #ifdef _DEBUG1 cm2.Checkpoint(); if (cm3.Difference(cm1, cm2)) { BCCMsgLogOut(14444,"在执行功能号:%u时候,经检查,内存出现错误!",rpack->head.RequestType); g_LogFile.WriteLogEx(14444,"在执行功能号:%u时候,经检查,内存出现错误!",rpack->head.RequestType); cm3.DumpStatistics(); } #endif if (g_BUnit.m_SqlDB.lErrorCode<=-10000) // 出现SQL比较严重的错误 { if (SQLIsConnectOK()==0) { SQLDisconnect(); } g_BUnit.m_SqlDB.lErrorCode = 0; } return(rtn); }
int test_fun_odbc_api_Mysql__DBPOOL_DYN() { int nFunRes = 0; nFunRes = SQLConfigDataSource( NULL, ODBC_REMOVE_DSN, "MySQL ODBC 5.2 Unicode Driver", "DSN=Mysql12343DYN\0"); // Drop and re-create a Msorcl10.dll (version 1.0) data source. SQLConfigDataSource(NULL, ODBC_ADD_DSN, "MySQL ODBC 5.2 Unicode Driver", "DSN=Mysql12343DYN;UID=IT271350_5;PWD=IT271350_5;SERVER=192.168.123.43;DATABASE=tra_occ"); SQLHENV m_hEnviroment; SQLHDBC m_hDatabaseConnection; SQLHSTMT m_hStatement; SQLRETURN retcode; ////http://support.microsoft.com/kb/164221/en-us ////http://www.informixchina.net/club/thread-5924-1-1.html /*Allocate environment handle */ retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_hEnviroment); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { return nFunRes; } // set the ODBC behavior version. /* Set the ODBC version environment attribute */ retcode = SQLSetEnvAttr(m_hEnviroment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0); if (!SQL_SUCCEEDED(retcode)) { retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } // make process level cursor pooling retcode = SQLSetEnvAttr(m_hEnviroment, SQL_ATTR_CONNECTION_POOLING, (SQLPOINTER)SQL_CP_ONE_PER_DRIVER, SQL_IS_UINTEGER); if (!SQL_SUCCEEDED(retcode)) { retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } //set the matching condition for using an existing connection in the pool retcode = SQLSetEnvAttr(m_hEnviroment, SQL_ATTR_CP_MATCH, (SQLPOINTER)SQL_CP_RELAXED_MATCH, 0);//SQL_IS_INTEGER if (!SQL_SUCCEEDED(retcode)) { printf("SQLSetEnvAttr/SQL_ATTR_CP_MATCH error\n"); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } int nIndex = 0; while (nIndex < 10) { /* Allocate connection handle */ retcode = SQLAllocHandle(SQL_HANDLE_DBC, m_hEnviroment, &m_hDatabaseConnection); if (!SQL_SUCCEEDED(retcode)) { printf("SQLAllocHandle error\n"); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* Set login timeout to 5 seconds. */ //SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, 5, 0); /* Connect to data source */ retcode = SQLConnect(m_hDatabaseConnection, (SQLCHAR*) "Mysql12343DYN", SQL_NTS, (SQLCHAR*) "IT271350_5", SQL_NTS, (SQLCHAR*) "IT271350_5", SQL_NTS); if (!SQL_SUCCEEDED(retcode)) { printf("SQLConnect error\n"); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } else { printf("Connect successfully %d times\n", nIndex); } ////////////////////////////////////////////////////////////////////////// /* Allocate statement handle */ retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hDatabaseConnection, &m_hStatement); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } retcode = SQLExecDirect(m_hStatement,(SQLCHAR*)"select pkey from recipient_info", SQL_NTS); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } /* get return data Row count */ SQLINTEGER l_siIdCount = 0; retcode = SQLRowCount(m_hStatement, &l_siIdCount); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); return nFunRes; } while (true) { //fecth data use SQLFetch() return SQL_SUCCESS then no data retcode = SQLFetch(m_hStatement); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { break; } SQLINTEGER l_siID; SQLINTEGER l_siIDLength = 0; retcode = SQLGetData(m_hStatement, 1, SQL_C_ULONG, &l_siID, 0, &l_siIDLength); if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO) { break; } }//while (true) //the first time, the application calls SQLDisconenct, it will return //the connection to the //pool retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hStatement); retcode = SQLDisconnect(m_hDatabaseConnection); retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hDatabaseConnection); ////////////////////////////////////////////////////////////////////////// nIndex++; }//while (nIndex < 10) retcode = SQLFreeHandle(SQL_HANDLE_ENV, m_hEnviroment); nFunRes = SQLConfigDataSource( NULL, ODBC_REMOVE_DSN, "MySQL ODBC 5.2 Unicode Driver", "DSN=Mysql12343DYN\0"); return nFunRes; }
DWORD WINAPI NetmailOutThread(LPVOID param) { SQLHDBC hdbc; SQLHSTMT hstmt; SQLRETURN sqlret; SQLLEN cb; HANDLE hHeap; FTNAddr LastAddr; HANDLE hPktFile; wchar_t tmpFileName[MAX_PATH], finalPktFileName[MAX_PATH],FileboxDirName[MAX_PATH]; wchar_t LogStr[255]; unsigned int PktNumber; char PktPwd[9]; NetmailOutQueue NDOQ; int WaitTime; int result; HANDLE hEvent[2]; InterlockedIncrement(&(cfg.ThreadCount)); WaitTime=INFINITE; hEvent[0]=cfg.hExitEvent; hEvent[1]=cfg.hNetmailOutEvent; AddLogEntry(L"Netmail out thread started"); loop: result=WaitForMultipleObjects(2,hEvent,FALSE,WaitTime); if (result==WAIT_TIMEOUT) { SQLFreeHandle(SQL_HANDLE_STMT,hstmt); SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC,hdbc); WaitTime=INFINITE; HeapDestroy(hHeap); goto loop; } if (WaitTime==INFINITE) { hHeap=HeapCreate(HEAP_NO_SERIALIZE,16384,0); SQLAllocHandle(SQL_HANDLE_DBC, cfg.henv, &hdbc); sqlret=SQLDriverConnectW(hdbc, NULL, cfg.ConnectionString, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (sqlret != SQL_SUCCESS && sqlret != SQL_SUCCESS_WITH_INFO) { SetEvent(cfg.hExitEvent); goto threadexit; //fatal error } SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); WaitTime=10000; } switch(result) { case (WAIT_OBJECT_0): { goto threadexit; } case (WAIT_OBJECT_0+1): { NDOQ.First=NULL; NDOQ.Last=NULL; EnterCriticalSection(&NetmailRouteCritSect); SQLExecDirectW(hstmt, L"execute sp_DirectNetmail", SQL_NTS); // обработать директный нетмейл для использующих FTN Service линков LeaveCriticalSection(&NetmailRouteCritSect); sqlret=SQLExecDirectW(hstmt,L"select MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail where direct=1 and sent=0 and Locked=0 order by ToZone,ToNet,ToNode,MessageID",SQL_NTS); if ((sqlret==SQL_SUCCESS)||(sqlret==SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt,hHeap,&NDOQ); } sqlret=SQLExecDirectW(hstmt,L"select MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail,MyAka where direct=0 and sent=0 and Locked=0 and MyAka.Point=0 and Netmail.ToPoint<>0 and Netmail.ToZone=MyAka.Zone and Netmail.ToNet=MyAka.Net and Netmail.ToNode=MyAka.Node order by ToPoint,MessageID",SQL_NTS); if ((sqlret==SQL_SUCCESS)||(sqlret==SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt, hHeap, &NDOQ); } sqlret = SQLExecDirectW(hstmt, L"select MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail,Links where direct=0 and sent=0 and Locked=0 and Netmail.ToZone=Links.Zone and Netmail.ToNet=Links.Net and Netmail.ToNode=Links.Node and Links.NetmailDirect<>0 and Links.LinkType=2 order by Links.LinkID,MessageID", SQL_NTS); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt, hHeap, &NDOQ); } LastAddr.FullAddr=0; hPktFile=INVALID_HANDLE_VALUE; while (NDOQ.First!=NULL) { lpNetmailMessage lpTmp; wsprintfW(LogStr,L"Direct netmail From %u:%u/%u.%u To %u:%u/%u.%u",NDOQ.First->FromAddr.zone,NDOQ.First->FromAddr.net,NDOQ.First->FromAddr.node,NDOQ.First->FromAddr.point,NDOQ.First->ToAddr.zone,NDOQ.First->ToAddr.net,NDOQ.First->ToAddr.node,NDOQ.First->ToAddr.point); AddLogEntry(LogStr); if (LastAddr.FullAddr!=NDOQ.First->ToAddr.FullAddr) { if(LastAddr.FullAddr!=0) { ClosePktFile(hPktFile); CreateDirectoryW(FileboxDirName,NULL); MoveFileExW(tmpFileName,finalPktFileName,MOVEFILE_COPY_ALLOWED); } LastAddr.FullAddr=NDOQ.First->ToAddr.FullAddr; //create file PktNumber=GetPktNumber(hstmt); wsprintfW(FileboxDirName, L"%s\\%u.%u.%u.%u", cfg.FileboxesDir, NDOQ.First->ToAddr.zone, NDOQ.First->ToAddr.net, NDOQ.First->ToAddr.node, NDOQ.First->ToAddr.point); wsprintfW(tmpFileName, L"%s\\%08X.NETMAIL", cfg.TmpOutboundDir, PktNumber); wsprintfW(finalPktFileName,L"%s\\%08X.PKT",FileboxDirName,PktNumber); hPktFile=CreateFileW(tmpFileName,GENERIC_READ|GENERIC_WRITE,0,NULL,CREATE_NEW,0,NULL); memset(PktPwd, 0, 9); SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.zone), 0, NULL); SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.net), 0, NULL); SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.node), 0, NULL); SQLBindParameter(hstmt, 4, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(NDOQ.First->ToAddr.point), 0, NULL); sqlret = SQLExecDirectW(hstmt, L"Select PktPassword from Links where Zone=? and Net=? and Node=? and Point=?", SQL_NTS); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { sqlret = SQLFetch(hstmt); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { SQLGetData(hstmt, 1, SQL_C_CHAR, PktPwd, 9, &cb); } } SQLCloseCursor(hstmt); SQLFreeStmt(hstmt, SQL_RESET_PARAMS); WritePktHeader(hPktFile,&(cfg.MyAddr),&(NDOQ.First->ToAddr),PktPwd); } // WriteNetmailMessage(hPktFile,hHeap,NDOQ.First); // SQLBindParameter(hstmt,1,SQL_PARAM_INPUT,SQL_C_ULONG,SQL_INTEGER,0,0,&(NDOQ.First->MessageID),0,NULL); sqlret=SQLExecDirectW(hstmt,L"{call sp_NetmailMessageSent(?)}",SQL_NTS); SQLFreeStmt(hstmt,SQL_RESET_PARAMS); // lpTmp=NDOQ.First->NextMsg; HeapFree(hHeap,0,NDOQ.First->MsgText); if (NDOQ.First->ReplyTo!=NULL) HeapFree(hHeap,0,NDOQ.First->ReplyTo); if (NDOQ.First->MsgId!=NULL) HeapFree(hHeap,0,NDOQ.First->MsgId); HeapFree(hHeap,0,NDOQ.First->Subject); HeapFree(hHeap,0,NDOQ.First->ToName); HeapFree(hHeap,0,NDOQ.First->FromName); HeapFree(hHeap,0,NDOQ.First); NDOQ.First=lpTmp; } if (hPktFile!=INVALID_HANDLE_VALUE) { ClosePktFile(hPktFile); CreateDirectoryW(FileboxDirName,NULL); MoveFileExW(tmpFileName,finalPktFileName,MOVEFILE_COPY_ALLOWED); } // EnterCriticalSection(&NetmailRouteCritSect); SQLExecDirectW(hstmt, L"EXECUTE sp_RouteNetmail",SQL_NTS); LeaveCriticalSection(&NetmailRouteCritSect); SetEvent(cfg.hMailerCallGeneratingEvent); //make polls sqlret = SQLExecDirectW(hstmt, L"select Zone,Net,Node from Links,NetmailOutbound,Netmail where Links.LinkID=NetmailOutbound.ToLinkID and Netmail.MessageID=NetmailOutbound.MessageID and Netmail.Locked=0 and Links.DialOut<>0 and Links.LinkType<=2 and Links.Point=0", SQL_NTS); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { unsigned short zone, net, node; SQLBindCol(hstmt, 1, SQL_C_USHORT, &zone, 0, NULL); SQLBindCol(hstmt, 2, SQL_C_USHORT, &net, 0, NULL); SQLBindCol(hstmt, 3, SQL_C_USHORT, &node, 0, NULL); sqlret = SQLFetch(hstmt); while ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { if (zone == cfg.MyAddr.zone) { wsprintfW(LogStr,L"Creating poll to %u:%u/%u", zone, net, node); AddLogEntry(LogStr); swprintf_s(tmpFileName, MAX_PATH, L"%s\\%04hX%04hX.CLO", cfg.BinkOutboundDir, net, node); hPktFile = CreateFileW(tmpFileName, GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); CloseHandle(hPktFile); // } sqlret = SQLFetch(hstmt); } SQLCloseCursor(hstmt); SQLFreeStmt(hstmt, SQL_UNBIND); } } } goto loop; threadexit: _InterlockedDecrement(&(cfg.ThreadCount)); SetEvent(cfg.hThreadEndEvent); return 0; }
int main(int argc, char *argv[]) { LOGINREC *login; SQLHENV hEnv = 0; SQLHDBC hDbc = 0; SQLRETURN erc; const char *sql; setlocale(LC_ALL, ""); memset(&options, 0, sizeof(options)); options.headers = stderr; login = get_login(argc, argv, &options); /* get command-line parameters and call dblogin() */ assert(login != NULL); /* * Override stdin, stdout, and stderr, as required */ if (options.input_filename) { if (freopen(options.input_filename, "r", stdin) == NULL) { fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.input_filename, strerror(errno)); exit(1); } } if (options.output_filename) { if (freopen(options.output_filename, "w", stdout) == NULL) { fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.output_filename, strerror(errno)); exit(1); } } if (options.error_filename) { if (freopen(options.error_filename, "w", stderr) == NULL) { fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.error_filename, strerror(errno)); exit(1); } } if (options.fverbose) { options.verbose = stderr; } else { static const char null_device[] = "/dev/null"; options.verbose = fopen(null_device, "w"); if (options.verbose == NULL) { fprintf(stderr, "%s:%d unable to open %s for verbose operation: %s\n", options.appname, __LINE__, null_device, strerror(errno)); exit(1); } } fprintf(options.verbose, "%s:%d: Verbose operation enabled\n", options.appname, __LINE__); /* * Connect to the server */ if ((erc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv)) != SQL_SUCCESS) { odbc_herror(SQL_HANDLE_ENV, hEnv, erc, "SQLAllocHandle", "failed to allocate an environment"); exit(EXIT_FAILURE); } assert(hEnv); if ((erc = SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)options.odbc_version, SQL_IS_UINTEGER)) != SQL_SUCCESS){ odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLSetEnvAttr", "failed to set SQL_OV_ODBC3"); exit(EXIT_FAILURE); } if ((erc = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc)) != SQL_SUCCESS) { odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLAllocHandle", "failed to allocate a connection"); exit(EXIT_FAILURE); } assert(hDbc); if ((erc = SQLConnect(hDbc, (SQLCHAR *) options.servername, SQL_NTS, (SQLCHAR *) login->username, SQL_NTS, (SQLCHAR *) login->password, SQL_NTS)) != SQL_SUCCESS) { odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLConnect", "failed"); exit(EXIT_FAILURE); } #if 0 /* Switch to the specified database, if any */ if (options.database) dbuse(dbproc, options.database); #endif /* * Read the queries and write the results */ while ((sql = next_query()) != NULL ) { SQLHSTMT hStmt; if ((erc = SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt)) != SQL_SUCCESS) { odbc_perror(hStmt, erc, "SQLAllocHandle", "failed to allocate a statement handle"); exit(EXIT_FAILURE); } /* "Prepare" the query and send it to the server */ if ((erc = SQLPrepare(hStmt, (SQLCHAR *) sql, SQL_NTS)) != SQL_SUCCESS) { odbc_perror(hStmt, erc, "SQLPrepare", "failed"); exit(EXIT_FAILURE); } if((erc = SQLExecute(hStmt)) != SQL_SUCCESS) { switch(erc) { case SQL_NEED_DATA: goto FreeStatement; case SQL_SUCCESS_WITH_INFO: if (0 != print_error_message(SQL_HANDLE_STMT, hStmt)) { fprintf(stderr, "SQLExecute: continuing...\n"); } break; default: odbc_perror(hStmt, erc, "SQLExecute", "failed"); exit(EXIT_FAILURE); } } /* Write the output */ print_results(hStmt); FreeStatement: if ((erc = SQLFreeHandle(SQL_HANDLE_STMT, hStmt)) != SQL_SUCCESS){ odbc_perror(hStmt, erc, "SQLFreeHandle", "failed"); exit(EXIT_FAILURE); } } SQLDisconnect(hDbc); SQLFreeHandle(SQL_HANDLE_DBC, hDbc); SQLFreeHandle(SQL_HANDLE_ENV, hEnv); return 0; }
void LogSessionAndSendNetmailToLink(lpFTNAddr lpLinkAddr, unsigned char SoftwareCode) { SQLHDBC hdbc; SQLHSTMT hstmt; SQLRETURN sqlret; SQLLEN cb; HANDLE hHeap; HANDLE hPktFile; wchar_t tmpPktFileName[MAX_PATH], finalPktFileName[MAX_PATH], FileboxDirName[MAX_PATH]; wchar_t LogStr[255]; unsigned int PktNumber; unsigned int LinkID; NetmailOutQueue NOQ; char PktPwd[9]; hHeap = HeapCreate(HEAP_NO_SERIALIZE, 16384, 0); SQLAllocHandle(SQL_HANDLE_DBC, cfg.henv, &hdbc); sqlret = SQLDriverConnectW(hdbc, NULL, cfg.ConnectionString, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT); if (sqlret != SQL_SUCCESS && sqlret != SQL_SUCCESS_WITH_INFO) { SetEvent(cfg.hExitEvent); return; //fatal error } SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); SQLBindParameter(hstmt, 1, SQL_PARAM_OUTPUT, SQL_C_ULONG, SQL_INTEGER, 0, 0, &LinkID, 0, NULL); SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->zone), 0, NULL); SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->net), 0, NULL); SQLBindParameter(hstmt, 4, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->node), 0, NULL); SQLBindParameter(hstmt, 5, SQL_PARAM_INPUT, SQL_C_USHORT, SQL_SMALLINT, 0, 0, &(lpLinkAddr->point), 0, NULL); SQLBindParameter(hstmt, 6, SQL_PARAM_INPUT, SQL_C_UTINYINT , SQL_TINYINT, 0, 0, &SoftwareCode, 0, NULL); SQLExecDirectW(hstmt, L"{?=call sp_GetLinkIdForNetmailRouting(?,?,?,?,?)}", SQL_NTS); NOQ.First = NULL; NOQ.Last = NULL; SQLFreeStmt(hstmt, SQL_RESET_PARAMS); if (SoftwareCode != 1) goto exit; if (LinkID != 0) { //netmail out// memset(PktPwd, 0, 9); SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_INTEGER, 0, 0, &LinkID, 0, NULL); sqlret = SQLExecDirectW(hstmt, L"select PktPassword from Links where LinkID=?", SQL_NTS);// if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { sqlret = SQLFetch(hstmt); if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { SQLGetData(hstmt, 1, SQL_C_CHAR, PktPwd, 9, &cb); } } SQLCloseCursor(hstmt); EnterCriticalSection(&NetmailRouteCritSect); sqlret = SQLExecDirectW(hstmt, L"select Netmail.MessageID,FromZone,FromNet,FromNode,FromPoint,ToZone,ToNet,ToNode,ToPoint,CreateTime,FromName,ToName,Subject,MsgId,ReplyTo,MsgText,KillSent,Pvt,FileAttach,Arq,RRq,ReturnReq,Direct,Cfm,recv from Netmail,NetmailOutbound where Netmail.MessageID=NetmailOutbound.MessageID and NetmailOutbound.ToLinkID=? order by Netmail.MessageID", SQL_NTS);// if ((sqlret == SQL_SUCCESS) || (sqlret == SQL_SUCCESS_WITH_INFO)) { GetNetmailMessages(hstmt, hHeap, &NOQ); } SQLFreeStmt(hstmt, SQL_RESET_PARAMS); if (NOQ.First != NULL) { PktNumber = GetPktNumber(hstmt); wsprintfW(FileboxDirName, L"%s\\%u.%u.%u.0", cfg.FileboxesDir, lpLinkAddr->zone, lpLinkAddr->net, lpLinkAddr->node); wsprintfW(tmpPktFileName, L"%s\\%08X.NETMAIL", cfg.TmpOutboundDir, PktNumber); wsprintfW(finalPktFileName, L"%s\\%08X.PKT", FileboxDirName, PktNumber); hPktFile = CreateFileW(tmpPktFileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL); WritePktHeader(hPktFile, &(cfg.MyAddr),lpLinkAddr, PktPwd); // while (NOQ.First != NULL) { lpNetmailMessage lpTmp; // wsprintfW(LogStr, L"Dynamic netmail %u:%u/%u.%u -> %u:%u/%u.%u thru %u:%u/%u", NOQ.First->FromAddr.zone, NOQ.First->FromAddr.net, NOQ.First->FromAddr.node, NOQ.First->FromAddr.point, NOQ.First->ToAddr.zone, NOQ.First->ToAddr.net, NOQ.First->ToAddr.node, NOQ.First->ToAddr.point, lpLinkAddr->zone, lpLinkAddr->net, lpLinkAddr->node); AddLogEntry(LogStr); WriteNetmailMessage(hPktFile, hHeap, NOQ.First); SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_INTEGER, 0, 0, &(NOQ.First->MessageID), 0, NULL); sqlret = SQLExecDirectW(hstmt, L"{call sp_NetmailMessageSent(?)}", SQL_NTS); SQLFreeStmt(hstmt, SQL_RESET_PARAMS); // lpTmp = NOQ.First->NextMsg; HeapFree(hHeap, 0, NOQ.First->MsgText); if (NOQ.First->ReplyTo != NULL) HeapFree(hHeap, 0, NOQ.First->ReplyTo); if (NOQ.First->MsgId != NULL) HeapFree(hHeap, 0, NOQ.First->MsgId); HeapFree(hHeap, 0, NOQ.First->Subject); HeapFree(hHeap, 0, NOQ.First->ToName); HeapFree(hHeap, 0, NOQ.First->FromName); HeapFree(hHeap, 0, NOQ.First); NOQ.First = lpTmp; } if (hPktFile != INVALID_HANDLE_VALUE) { ClosePktFile(hPktFile); CreateDirectoryW(FileboxDirName, NULL); MoveFileExW(tmpPktFileName, finalPktFileName, MOVEFILE_COPY_ALLOWED); } // } LeaveCriticalSection(&NetmailRouteCritSect); } exit: SQLFreeHandle(SQL_HANDLE_STMT, hstmt); SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); HeapDestroy(hHeap); }
/** \brief Disconnect from the server. * * This function ensures that the connection gets closed. * * If the connection is already closed, then the function will * most certainly generate an odbcpp_error. * * \exception odbcpp_error * If the connection fails, or an invalid name is specified, this * function will throw an odbcpp_error exception. */ void connection::disconnect() { f_connected = false; check(SQLDisconnect(f_handle)); }
int main() { SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; // Aloocate an environment handle ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env); checkrc(ret,__LINE__); //we need odbc3 support SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0); //ALLOCATE A Connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc); checkrc(ret,__LINE__); // connect to the DSN mydsn ret = SQLConnect (dbc, (SQLCHAR *) "test", (SQLSMALLINT) strlen ("test"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); if(SQL_SUCCEEDED(ret)) { printf("\nConnected to the Data Source..\n"); } else { printf("error in connection\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); return 1; } //****************************************************************** // TABLE CREATED ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt); checkrc(ret,__LINE__); SQLCHAR table[200]= "CREATE TABLE T1(F1 INT,F2 INT)"; // ret = SQLPrepare(stmt,table,SQL_NTS); // checkrc(ret,__LINE__); ret = SQLExecute(stmt); int rettype = ret; if(ret) printf("Table creation failed\n"); else printf("\nTABLE CREATED\n"); //**************************************************************** //**************************************************************** ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt); checkrc(ret,__LINE__); ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); if(rettype == 0)return 1; return 0; }
//--------------------------------------------------------- // TestSQLAllocStmt() //--------------------------------------------------------- PassFail TestSQLAllocStmt (TestInfo *pTestInfo, int MX_MP_SPECIFIC) { TEST_DECLARE; char Heading[MAX_STRING_SIZE]; RETCODE returncode; SQLHANDLE henv; SQLHANDLE hdbc; SQLHANDLE hstmt[NUM_STMT]; //RETCODE AsyncStmt[NUM_ASYNC_STMT]; char *StmtHndlStr; int i = 0, j = 0, k = 0; int AnyAsync; int AsyncOper[] = {CREATE_TABLE,INSERT_TABLE,SELECT_TABLE,DROP_TABLE,999}; char *teststmthndl[21]; //=========================================================================================================== var_list_t *var_list; var_list = load_api_vars("SQLAllocateStatement", charset_file); if (var_list == NULL) return FAILED; teststmthndl[0] = var_mapping("TestStmtHndl_0", var_list); teststmthndl[1] = var_mapping("TestStmtHndl_1", var_list); teststmthndl[2] = var_mapping("TestStmtHndl_2", var_list); teststmthndl[3] = var_mapping("TestStmtHndl_3", var_list); teststmthndl[4] = var_mapping("TestStmtHndl_4", var_list); teststmthndl[5] = var_mapping("TestStmtHndl_5", var_list); teststmthndl[6] = var_mapping("TestStmtHndl_6", var_list); teststmthndl[7] = var_mapping("TestStmtHndl_7", var_list); teststmthndl[8] = var_mapping("TestStmtHndl_8", var_list); teststmthndl[9] = var_mapping("TestStmtHndl_9", var_list); teststmthndl[10] = var_mapping("TestStmtHndl_10", var_list); teststmthndl[11] = var_mapping("TestStmtHndl_11", var_list); teststmthndl[12] = var_mapping("TestStmtHndl_12", var_list); teststmthndl[13] = var_mapping("TestStmtHndl_13", var_list); teststmthndl[14] = var_mapping("TestStmtHndl_14", var_list); teststmthndl[15] = var_mapping("TestStmtHndl_15", var_list); teststmthndl[16] = var_mapping("TestStmtHndl_16", var_list); teststmthndl[17] = var_mapping("TestStmtHndl_17", var_list); teststmthndl[18] = var_mapping("TestStmtHndl_18", var_list); teststmthndl[19] = var_mapping("TestStmtHndl_19", var_list); teststmthndl[20] = var_mapping("TestStmtHndl_20", var_list); //====================================================================================== if (MX_MP_SPECIFIC == MX_SPECIFIC) LogMsg(LINEBEFORE+SHORTTIMESTAMP,"Begin testing API => MX specific SQLAllocStmt | SQLAllocStmt | alocstmt.c\n"); else LogMsg(LINEBEFORE+SHORTTIMESTAMP,"Begin testing API => MP specific SQLAllocStmt | SQLAllocStmt | alocstmt.c\n"); TEST_INIT; TESTCASE_BEGIN("Setup for SQLAllocStmt/SQLFreeStmt tests\n"); /* 6-5-00: Need to turn Autocommit off since MX will close all open cursors that are open if the end of ANY of the cursors is reached. */ if(!FullConnectWithOptions(pTestInfo, CONNECT_ODBC_VERSION_2)) { LogMsg(NONE,"Unable to connect\n"); TEST_FAILED; TEST_RETURN; } henv = pTestInfo->henv; hdbc = pTestInfo->hdbc; //set the connection attribute to SQL_AUTOCOMMIT_OFF to enable use of multiple stmt without errors SQLSetConnectAttr((SQLHANDLE)hdbc, SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, SQL_IS_UINTEGER); TESTCASE_END; // end of setup StmtHndlStr = (char *)malloc(MAX_NOS_SIZE); //==================================================================================================== // General statement handle exercise testcases. for (k = 0; k < 2; k++) { for (i = 0; i < NUM_STMT; i++) { hstmt[i] = (SQLHANDLE)pTestInfo->hstmt; sprintf(Heading,"SQLAllocstmt: Test #%d\n",i); TESTCASE_BEGIN(Heading); returncode = SQLAllocStmt((SQLHANDLE)hdbc, &hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; if (returncode == SQL_SUCCESS) { if (i == 0) // cleanup { for (j = 0; j < NUM_STMT; j++) { SQLExecDirect(hstmt[0],StmtQueries(DROP_TABLE,teststmthndl[j],StmtHndlStr),SQL_NTS); } } sprintf(Heading,"SQLAllocStmt: create table teststmthndl%d\n",i+1); TESTCASE_BEGIN(Heading); if (k == 0) // prepare & execute { returncode = SQLPrepare(hstmt[i],StmtQueries(CREATE_TABLE,teststmthndl[i],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLPrepare")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } else{ returncode = SQLExecute(hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecute")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } } else // execdirect { returncode = SQLExecDirect(hstmt[i],StmtQueries(CREATE_TABLE,teststmthndl[i],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } } if (returncode == SQL_SUCCESS) TESTCASE_END; } for (i = 0; i < NUM_STMT; i++) { sprintf(Heading,"SQLAllocStmt: inserts on Stmt Handle(%d)\n",i); TESTCASE_BEGIN(Heading); if (k == 0) // prepare & execute { returncode = SQLPrepare(hstmt[i],StmtQueries(INSERT_TABLE,teststmthndl[i],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLPrepare")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } else { returncode = SQLExecute(hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecute")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } } else // execdirect { returncode = SQLExecDirect(hstmt[i],StmtQueries(INSERT_TABLE,teststmthndl[i],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } if (returncode == SQL_SUCCESS)TESTCASE_END; } for (i = 0; i < NUM_STMT; i++) { sprintf(Heading,"SQLAllocStmt: selects on Stmt Handle(%d)\n",i); TESTCASE_BEGIN(Heading); if (k == 0) // prepare & execute { returncode = SQLPrepare(hstmt[i],StmtQueries(SELECT_TABLE,teststmthndl[i],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLPrepare")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } else{ returncode = SQLExecute(hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecute")){ TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } } else // execdirect { returncode = SQLExecDirect(hstmt[i],StmtQueries(SELECT_TABLE,teststmthndl[i],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } if (returncode == SQL_SUCCESS) TESTCASE_END; } for (i = (NUM_STMT-1); i > -1; i--) { sprintf(Heading,"SQLAllocStmt: fetches on selects on Stmt Handle(%d)\n",i); TESTCASE_BEGIN(Heading); returncode = SQLFetch(hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFetch")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } if (returncode == SQL_SUCCESS) TESTCASE_END; } for (i = 0; i < NUM_STMT; i++) { sprintf(Heading,"SQLAllocStmt: SQLFreeStmt(%d) with SQL_CLOSE\n",i); TESTCASE_BEGIN(Heading); returncode = SQLFreeStmt(hstmt[i],SQL_CLOSE); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } else{ TESTCASE_END; } if (i == (NUM_STMT-1)) // cleanup { for (j = 0; j < NUM_STMT; j++) { SQLExecDirect(hstmt[0],StmtQueries(DROP_TABLE,teststmthndl[j],StmtHndlStr),SQL_NTS); } } } for (i = 0; i < NUM_STMT; i++) { sprintf(Heading,"SQLAllocStmt: SQLFreeStmt(%d) with SQL_DROP\n",i); TESTCASE_BEGIN(Heading); returncode = SQLFreeStmt(hstmt[i],SQL_DROP); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } else{ TESTCASE_END; } } sprintf(Heading,"SLQAllocStmt: same sql operations on different of SQLAllocstmt(%d)s\n",i); TESTCASE_BEGIN(Heading); for (i = 0; i < NUM_STMT; i++) { hstmt[i] = (SQLHANDLE)pTestInfo->hstmt; returncode = SQLAllocStmt((SQLHANDLE)hdbc, &hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } if (returncode == SQL_SUCCESS) { if (i == 0) // cleanup { SQLExecDirect(hstmt[0],StmtQueries(DROP_TABLE,teststmthndl[20],StmtHndlStr),SQL_NTS); returncode = SQLExecDirect(hstmt[0],StmtQueries(CREATE_TABLE,teststmthndl[20],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[0]); } } if (k == 0) // prepare & execute { returncode = SQLPrepare(hstmt[i],StmtQueries(INSERT_TABLE,teststmthndl[20],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLPrepare")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } returncode = SQLExecute(hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecute")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } else // execdirect { returncode = SQLExecDirect(hstmt[i],StmtQueries(INSERT_TABLE,teststmthndl[20],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } if (k == 0) // prepare & execute { returncode = SQLPrepare(hstmt[i],StmtQueries(SELECT_TABLE,teststmthndl[20],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLPrepare")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } returncode = SQLExecute(hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecute")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } else { returncode = SQLExecDirect(hstmt[i],StmtQueries(SELECT_TABLE,teststmthndl[20],StmtHndlStr),SQL_NTS); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLExecDirect")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } returncode = SQLFetch(hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFetch")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } } for (i = 0; i < NUM_STMT; i++) { returncode = SQLFreeStmt(hstmt[i],SQL_CLOSE); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } if (i == 0) { SQLExecDirect(hstmt[0],StmtQueries(DROP_TABLE,teststmthndl[20],StmtHndlStr),SQL_NTS); } returncode = SQLFreeStmt(hstmt[i],SQL_DROP); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } TESTCASE_END; } //==================================================================================================== // Asynchronus Testcases if (MX_MP_SPECIFIC == MX_SPECIFIC) { for (i = 0; i < NUM_ASYNC_STMT; i++) { hstmt[i] = (SQLHANDLE)pTestInfo->hstmt; // Creating statement handles sprintf(Heading,"SQLAllocstmt: Test #%d and Enable the ASYNC MODE ON.\n",i); TESTCASE_BEGIN(Heading); returncode = SQLAllocStmt((SQLHANDLE)hdbc, &hstmt[i]); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLAllocStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } else { if (i == 0) // cleanup { // Creating tables to be used by each of the stmt handles for (j = 0; j < NUM_ASYNC_STMT; j++) { SQLExecDirect(hstmt[0],StmtQueries(DROP_TABLE,teststmthndl[j],StmtHndlStr),SQL_NTS); } } // Putting each stmthandle into Asynchronus mode returncode = SQLSetStmtOption(hstmt[i],SQL_ASYNC_ENABLE,SQL_ASYNC_ENABLE_ON); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLSetStmtOptions")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } } TESTCASE_END; } // Running the Asynchronus tests // WHAT IS GOING ON // Two tests cases are being checked: // 1. That the status of an asynchronus stmt handle CAN be checked. // 2. That the stmt handle completes correctly. // // HOW IT'S BEING RUN // Steps being performed until all handles are no longer executing: // 1. Prepare the async test data structure. // 2. Generate table name based on statement handle being used. // 3. If handle's status has not been checked already, check as test case 1. // Else, check it's status NOT as a test case. // 4. Run the statement (also used to check the status of the handle). // 5. If the stmt completes, verify that it does so successfully. Test case 2. // // Once all of the handles have completed, perform the next Async Operation // until the terminating operation (a.k.a "999") is reached. k = 0; while (AsyncOper[k] != 999) { // 1. Preparing the async test data structure for (i = 0; i < NUM_ASYNC_STMT; i++) { AsyncStmt[i].status = SQL_STILL_EXECUTING; AsyncStmt[i].checked = FALSE; } AnyAsync = 1; // Testing begins while (AnyAsync > 0) { for (i = 0; i < NUM_ASYNC_STMT; i++) { if (AsyncStmt[i].status == SQL_STILL_EXECUTING) { // 3. Has the handle been checked for its status? if (AsyncStmt[i].checked) { // 4. Run the statement. returncode = SQLExecDirect(hstmt[i],StmtQueries(AsyncOper[k],teststmthndl[i],StmtHndlStr),SQL_NTS); AsyncStmt[i].status = returncode; // 5. Result Test: Verifying that the statement completes correctly. if (returncode != SQL_STILL_EXECUTING) { sprintf(Heading,"SQLAllocStmt: Result Test: %d; SQLStmt: %s.\n",i,StmtQueries(AsyncOper[k],teststmthndl[i],StmtHndlStr)); TESTCASE_BEGIN(Heading); if (returncode != SQL_SUCCESS) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; } } else { // Status Test (Test case 1): // Only EXECUTING and SUCCESS are acceptable, others are errors. // This test is only run once! sprintf(Heading,"SQLAllocStmt: Status Test: %d; SQLStmt: %s.\n",i,StmtQueries(AsyncOper[k],teststmthndl[i],StmtHndlStr)); TESTCASE_BEGIN(Heading); // 4. Run the statement. returncode = SQLExecDirect(hstmt[i],StmtQueries(AsyncOper[k],teststmthndl[i],StmtHndlStr),SQL_NTS); AsyncStmt[i].status = returncode; AsyncStmt[i].checked = TRUE; if ((returncode != SQL_STILL_EXECUTING) && (returncode != SQL_SUCCESS)) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; // 5. If the stmt completes, verify that it does so successfully. if (returncode != SQL_STILL_EXECUTING) { // Result Test: Verifying that the stmt completes successfully. sprintf(Heading,"SQLAllocStmt: Result Test: %d; SQLStmt: %s.\n",i,StmtQueries(AsyncOper[k],teststmthndl[i],StmtHndlStr)); TESTCASE_BEGIN(Heading); if (returncode != SQL_SUCCESS) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; } //Sleep (500); } } } AnyAsync = 0; for (i = 0; i < NUM_ASYNC_STMT; i++) { if (AsyncStmt[i].status == SQL_STILL_EXECUTING) { AnyAsync = AnyAsync + 1; } } } // Special tests for Fetching after doing a SELECT // Steps are identical to the above steps. if (AsyncOper[k] == SELECT_TABLE) { // Preparing data structure for (i = 0; i < NUM_ASYNC_STMT; i++) { AsyncStmt[i].status = SQL_STILL_EXECUTING; AsyncStmt[i].checked = FALSE; } AnyAsync = 1; // Select testing begins while (AnyAsync > 0) { for (i = 0; i < NUM_ASYNC_STMT; i++) { if (AsyncStmt[i].status == SQL_STILL_EXECUTING) { if (AsyncStmt[i].checked) { returncode = SQLFetch(hstmt[i]); AsyncStmt[i].status = returncode; if (returncode != SQL_STILL_EXECUTING) { // Result Test sprintf(Heading,"SQLAllocStmt: Result Test:%d; performing SQLFetch.\n",i); TESTCASE_BEGIN(Heading); if (returncode != SQL_SUCCESS) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; } } else { // Status Test sprintf(Heading,"SQLAllocStmt: Status Test:%d; performing SQLFetch.\n",i); TESTCASE_BEGIN(Heading); returncode = SQLFetch(hstmt[i]); AsyncStmt[i].status = returncode; AsyncStmt[i].checked = TRUE; if ((returncode != SQL_STILL_EXECUTING) && (returncode != SQL_SUCCESS)) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; // Result Test if (returncode != SQL_STILL_EXECUTING) { sprintf(Heading,"SQLAllocStmt: Result Test:%d; performing SQLFetch.\n",i); TESTCASE_BEGIN(Heading); if (returncode != SQL_SUCCESS) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; } } } } AnyAsync = 0; for (i = 0; i < NUM_ASYNC_STMT; i++) { if (AsyncStmt[i].status == SQL_STILL_EXECUTING) { AnyAsync = AnyAsync + 1; } } } // Closing the cursor from the SELECT stmt result set. for (i = 0; i < NUM_ASYNC_STMT; i++) { sprintf(Heading,"SQLFreeStmt: %d.\n",i); TESTCASE_BEGIN(Heading); returncode = SQLFreeStmt(hstmt[i],SQL_CLOSE); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFreeStmt")) { TEST_FAILED; LogAllErrors(henv,hdbc,hstmt[i]); } TESTCASE_END; } } // End of async SELECT test. // Resetting the checked status for the next operation. for (i = 0; i < NUM_ASYNC_STMT; i++) { AsyncStmt[i].checked = FALSE; } k++; } } //==================================================================================================== free(StmtHndlStr); returncode = SQLDisconnect((SQLHANDLE)hdbc); if(!CHECKRC(SQL_ERROR,returncode,"SQLDisconnect")) { TEST_FAILED; LogAllErrorsVer3(henv,hdbc,hstmt[0]); } // Free the open transactions. returncode=SQLTransact((SQLHANDLE)henv,(SQLHANDLE)hdbc,SQL_ROLLBACK); Sleep(2); returncode=FullDisconnect(pTestInfo); if(!CHECKRC(SQL_SUCCESS,returncode,"SQLFullDisconnect")) { TEST_FAILED; LogAllErrorsVer3(henv,hdbc,hstmt[0]); } LogMsg(SHORTTIMESTAMP+LINEAFTER,"End testing API => SQLAllocStmt.\n"); free_list(var_list); TEST_RETURN; }
//************************************************************************* int main() { SQLHENV env; SQLHDBC dbc; SQLHSTMT stmt; SQLRETURN ret; SQLCHAR outstr[1024]; SQLSMALLINT outstrlen; // Aloocate an environment handle ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env); checkrc(ret,__LINE__); //we need odbc3 support SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0); //ALLOCATE A Connection handle ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc); checkrc(ret,__LINE__); // connect to the Data source ret = SQLConnect (dbc, (SQLCHAR *) "DSN=mycsql;MODE=GATEWAY;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=GATEWAY;SERVER=127.0.0.1;PORT=5678;"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); if(SQL_SUCCEEDED(ret)) { printf("\nConnected to the Data Source..\n"); } else { printf("error in connection\n"); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_DBC,env); checkrc(ret,__LINE__); return 1; } //********************************************************************* //again call to driver connect ret = SQLConnect (dbc, (SQLCHAR *) "DSN=mycsql;MODE=GATEWAY;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=GATEWAY;SERVER=127.0.0.1;PORT=5678;"), (SQLCHAR *) "root", (SQLSMALLINT) strlen ("root"), (SQLCHAR *) "manager", (SQLSMALLINT) strlen ("")); int rettype = ret; if(SQL_SUCCEEDED(ret)) { printf("\nConnected to the Data Source..\n"); } else { printf("Connection name in use\n"); } //********************************************************************** ret = SQLDisconnect(dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc); checkrc(ret,__LINE__); ret = SQLFreeHandle(SQL_HANDLE_ENV,env); checkrc(ret,__LINE__); if(rettype ==0)return 1; return 0; }