SQLHANDLE sqlenvhandle = NULL;
SQLHANDLE sqlconnectionhandle = NULL;
SQLHANDLE sqlstatementhandle = NULL;
SQLRETURN retcode;
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle)) {
goto FINISHED;
}
if (SQL_SUCCESS != SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0)){
goto FINISHED;
}
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle)){
goto FINISHED;
}
SQLWCHAR retconstring[1024];
switch (SQLDriverConnect(sqlconnectionhandle,
NULL,
(SQLWCHAR*)"DRIVER={SQL Server};SERVER=localhost;DATABASE=Prod;UID=user;PWD=pass;",
SQL_NTS,
retconstring,
1024,
NULL,
SQL_DRIVER_NOPROMPT)){
case SQL_SUCCESS_WITH_INFO:
show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
break;
case SQL_INVALID_HANDLE:
case SQL_ERROR:
show_error(SQL_HANDLE_DBC, sqlconnectionhandle);
goto FINISHED;
default:
break;
}
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle)){
goto FINISHED;
}
if (SQL_SUCCESS != SQLExecDirect(sqlstatementhandle, (SQLWCHAR*)"select * from testtable", SQL_NTS)){
show_error(SQL_HANDLE_STMT, sqlstatementhandle);
goto FINISHED;
}
else{
char name[64];
char address[64];
int id;
while (SQLFetch(sqlstatementhandle) == SQL_SUCCESS){
SQLGetData(sqlstatementhandle, 1, SQL_C_ULONG, &id, 0, NULL);
SQLGetData(sqlstatementhandle, 2, SQL_C_CHAR, name, 64, NULL);
SQLGetData(sqlstatementhandle, 3, SQL_C_CHAR, address, 64, NULL);
cout << id << " " << name << " " << address << endl;
}
}
FINISHED:
if (sqlstatementhandle != NULL) {
SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle);
}
if (sqlconnectionhandle != NULL) {
SQLDisconnect(sqlconnectionhandle);
SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
}
if (sqlenvhandle != NULL) {
SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
}
what should my dsn connection string look like?you may try with "ODBC;<dsnname>" what could be sufficient if your datasource already was working.
sDsn.Format((SQLWCHAR*)"ODto cast a char * to SQLWCHAR* probably isn't a good idea. I would configure the mfc project with multi-byte character set rather than with Unicode. but if your gui is Unicode you also could switch to Unicode. if that is the case you should use the L prefix to using wide character literals or use the _T or TEXT macros provided. don't mix wide and narrow characters if it is not absolutely necessary.BC;DRIVER= {%s};Serve r=%s;Datab ase=%s;UID =user;PWD= pass;", sDriver, sMc, sFile);
sDsn.Format("ODBC;DSN='MyDSN';UID=user;PWD=pass;");
database.noOdbcDialog;
if (database.Open("MyDSN", false, false, sDsn))
{
//success
}
Open in new window
You may need to post here the portion of code you're using for connecting to SQL Server so we can help you better.