Connecting to Database using C++

Jun 30, 2011 at 5:30pm
I want to write an application using pure C++ code. I have to use
MS Access as Database because that is the only way that I can access my OPC server to acquire data. So all database functionalities ( i.e
adding,retrieving,modifying,deleting etc... ) should reflect on this
application.

Any one can please help me out, what should be the C++ code for my
application. Please help me as soon as possible. This is part of a work project. I have looked at the information from the website: http://msdn.microsoft.com/en-us/library/cc811599.aspx

I have also tried to test the code from the site using C++ on Visual Studio, but I repeatedly got errors even after establishing that my connection string was good. I was wondering if someone could please help me with this.

Thank you.
Jun 30, 2011 at 5:47pm
The below code is the one I designed using MFC (ODBC connection), the steps should be much similar for C++.
Hope this helps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
        CDatabase database;
	CString SqlString;
	CString sCatID, sCategory;
	CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)";
	CString sDsn;
	CString sFile = "C:\\Users\\EmployeeData.mdb";
	// You must change above path if it's different
	int iRec = 0; 	
	
	// Build ODBC connection string
	sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile);
	TRY
	{
		// Open the database
		if(database.Open(NULL,false,false,sDsn))
		{
		
		// Allocate the recordset
		CRecordset recset( &database );

		// Build the SQL statement
		SqlString =  "SELECT EmpID,EmpName "
				"FROM Empdata";

		// Execute the query
		recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);
		// Reset List control if there is any data
		ResetListControl();
		// populate Grids
		ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES);
 
		// Column width and heading
		m_ListControl.InsertColumn(0,"Emp Id",LVCFMT_LEFT,-1,0);
		m_ListControl.InsertColumn(1,"Emp Name",LVCFMT_LEFT,-1,1);
		m_ListControl.SetColumnWidth(0, 120);
		m_ListControl.SetColumnWidth(1, 200);

		// Loop through each record
		while( !recset.IsEOF() )
		{
			// Copy each column into a variable
			recset.GetFieldValue("EmpID",sCatID);
			recset.GetFieldValue("EmpName",sCategory);

			// Insert values into the list control
			iRec = m_ListControl.InsertItem(0,sCatID,0);
			m_ListControl.SetItemText(0,1,sCategory);

			// goto next record
			recset.MoveNext();
		}
		// Close the database
		database.Close();
		}
	}
	CATCH(CDBException, e)
	{
		// If a database exception occured, show error msg
		AfxMessageBox("Database error: "+e->m_strError);
	}
	END_CATCH;


Topic archived. No new replies allowed.