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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <windows.h>
#include <stdio.h>
//#include <sql.h>
#include <sqlext.h>
//#include <odbcss.h>
//#include <string>
/* Data Access Method used in this sample */
const char* DAM = "Direct ODBC";
/* Connection string for Direct ODBC */
SQLCHAR szDSN[256] =
"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=C:\\FILEBLOCK\\Fileblocker.accdb;";
main()
{
HENV hEnv;
HDBC hDbc;
/* ODBC API return status */
SQLRETURN rc;
SQLSMALLINT iConnStrLength2Ptr;
SQLCHAR szConnStrOut[255];
SQLCHAR* query = "SELECT tblIP.[IPAddress], tblIP.[IPStatus], tblIP.[IPType] FROM tblIP ORDER BY tblIP.[IPAddress] ASC;";
SQLCHAR chval1[128], chval2[128], chval3[128], colName[128];
SQLINTEGER ret1, ret2, ret3;
/* Number of rows and columns in result set */
SQLINTEGER rowCount = 0;
SQLSMALLINT fieldCount = 0, column = 0;
HSTMT hStmt;
/* Allocate an environment handle */
rc = SQLAllocEnv(&hEnv);
/* Allocate a connection handle */
rc = SQLAllocConnect(hEnv, &hDbc);
/* Connect to the 'Northwind 2007.accdb' database */
rc = SQLDriverConnect(hDbc, NULL, szDSN, _countof(szDSN),
szConnStrOut, 255, &iConnStrLength2Ptr, SQL_DRIVER_NOPROMPT);
if (SQL_SUCCEEDED(rc))
{
printf("%s: Successfully connected to database. Data source name: \n %s\n",
DAM, szConnStrOut);
/* Prepare SQL query */
printf("%s: SQL query:\n %s\n", DAM, query);
rc = SQLAllocStmt(hDbc,&hStmt);
rc = SQLPrepare(hStmt, query, SQL_NTS);
/* Bind result set columns to the local buffers */
rc = SQLBindCol(hStmt, 1, SQL_C_CHAR, chval1, 128, &ret1);
rc = SQLBindCol(hStmt, 2, SQL_C_CHAR, chval2, 128, &ret2);
rc = SQLBindCol(hStmt, 3, SQL_C_CHAR, chval3, 128, &ret3);
/* Execute the query and create a record set */
rc = SQLExecute(hStmt);
if (SQL_SUCCEEDED(rc))
{
printf("%s: Retrieve schema info for the given result set:\n", DAM);
SQLNumResultCols(hStmt, &fieldCount);
if (fieldCount > 0)
{
for (column = 1; column <= fieldCount; column++)
{
SQLDescribeCol(hStmt, column,
colName, sizeof(colName), 0, 0, 0, 0, 0);
printf(" | %s", colName);
}
printf("\n");
}
else
{
printf("%s: Error: Number of fields in the result set is 0.\n", DAM);
}
printf("%s: Fetch the actual data:\n", DAM);
/* Loop through the rows in the result set */
rc = SQLFetch(hStmt);
while (SQL_SUCCEEDED(rc))
{
printf(" | %s | %s\n", chval1, chval2, chval3);
rc = SQLFetch(hStmt);
rowCount++;
};
printf("%s: Total Row Count: %d\n", DAM, rowCount);
rc = SQLFreeStmt(hStmt, SQL_DROP);
}
}
else
{
printf("%s: Couldn't connect to %s.\n", DAM, szDSN);
}
/* Disconnect and free up allocated handles */
SQLDisconnect(hDbc);
SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
printf("%s: Cleanup. Done.\n", DAM);
}
|