IT_Programming/C · C++

[펌_Win32 C++] Configuration MS SQL Express, ODBC DSN with Win32 C++

JJun ™ 2009. 8. 6. 15:02

출처: http://hwanysnote.blogspot.com/2008_03_01_archive.html

 

 

Requirements

  • MS SQL Server 2005 Express
  • MS SQL Server Management Studio Express
  • MS VisualStudio 2005 (VC++8)

 

Instruction

 

1. Install all Requirements. And Confirm 'MS SQL Server 2005 Express' is running.

 

2. Execute 'MS SQL Server Management Studio Express'.    

 

 

3. Add new database. 

 

 

4. Add new table 

 

 

5. Open ODBC configuration ( Start - Control Panel - Administrative Tools - Data Source ) 

 

 

6. Add new Data Source 

 

 

7. Select SQL Server  

 

 

 

8. Click Client Configuration 

 

 

9. Set 'Network Library' to TCP/IP (or other correspond to SQL Server)  

 

 

10. Check Server's Connection  

 

 

11. Enabling TCP/IP connection of SQL server.  

 

 

 

 

12. Return to the ODBC configuration and set a default database

     ( If the connection to the SQL server is valid, the combobox of database names present the

       whole database names of the SQL server.)  

 

 

 

13. Finally, configuration dialog represent the report.

     Click the 'Test Data Source..' if you want.  

 

 

 

14. The new Data Souce Name is added.   

 

 

 

[Sample Code] Below is the code of connecting ODBC using Win32 C++.

--------------------------------------------------------------------------------------------------

#include <Windows.h>
#include <iostream>
#include <sql.h>
#include <sqlext.h>

int main(int argc, char *argv[])
{
    SQLHENV hEnv = NULL;
    SQLHDBC hDbc = NULL;
    SQLRETURN ret = SQL_SUCCESS;

    char ConStr[] = onfuse_p2p_db";

    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv);
    SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3,

                  SQL_IS_INTEGER);

    SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc);
    ret = SQLConnect(hDbc,(SQLCHAR *)ConStr, SQL_NTS, (SQLCHAR *)NULL, SQL_NTS,

                      (SQLCHAR *)NULL, SQL_NTS);

    if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO)) {
        std::cout << "Connection:fail" << std::endl;
    }
    else
    {
        std::cout << "Connection:success" << std::endl;
    }
   
    if (hDbc) SQLDisconnect(hDbc);
    if (hDbc) SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
    if (hEnv) SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

    return 0;
}
--------------------------------------------------------------------------------------------------