//through the product info get the best channel to create order //@return the channel num int ChargeBusiness::SelectBestChannel(int value, int province, int op, vector<ChannelInfo>& channels){ int ret = 0; Statement *stmt = NULL; try{ stmt = conn->createStatement(SQL_SELECT_CHANNEL); stmt->setInt(1, value); //product value stmt->setInt(2, province); //provice of product stmt->setInt(3, op); //operator of product ResultSet *rs = stmt->executeQuery(); while(rs->next()) { ChannelInfo channel; channel.channelId = rs->getInt(1); //channel id //channel.channelName = rs->getString(2); //channel name channel.sname = rs->getString(2); //short name channel.priority = rs->getInt(3); //priority channel.repeat = rs->getInt(4); //repeat times channel.discount = rs->getFloat(5); //discount of product channel.interfaceName = rs->getString(6); //the interface of channel,through it to find the class to handle order channel.pid = rs->getString(7); //the product id given by channel channel.private_key = rs->getString(8); //the private key given by channel channel.query_interval = rs->getInt(9); //query order interval channels.push_back(channel); ret++; } stmt->closeResultSet(rs); }catch(std::exception &e){ HandleException(e); ret = -1; } Finish(); if(stmt) conn->terminateStatement(stmt); return ret; }
bool TEST_CONNECTION(){ GlobalConfig *gconf = GlobalConfig::Instance(); if(gconf == NULL || !gconf->Init("../conf/topup.ini")){ exit(EXIT_FAILURE); } ConnectionManager* conn_manager = ConnectionManager::Instance(); printf("user:%s\tpasswd:%s\n", gconf->s_db_userName.c_str(), gconf->s_db_passWord.c_str()); if(conn_manager == NULL || !conn_manager->Init(gconf->s_db_userName, gconf->s_db_passWord, gconf->s_db_connString, gconf->n_max_connection, gconf->n_min_connection, gconf->n_inc_connection)){ exit(EXIT_FAILURE); } Connection *conn = conn_manager->CreateConnection(); Statement *stmt = conn->createStatement("SELECT ID,ZONE,VALUE,OPERATOR FROM PRODUCT_TBL WHERE ID = :1 AND STATUS != 3"); stmt->setString(1, "10001"); ResultSet *rs = stmt->executeQuery(); while (rs->next()) { string id = rs->getString(1); cout << id << endl; } stmt->closeResultSet(rs); conn->terminateStatement(stmt); return true; }
///ret = 2 no such product ///ret = 1 exception not find product int ChargeBusiness::GetTmallProduct(string productId, Product &product){ int ret = 0; Statement *stmt = NULL; try{ //初始化数据库连接 stmt = conn->createStatement(SQL_QUERY_PRODUCT); stmt->setString(1, productId); ResultSet *rs = stmt->executeQuery(); while (rs->next()) { product.productId = rs->getString(1); product.provinceId = rs->getInt(2); product.price = rs->getInt(3); product.op = rs->getInt(4); } stmt->closeResultSet(rs); if(product.productId.empty() || product.provinceId == 0){ ret = 2; } } catch(std::exception &e) { HandleException(e); ret = 1; } Finish(); if(stmt) conn->terminateStatement(stmt); return ret; }
/** * The testing logic of the test case. */ dvoid select () { cout << "occipool - Selecting records using ConnectionPool interface" << endl; const string poolUserName = "******"; const string poolPassword = "******"; const string connectString = ""; const string username = "******"; const string passWord = "******"; unsigned int maxConn = 5; unsigned int minConn = 3; unsigned int incrConn = 2; ConnectionPool *connPool; try{ connPool = env->createConnectionPool (poolUserName, poolPassword, connectString, minConn, maxConn, incrConn); if (connPool) cout << "SUCCESS - createConnectionPool" << endl; else cout << "FAILURE - createConnectionPool" << endl; con = connPool->createConnection (username, passWord); if (con) cout << "SUCCESS - createConnection" << endl; else cout << "FAILURE - createConnection" << endl; }catch(SQLException ex) { cout<<"Exception thrown for createConnectionPool"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; return; } cout << "retrieving the data" << endl; try{ stmt = con->createStatement ("SELECT author_id, author_name FROM author_tab"); ResultSet *rset = stmt->executeQuery(); while (rset->next()) { cout << "author_id:" << rset->getInt (1) << endl; cout << "author_name:" << rset->getString (2) << endl; } stmt->closeResultSet (rset); con->terminateStatement (stmt); connPool->terminateConnection (con); env->terminateConnectionPool (connPool); }catch(SQLException ex) { cout<<"Exception thrown for retrieving data"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } cout << "occipool - done" << endl; } // end of test (Connection *)
int BillingInstance::queryStaticIP(std::string ip, std::string server, queryResult &_rv) { if(_conn == NULL) { return 0; } int retval = 0; Statement *sth = NULL; try { sth = _conn->createStatement(QUERY_STATIC_IP); sth->setAutoCommit(true); sth->setString(1, ip); sth->setString(2, server); std::cerr << "Query execute" << std::endl; ResultSet *rs = sth->executeQuery(); const std::vector<MetaData> md = rs->getColumnListMetaData(); if(rs) { while( rs->next() ) { std::multimap<std::string, std::string> tmp; tmp.clear(); for(int i=0; i < md.size(); ++i) { tmp.insert(std::pair<std::string, std::string>(md.at(i).getString(MetaData::ATTR_NAME), rs->getString(i+1))); } _rv.push_back(tmp); } } sth->closeResultSet(rs); retval = 0; } catch (SQLException &sqlExcp) { std::cerr <<sqlExcp.getErrorCode() << " at " << __FILE__ << "/" << __LINE__ << ": " << sqlExcp.getMessage() << std::endl; retval = sqlExcp.getErrorCode(); } if(sth != NULL) { try { _conn->terminateStatement(sth); } catch (SQLException &sqlExcp) { std::cerr <<sqlExcp.getErrorCode() << " at " << __FILE__ << "/" << __LINE__ << ": " << sqlExcp.getMessage() << std::endl; retval = sqlExcp.getErrorCode(); } } return retval; }
void Student::List() { Statement *stmt = NULL; ResultSet *rs = NULL; string sql = "select * from sql_test_table"; try { stmt = conn->createStatement(sql); } catch (SQLException &e) { cout << e.getMessage(); } if (stmt) { try { rs = stmt->executeQuery(); } catch (SQLException &e) { cout << e.getMessage(); } if (rs) { cout << endl << setw(3) << left <<"ID" << setw(6) << left << "NAME" << setw(8) << left << "DEFINITION" << endl; cout << "===================" << endl; while (rs->next()) { cout << setw(3) << left << rs->getInt(1) << setw(6) << left << rs->getString(2) << setw(8) << left << rs->getString(3) << endl; } cout << "===================" << endl; cout << endl; stmt->closeResultSet(rs); } conn->terminateStatement(stmt); } }
/** * displaying all the rows in the table */ void displayAllRows () { string sqlStmt = "SELECT author_id, author_name FROM author_tab \ order by author_id"; stmt = conn->createStatement (sqlStmt); ResultSet *rset = stmt->executeQuery (); try{ while (rset->next ()) { cout << "author_id: " << rset->getInt (1) << " author_name: " << rset->getString (2) << endl; } }catch(SQLException ex) { cout<<"Exception thrown for displayAllRows"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } stmt->closeResultSet (rset); conn->terminateStatement (stmt); }
/** * displaying rows from element table */ void displayElements () { string sqlStmt = "SELECT element_name, molar_volume, atomic_weight FROM elements \ order by element_name"; stmt = conn->createStatement (sqlStmt); ResultSet *rset = stmt->executeQuery (); try{ cout.precision(7); while (rset->next ()) { string elem_name = rset->getString(1); BFloat mol_vol = rset->getBFloat(2); BDouble at_wt = rset->getBDouble(3); cout << "Element Name: " << elem_name << endl; if ( mol_vol.isNull ) cout << "Molar Volume is NULL" << endl; else cout << "Molar Volume: " << mol_vol.value << " cm3 mol-1" << endl; if ( at_wt.isNull ) cout << "Atomic Weight is NULL" << endl; else cout << "Atomic Weight: " << at_wt.value << " g/mole" << endl; } }catch(SQLException ex) { cout<<"Exception thrown for displayElements"<<endl; cout<<"Error number: "<< ex.getErrorCode() << endl; cout<<ex.getMessage() << endl; } stmt->closeResultSet (rset); conn->terminateStatement (stmt); }
int main(int argc, char **argv) { if (argc != 6) { Usage(); return 0; } bool bPrint = false; if (strcmp(argv[1], "-p") == 0) { bPrint = true; } struct timeval tv_start, tv_end; gettimeofday(&tv_start, NULL); // create Environment Environment *env = Environment::createEnvironment(); if (env == NULL) { cout << "createEnvironment failed!" << endl; return -1; } // use the Environment instance to create connections; Connection *conn = env->createConnection(argv[2], argv[3], argv[4]); if (conn == NULL) { cout << "createConnection failed!" << endl; return -1; } // use Statement to execute sql and get result Statement *stmt = conn->createStatement(argv[5]); if (stmt == NULL) { cout << "createStatement failed!" << endl; return -1; } // execute sql and get result set ResultSet *rs = stmt->executeQuery(); if (rs == NULL) { cout << "executeQuery failed!" << endl; return -1; } // ResultSet::next() fetch rows and return FALSE // when no more rows int nColumns; long long llCount = 0; string strTemp; vector<MetaData> vecColumns = rs->getColumnListMetaData(); nColumns = vecColumns.size(); while (rs->next() == true) { // get values using the getXXX() methods of Resultset for (int i = 0; i < nColumns; ++i) { strTemp = rs->getString(i + 1); if (bPrint) { cout << strTemp << "\t"; } } if (bPrint) { cout << endl; } ++llCount; } // close result stmt->closeResultSet(rs); // close statement conn->terminateStatement(stmt); // close connection env->terminateConnection(conn); // close Environment Environment::terminateEnvironment(env); gettimeofday(&tv_end, NULL); long long llUsed = (tv_end.tv_sec - tv_start.tv_sec) * 1000000 + tv_end.tv_usec - tv_start.tv_usec; cout << "read data " << llCount << " used " << llUsed / 1000000.0 << " sec." << endl; return 0; }
int _tmain(int argc, _TCHAR* argv[]) { const char* userName = "******"; const char* password = "******"; const char* connectString = "(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=tcp)(HOST=80.67.144.206)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=XE)))"; const char* sql = "SELECT * FROM ALL_TABLES"; int i = 0; int rows = 0; try { Environment *env = Environment::createEnvironment(Environment::THREADED_MUTEXED); cout << "createEnvironment" << endl; Connection *conn = env->createConnection((char*)userName, (char*)password, (char*)connectString); cout << " createConnection" << endl; for (i=100; i>0; --i) { Statement *stmt = conn->createStatement(sql); cout << " createStatement" << endl; ResultSet *rs = stmt->executeQuery(); cout << " executeQuery" << endl; #if 0 vector<MetaData> listOfColumns = rs->getColumnListMetaData(); cout << " getColumnListMetaData" << endl; cout << i << " columns " << listOfColumns.size() << endl; for (i=0; i < listOfColumns.size(); i++) { MetaData columnObj=listOfColumns[i]; //cout << (columnObj.getString(MetaData::ATTR_NAME)) // << "(" << (columnObj.getInt(MetaData::ATTR_DATA_TYPE)) << "), "; } #endif rows = 0; while(rs->next()) { ++rows; /*for (i=0; i < listOfColumns.size(); i++) string str = rs->getString(i+1); //cout << rs->getString(j+1) << ", "; //cout << endl;*/ } cout << " itr " << i << " rows " << rows << endl; stmt->closeResultSet(rs); cout << " closeResultSet" << endl; conn->terminateStatement(stmt); cout << " terminateStatement" << endl; } env->terminateConnection(conn); cout << " terminateConnection" << endl; Environment::terminateEnvironment(env); cout << "terminateEnvironment" << endl; } catch (std::exception const & ex) { cout << ex.what() << endl; } catch (std::string const & ex) { cout << ex << endl; } catch (...) { // ... } return 0; }
int main() { cout << "***OCCI Globalization Support demo program.***" << endl; cout << "***This program loads Unicode data files into a NClob attribute***" << endl; char *unicodefiles[4] = {"occiuni2_hindi.txt", "occiuni2_russian.txt", "occiuni2_korean.txt", "occiuni2_japanese.txt"}; try { cout << "Initializing OCCI environment in Unicode mode" << endl; //initialize in Unicode(UTF16) mode Environment *utf16env = Environment::createEnvironment( "OCCIUTF16", "OCCIUTF16", Environment::OBJECT ); occiuni2m(utf16env); //"L" prefix will create a widechar i.e Unicode literal which is equivalent to // OCCI's UString datatype Connection *conn = utf16env->createConnection( L"hr",L"hr",L"" ); //load the 4 sample Unicode files for (int i = 0; i < 4;i++) { //convert the filename argument to Unicode. We will be saving the filename //as one of the attributes of the object. const char *asciifilename = unicodefiles[i]; wchar_t wcfilename[100]; MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, (LPCSTR)asciifilename, strlen(asciifilename)+1, (LPWSTR)wcfilename, 100 ); wstring docname(wcfilename); cout << "Loading " << asciifilename << endl; //Create a persistent object, set the NClob to empty and save //the object. Use the overloaded new operator that takes UString //arugments DocObjType *newdoc = new (conn, L"DOCUMENTSTAB",L"DOCOBJTYPE", L"HR",L"HR") DocObjType(); newdoc->setDocname(docname); //first insert a empty clob Clob doccontents(conn); doccontents.setEmpty(); newdoc->setDoctext(doccontents);//empty conn->commit(); //Now, we will select the object again and add the document text //to the NClob attribute. Statement *stmt = conn->createStatement( L"select ref(a) from documentstab a where docname = :1 for update"); stmt->setUString(1, docname);//bind wstring ResultSet *rs = stmt->executeQuery(); rs->next();//this will actually fetch the Ref Ref<DocObjType> docobjref = rs->getRef(1); DocObjType *docobj = docobjref.ptr();//pin the object doccontents = docobj->getDoctext();//get the Clob doccontents.open(); doccontents.setCharSetId("OCCIUTF16"); doccontents.setCharSetForm(OCCI_SQLCS_NCHAR); ifstream in( asciifilename, ios::binary ); int bytesread=0, totalbytesread=0, wcharsread=0; wchar_t wbuffer1[50];//50 chars = 100 bytes at a time //we have stored the data in a Unicode text file. The first //character (2 bytes) is a Unicode Byte-Order-Mark and //indicates whether the data in the file is little-endian or //big-endian in.read((char *)wbuffer1,2);//read & skip BOM int offset = 1; while (in.read( (char *)wbuffer1,sizeof(wbuffer1) )) { bytesread = in.gcount(); wcharsread = bytesread/2; //write to the NClob doccontents.writeChunk( wcharsread, (utext *)wbuffer1, sizeof(wbuffer1), offset ); offset += wcharsread;//offset is in terms of characters totalbytesread += bytesread; } //last chunk bytesread = in.gcount(); wcharsread = bytesread/2; totalbytesread += bytesread; doccontents.writeChunk( wcharsread, (utext *)wbuffer1, bytesread, offset ); doccontents.close(); //update the object and flush to database docobj->setDoctext(doccontents); docobj->markModified(); docobj->flush(); conn->commit(); cout << totalbytesread/2 << " characters saved" << endl; //Statement & ResultSet objects will be created again stmt->closeResultSet(rs); conn->terminateStatement(stmt); }//for (i = 0; i < 4) cout << "Now reading the NClob data back and saving to new files" << endl; Statement *selectstmt = conn->createStatement( L"select ref(a) from DocumentsTab a" ); ResultSet *queryrs = selectstmt->executeQuery(); wstring wfilehdrtxt = L"If you cannot see the text properly, try setting your font to a Unicode font like : - Arial Unicode MS, Lucinda Sans Unicode etc..."; while (queryrs->next()) { Ref<DocObjType> docobjref = queryrs->getRef(1); wstring docname = docobjref->getDocname(); //create the output file, prepend "fetch_" to the original filename docname = L"fetch_" + docname; char asciifilenamebuf[100]; int ret = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)docname.c_str(), docname.length()+1, (LPSTR)asciifilenamebuf, 100, NULL, NULL); cout << "Creating Unicode textfile " << asciifilenamebuf << endl; ofstream outdoc(asciifilenamebuf, ios_base::binary | ios_base::trunc); //first write the BOM wchar_t bom = 0xFEFF;//Windows is little-endian outdoc.write((char *)&bom, 2); outdoc.write((char *)wfilehdrtxt.c_str(), wfilehdrtxt.length()*2); Clob doccontents = docobjref->getDoctext(); doccontents.setCharSetId("OCCIUTF16"); doccontents.setCharSetForm(OCCI_SQLCS_NCHAR); int offset = 1; int clobcharsread=0; //now read the NClob and write to file wchar_t wbuffer2[100];//100 chars at a time while ( (clobcharsread = doccontents.read(100, wbuffer2, sizeof(wbuffer2), offset)) !=0 ) { offset = offset+clobcharsread; outdoc.write((char *)wbuffer2,clobcharsread*2);//write takes number of bytes } outdoc.close(); }//while (queryrs->next()) //done cout << "You can view the created files in Notepad(or any other editor that displays Unicode)" << endl; selectstmt->closeResultSet(queryrs); conn->terminateStatement(selectstmt); //delete the rows from the table //if you want to retain the rows, comment out cout << "Cleaning up table" << endl; Statement *deletestmt = conn->createStatement( L"delete from DocumentsTab"); deletestmt->executeUpdate(); conn->commit(); utf16env->terminateConnection(conn); Environment::terminateEnvironment(utf16env); cout << "Done" << endl; } catch (SQLException &e) { std::cout << e.getErrorCode() << std::endl; } return 0; }
int main(ub4 argc, char* argv[]) { Environment* env; Connection* conn; try { // Connect String (database variable) should be // failover configured for TAF to work correctly. string userName = "******"; string password = "******"; string database = "rnd.solbrain.co.kr/ora"; // Example of Failover Configured String: This should be the way // the connect string should be configured for failover. // mydb = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname)\ // (PORT=portno))(CONNECT_DATA=(SERVICE_NAME=svcname) // (FAILOVER_MODE=(TYPE=SELECT)(METHOD=BASIC)))) // Creating the OCCI Environment and Creating a // connection to the Scott User cout << "OCCI Demo Of TAF" << endl; env = Environment::createEnvironment(Environment::DEFAULT); conn = env->createConnection(userName,password,database); cout << "OCCI Environment and Connection Created " << endl; // Registering the Connection for TAF Callback. cout << "Registering the Connection with the TAF Callback" << endl; conn->setTAFNotify(taf_callback, NULL); } catch (SQLException &e) { cout << "Error in Constructor Call " << endl; cout << "Error Number: " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } try { string sql("select empno, ename from emp order by empno"); Statement *stmt = conn->createStatement(sql); cout << "Selecting Records from Emp Table " << endl; ResultSet *rs = stmt->executeQuery(); // The logic is as follows. // A select statement is issued to the server. After 2 records are // fetched the server is bounced. This triggers the failover // and the rest of the records are fetched after the failover for (int i=0; i<2; i++) { rs->next(); cout <<"Emp No :" << rs->getInt(1) << endl; cout <<"Emp Name :" << rs->getString(2) << endl; } cout << "Fetched Partial Number of Records " << endl; cout << "Performing Failover" << endl; // The callback gets called whenever the failover is // attemped for this connection since the callback is // registered with the connection. // Hence if the application tries to fail over even before // the instance is brought up the failover would be attempted // and callback called and FO_ERROR would be raised. // In the callback whenever an FO_ERROR is recieved, FO_RETRY is sent. // The failover would be attempted until the instance is // actually brought up which is when FO_END would be signalled // and the failover would succeed cout << "Bounce the Server" << endl; cout << "Once the Server is brought up. Press any key to continue" << endl; fflush(stdin); int ch = getchar(); try { cout << "Connection About to Fail Over" << endl; while (rs->next()) { cout <<"Emp No :" << rs->getInt(1) << endl; cout <<"Emp No :" << rs->getString(1) << endl; cout <<"Emp Name :" << rs->getString(2) << endl; } cout << "Selected All Rows after failover" << endl; } catch (SQLException &e) { cout << "Error during Selecting rest of the rows" << endl; cout << "Error Number: " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } stmt->closeResultSet(rs); conn->terminateStatement(stmt); } catch (SQLException &e) { cout << "Exception " << endl; cout << "Error Number: " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } // Terminating the Connection and the OCCI Environment cout << "Terminating the Connection and The Environment" << endl; env->terminateConnection(conn); Environment::terminateEnvironment(env); cout << "Demo Done" << endl; }