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
|
#include <iostream>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>
int Connect_SQL() {
#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
#define MAX_STRING_LEN 255
//define handles and variables
SQLHANDLE sqlConnHandle;
SQLHANDLE sqlStmtHandle;
SQLHANDLE sqlEnvHandle;
SQLWCHAR retconstring[SQL_RETURN_CODE_LEN];
//initializations
sqlConnHandle = NULL;
sqlStmtHandle = NULL;
//allocations
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle))
goto COMPLETED;
if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
goto COMPLETED;
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle))
goto COMPLETED;
switch (
SQLDriverConnect(sqlConnHandle,
NULL,
(SQLWCHAR*)L"DRIVER={SQL Server};SERVER = 103.151.23.147;DATABASE=test;UID=sa;PASSWORD=44448888;",
SQL_NTS,
retconstring,
1024,
NULL,
SQL_DRIVER_NOPROMPT))
{
case SQL_SUCCESS:
MessageBox(NULL, L"Successfully connected to SQL Server", L"", MB_OK);
break;
case SQL_SUCCESS_WITH_INFO:
MessageBox(NULL, L"SQL_SUCCESS_WITH_INFO", L"", MB_OK);
break;
case SQL_INVALID_HANDLE:
MessageBox(NULL, L"SQL_INVALID_HANDLE", L"", MB_OK);
goto COMPLETED;
case SQL_ERROR:
MessageBox(NULL, L"SQL_ERROR", L"", MB_OK);
goto COMPLETED;
default:
break;
}
//if there is a problem connecting then exit application
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle))
goto COMPLETED;
//output
MessageBox(NULL, L"Executing T-SQL query...", L"", MB_OK);
//if there is a problem executing the query then exit application
//else display query result
if (SQL_SUCCESS != SQLExecDirect(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) {
MessageBox(NULL, L"Error querying SQL Server", L"", MB_OK);
goto COMPLETED;
}
else {
//declare output variable and pointer
SQLCHAR sqlVersion[SQL_RESULT_LEN];
SQLINTEGER ptrSqlVersion;
while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion);
//display query result
MessageBox(NULL, L"Query Result", L"", MB_OK);
}
}
//close connection and free resources
COMPLETED:
SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);
SQLDisconnect(sqlConnHandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle);
SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle);
return 0;
}
| |