Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
4.20/5 (2 votes)
See more:
How do I use and execute queries on databases in my native C++ windows application. Especially on MS Excel database.
Posted
Updated 13-Jul-12 7:38am
v2
Comments
Jochen Arndt 13-Jul-12 3:20am    
That depends on the database type and the used interface. The documentation of the interface usually contains examples. When a connection has been established, a query can be executed using a SQL SELECT statement.

For example the accessing SQL Server :

#define DBNTWIN32
#include <stdio.h>
#include <windows.h>
#include <sqlfront.h>
#include <sqldb.h>

// Forward declarations of the error handler and message handler. 

int err_handler(PDBPROCESS, INT, INT, INT, LPCSTR, LPCSTR);
int msg_handler(PDBPROCESS, DBINT, INT, INT, LPCSTR, LPCSTR,
LPCSTR, DBUSMALLINT);
main()
{
   PDBPROCESS dbproc; // The connection with SQL Server. 
   PLOGINREC login; // The login information. 
   DBCHAR name[100];
   DBCHAR city[100];

// Install user-supplied error- and message-handling functions.

   dberrhandle (err_handler);
   dbmsghandle (msg_handler);

// Initialize DB-Library.

   dbinit ();

// Get a LOGINREC.

   login = dblogin ();
   DBSETLUSER (login, "my_login");
   DBSETLPWD (login, "my_password");
   DBSETLAPP (login, "example");

// Get a DBPROCESS structure for communication with SQL Server. 

   dbproc = dbopen (login, "my_server");

// Retrieve some columns from the authors table in the
// pubs database.
// First, put the command into the command buffer. 

   dbcmd (dbproc, "SELECT au_lname, city FROM pubs..authors");
   dbcmd (dbproc, " WHERE state = 'CA' ");

// Send the command to SQL Server and start execution. 

   dbsqlexec (dbproc);

// Process the results. 

   if (dbresults (dbproc) == SUCCEED)
   {

// Bind column to program variables. 

      dbbind (dbproc, 1, NTBSTRINGBIND, 0, name);
      dbbind (dbproc, 2, NTBSTRINGBIND, 0, city);

// Retrieve and print the result rows. 

      while (dbnextrow (dbproc) != NO_MORE_ROWS)
      {
         printf ("%s from %s\n", name, city);
      }
   }

// Close the connection to SQL Server. 

   dbexit ();
   return (0);
}

int err_handler (PDBPROCESS dbproc, INT severity,
INT dberr, INT oserr, LPCSTR dberrstr, LPCSTR oserrstr)
{
   printf ("DB-Library Error %i: %s\n", dberr, dberrstr);
   if (oserr != DBNOERR)
   {
      printf ("Operating System Error %i: %s\n", oserr, oserrstr);
   }
   return (INT_CANCEL);
}

int msg_handler (PDBPROCESS dbproc, DBINT msgno, INT msgstate,
INT severity, LPCSTR msgtext, LPCSTR server,
LPCSTR procedure, DBUSMALLINT line)
{
   printf ("SQL Server Message %ld: %s\n", msgno, msgtext);
   return (0);
}
</sqldb.h></sqlfront.h></windows.h></stdio.h>


Oracle C++ Call Interface (OCCI) is an Application Programming Interface (API) that provides C++ applications access to data in an Oracle database. This API is a significant improvement to the Oracle Call Interface (OCI) API as far as ease of use is concerned.
#include <dbmanager.h>
#include <iostream>

using namespace std;

using namespace oracle::occi;

const string sqlString("select empno, ename, hiredate from emp");

const string dateFormat("DD-MON-YYYY HH24:MI:SS");

int main(int argc, char **argv)
{
  if (argc != 2)
  {
	cerr << "\nUsage: " << argv[0] << " <db-user-name>\n" << endl;
	exit(1);
  }

  string userName = argv[1];

  // Initialize OracleServices

  DbManager* dbm = NULL;

  OracleServices* oras = NULL;

  Statement *stmt = NULL;

  ResultSet *resultSet = NULL;

  try

  {

	// Obtain OracleServices object with the default args.

	// The default args creates OracleServices with an environment of

	// Environment::OBJECT|Environment::THREADED_MUTEXED

	dbm = new DbManager(userName);

	oras = dbm->getOracleServices();

	// Obtain a cached connection

	Connection * conn = oras->connection();

	// Create a statement

	stmt = conn->createStatement(sqlString);

	int empno;

	string ename;

	Date hireDate;

	string dateAsString;

	// Execute query to get a resultset

	resultSet = stmt->executeQuery();

	while (resultSet->next()) 
	{
	  empno = resultSet->getInt(1);  // get the first column returned by the query;

	  ename = resultSet->getString(2);  // get the second column returned by the query

	  hireDate = resultSet->getDate(3);  // get the third column returned by the query

	  dateAsString="";

	  //You cannot check for null until the data has been read

	  if (resultSet->isNull(1))

	  {

				cout << "Employee num is null... " << endl;

	  }

	  if (resultSet->isNull(2))

	  {

				cout << "Employee name is null..." << endl;

	  }

	  if (resultSet->isNull(3))

	  {

				cout << "Hire date is null..." << endl;

	  }
	  else
	  {
				dateAsString=hireDate.toText(dateFormat);
	  }

	  cout << empno << "\t" << ename << "\t" << dateAsString << endl;

	}

	// Close ResultSet and Statement

	stmt->closeResultSet(resultSet);

	conn->terminateStatement(stmt);
 

	// Close Connection and OCCI Environment

	delete dbm;

  }

  catch (SQLException& ex)

  {

	if (dbm != NULL)

	{
		dbm->rollbackActions(ex, stmt, resultSet); // free resources and rollback transaction

	}

  }

  
  return 0;

}</db-user-name></iostream></dbmanager.h>


About using the MySQL Database with C++, you can read here:
http://suite101.com/article/using-a-mysql-databases-with-c-a70097[^]
 
Share this answer
 
Comments
Gbenbam 13-Jul-12 13:36pm    
I tried this code in visual studio 2008, but vs does not recognise the header files for all of sql server , oracle and MYSQL, why, what do I need to do
Volynsky Alex 14-Jul-12 3:07am    
You can use Data Sources Open Database Connectivity (ODBC) to access data from a variety of database management systems. For example, if you have a program that accesses data in a SQL database, Data Sources (ODBC) will let you use the same program to access data in a Visual FoxPro database. To do this, you must add software components called drivers to your system. Data Sources (ODBC) helps you add and configure these drivers.

start->Settings->Control Panel->Administrative Tools->Data Sources (ODBC)

Please see here: http://msdn.microsoft.com/en-us/library/2x0tte0f.aspx
There is a portable API named ODBC. You can use also native accessors, deppending on the database.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900