How to get Columns, their names and attributes from a table?
Submitted by date of submission user level
Mahesh Chand July 01, 2000 Beginner
Here are few simple steps :
Create a dialog based MFC exe project with default options.
Add a list control on the dialog with default name ( IDC_LIST1).
include
write this code at your project's OnInitDlg or Ok button's handler :
NOTE : Here my DSN name is "Kruse" which is connected to an access or SQL Server database. I am accessing a table called "KRUSE1" which contains 57 fields. You can modify this according to your table.
CListBox * lpDatasourceList=(CListBox*)GetDlgItem(IDC_LIST1);
UCHAR FAR * szColName = new UCHAR[15];
SWORD FAR pcbColName;
SWORD pfSqlType;
UDWORD pcbColDef;
SWORD pibScale;
SWORD pfNullable;
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
RETCODE retcode ;
int ntotalCols ;
UCHAR uchOWN[256];
SWORD swScale;
SDWORD wlenCol;
// allocate environment handle
retcode = ::SQLAllocEnv(&henv);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
retcode = ::SQLAllocConnect( henv, &hdbc);
if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
{
/* Connect to data source called 'Kruse' . If you are using UserID and Password, then pass them as fourth and fifth arguments casting by SQLCHAR*. */
retcode = ::SQLConnect(hdbc, (SQLCHAR*) "Kruse", SQL_NTS, (SQLCHAR*) "", SQL_NTS, (SQLCHAR*) "", SQL_NTS);
if (retcode==SQL_SUCCESS || retcode==SQL_SUCCESS_WITH_INFO) {
/* Allocate statement handle */
retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
if (retcode==SQL_SUCCESS ||retcode==SQL_SUCCESS_WITH_INFO) {
retcode = ::SQLPrepare(hstmt, (UCHAR FAR*)"SELECT * FROM KRUSE1",(SDWORD)20);
ASSERT(retcode == SQL_SUCCESS);
/* execute statement */
retcode = ::SQLExecute(hstmt);
if (retcode == SQL_SUCCESS)
{
// get total number of columns in kruse1 table
retcode = ::SQLColAttributes( hstmt, 0, SQL_COLUMN_COUNT, uchOWN, 256, &swScale, &wlenCol );
ntotalCols=(int)wlenCol;
if (retcode==SQL_SUCCESS||retcode== SQL_SUCCESS_WITH_INFO) {
for(int i=0; i <= ntotalCols; i++) {
// here we can get column name, type, and other // properties. see SQLDescribeCol from more details.
retcode = ::SQLDescribeCol(hstmt, (UWORD)i, szColName, (SWORD)15, &pcbColName, &pfSqlType, &pcbColDef, &pibScale, &pfNullable);
lpDatasourceList->AddString( LPCTSTR(szColName) );
}
}
// free statement handle
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
}
SQLDisconnect(hdbc);
}
// free connection handle
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
}
}
// free environment handle
SQLFreeHandle(SQL_HANDLE_ENV, henv);
lpDatasourceList->SetCurSel(0);
Contact mindcracker.com: webmaster.