const char *COdbcConnection::ErrorString()
{
	SQLCHAR state[6];
	SQLINTEGER error;
	SQLSMALLINT size = 512,len;
	m_lasterrorString.resize((int)size);
	SQLCHAR *pmsg = (SQLCHAR*)m_lasterrorString.data();

	if(m_lastrsError.size())
	{
		strcpy((char*)pmsg,m_lastrsError.c_str());
		pmsg+=m_lastrsError.size();
		size-=(SQLSMALLINT)m_lastrsError.size();
		m_lastrsError="";
	}
	if(m_hDbc)
	{
		for(int i=1; SQL_SUCCEEDED(SQLGetDiagRec(SQL_HANDLE_DBC, m_hDbc, i, state, &error, pmsg, size, &len)); i++)
		{
			size-=len;
			pmsg+=len;
		}
	}
	if(m_hEnv)
	{
		for(int i=1; SQL_SUCCEEDED(SQLGetDiagRec(SQL_HANDLE_ENV, m_hEnv, i, state, &error, pmsg, size, &len)); i++)
		{
			size-=len;
			pmsg+=len;
		}
	}
	m_lasterrorString.resize(512-size);
	return m_lasterrorString.c_str();
}
Beispiel #2
0
static void odbc_Error(SQLSMALLINT type, void *obj, t_eventlog_level level, const char *function)
{
	SQLCHAR mState[6] = "\0";
	long native = 0;
	SQLSMALLINT mTextLen;
	short i = 0;

	while(SQLGetDiagRec(type, obj, ++i, NULL, NULL, NULL, 0, &mTextLen) != SQL_NO_DATA) {
		SQLCHAR *mText = xcalloc(sizeof *mText, ++mTextLen);
		SQLGetDiagRec(type, obj, i, mState,	&native, mText, mTextLen, NULL);
		eventlog(level, function, "ODBC Error: State %s, Native %i: %s", mState, native, mText);
		xfree(mText);
	}
}
Beispiel #3
0
void HandleDiagnosticRecord (SQLHANDLE      hHandle,    
                             SQLSMALLINT    hType,  
                             RETCODE        RetCode)
{
  SQLSMALLINT iRec = 0;
  SQLINTEGER  iError;
  char        message[1000];
  char        state[SQL_SQLSTATE_SIZE+1];


  if (RetCode == SQL_INVALID_HANDLE)
    {
      fprintf(stderr, "Invalid handle!\n");
      return;
    }

  while (SQLGetDiagRec(hType,
		       hHandle,
		       ++iRec,
		       state,
		       &iError,
		       message,
		       (SQLSMALLINT)(sizeof(message) / sizeof(WCHAR)),
		       (SQLSMALLINT *)NULL) == SQL_SUCCESS)
    {
      // Hide data truncated..
      if (strncmp(state, "01004", 5))
        {
	  fprintf(stderr, "[%5.5s] %s (%d)\n", state, message, iError);
        }
    }

}
Beispiel #4
0
void
odbc_report_error(const char *errmsg, int line, const char *file)
{
	SQLSMALLINT handletype;
	SQLHANDLE handle;
	SQLRETURN ret;
	SQLTCHAR sqlstate[6];
	SQLTCHAR msg[256];
	ODBC_BUF *odbc_buf = NULL;

	if (odbc_stmt) {
		handletype = SQL_HANDLE_STMT;
		handle = odbc_stmt;
	} else if (odbc_conn) {
		handletype = SQL_HANDLE_DBC;
		handle = odbc_conn;
	} else {
		handletype = SQL_HANDLE_ENV;
		handle = odbc_env;
	}
	if (errmsg[0]) {
		if (line)
			fprintf(stderr, "%s:%d %s\n", file, line, errmsg);
		else
			fprintf(stderr, "%s\n", errmsg);
	}
	ret = SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, msg, ODBC_VECTOR_SIZE(msg), NULL);
	if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
		fprintf(stderr, "SQL error %s -- %s\n", C(sqlstate), C(msg));
	odbc_disconnect();
	ODBC_FREE();
	exit(1);
}
Beispiel #5
0
static void
prerr(SQLSMALLINT tpe, SQLHANDLE hnd, const char *func, const char *pref)
{
	SQLCHAR state[6];
	SQLINTEGER errnr;
	SQLCHAR msg[256];
	SQLSMALLINT msglen;

	switch (SQLGetDiagRec(tpe, hnd, 1, state, &errnr, msg, sizeof(msg), &msglen)) {
	case SQL_SUCCESS_WITH_INFO:
		if (msglen >= (signed int) sizeof(msg))
			fprintf(stderr, "(message truncated)\n");
	case SQL_SUCCESS:
		fprintf(stderr, "%s: %s: SQLstate %s, Errnr %d, Message %s\n", func, pref, (char*)state, (int)errnr, (char*)msg);
		break;
	case SQL_INVALID_HANDLE:
		fprintf(stderr, "%s: %s, invalid handle passed to error function\n", func, pref);
		break;
	case SQL_ERROR:
		fprintf(stderr, "%s: %s, unexpected error from SQLGetDiagRec\n", func, pref);
		break;
	case SQL_NO_DATA:
		fprintf(stderr, "%s: %s, no error message from driver\n", func, pref);
		break;
	default:
		fprintf(stderr, "%s: %s, weird return value from SQLGetDiagRec\n", func, pref);
		break;
	}
}
Beispiel #6
0
void getDiag(SQLSMALLINT type, SQLHANDLE handle, unsigned k, unsigned count) 
{
  char message[MAX_MESSAGE];
  char state[6];
  SQLINTEGER native;

  SQLSMALLINT length = -1;
  memset(message, 0, MAX_MESSAGE);
  int ret = SQLGetDiagRec(type, handle, k, (SQLCHAR*)state, 
			  &native, (SQLCHAR*)message, MAX_MESSAGE, &length);
  if (ret == SQL_NO_DATA) {
    ndbout << "No error diagnostics available" << endl;
    return;
  }
  ndbout << message << endl;

  if (k <= count && ret != SQL_SUCCESS)
    ndbout_c("SQLGetDiagRec %d of %d: return %d != SQL_SUCCESS", 
	     k, count, (int)ret);
  if (k <= count && (SQLSMALLINT) strlen(message) != length)
    ndbout_c("SQLGetDiagRec %d of %d: message length %d != %d", 
	     k, count, strlen(message), length);
  if (k > count && ret != SQL_NO_DATA)
    ndbout_c("SQLGetDiagRec %d of %d: return %d != SQL_NO_DATA", 
	     k, count, (int)ret);
}
Beispiel #7
0
void
odbc_report_error(const char *errmsg, int line, const char *file)
{
    SQLSMALLINT handletype;
    SQLHANDLE handle;
    SQLRETURN ret;
    unsigned char sqlstate[6];
    unsigned char msg[256];


    if (odbc_stmt) {
        handletype = SQL_HANDLE_STMT;
        handle = odbc_stmt;
    } else if (odbc_conn) {
        handletype = SQL_HANDLE_DBC;
        handle = odbc_conn;
    } else {
        handletype = SQL_HANDLE_ENV;
        handle = odbc_env;
    }
    if (errmsg[0]) {
        if (line)
            fprintf(stderr, "%s:%d %s\n", file, line, errmsg);
        else
            fprintf(stderr, "%s\n", errmsg);
    }
    ret = SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, msg, sizeof(msg), NULL);
    if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
        fprintf(stderr, "SQL error %s -- %s\n", sqlstate, msg);
    odbc_disconnect();
    exit(1);
}
Beispiel #8
0
static void
run_statement(char *statement)
{
	SQLRETURN	ret;
	char		errmsg[500];
	SQLSMALLINT textlen;
	char		sqlstate[20];

	/*
	 * Skip empty lines. The server would just ignore them too, but might as
	 * well avoid the round-trip.
	 */
	if (statement[0] == '\0' || statement[0] == '\n')
		return;

	/* Skip comment lines too. */
	if (statement[0] == '-' && statement[1] == '-')
		return;

	ret = SQLExecDirect(hstmt, (SQLCHAR *) statement, SQL_NTS);
	if (!SQL_SUCCEEDED(ret))
	{
		printf("Statement failed: %s\n", statement);
		ret = SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, sqlstate, NULL,
							errmsg, sizeof(errmsg), &textlen);
		if (ret == SQL_INVALID_HANDLE)
			printf("Invalid handle\n");
		else if (SQL_SUCCEEDED(ret))
			printf("%s=%s\n", sqlstate, errmsg);
		exit(1);
	}
	(void) SQLFreeStmt(hstmt, SQL_CLOSE);
}
Beispiel #9
0
static void
connect_to_db(char *dsn)
{
	SQLRETURN	ret;
	char		errmsg[500];
	SQLSMALLINT textlen;
	char		sqlstate[20];

	SQLAllocHandle(SQL_HANDLE_DBC, env, &conn);

	ret = SQLDriverConnect(conn, NULL, (SQLCHAR *) dsn, SQL_NTS, NULL, 0, NULL,
						   SQL_DRIVER_NOPROMPT);
	if (!SQL_SUCCEEDED(ret))
	{
		printf("connection to %s failed\n", dsn);

		ret = SQLGetDiagRec(SQL_HANDLE_DBC, conn, 1, sqlstate, NULL,
							errmsg, sizeof(errmsg), &textlen);
		if (ret == SQL_INVALID_HANDLE)
			printf("Invalid handle\n");
		else if (SQL_SUCCEEDED(ret))
			printf("%s=%s\n", sqlstate, errmsg);
		exit(1);
	}

	printf("connected to %s\n", dsn);

	ret = SQLAllocHandle(SQL_HANDLE_STMT, conn, &hstmt);
	if (!SQL_SUCCEEDED(ret))
	{
		printf("SQLAllocHandle failed\n");
		exit(1);
	}
}
Beispiel #10
0
	bool SetError(int nResult, bool bFree = true) {
		if (!myErrRes 
			&& !SQL_SUCCEEDED(nResult)) {
				myErrBuf.Grow(1024);
				myErrState.Grow(6);
				SQLSMALLINT tlen = 0;
				if (!SQLGetDiagRec(myType, myHandle, 1, (SQLCHAR*) myErrState.GetBuffer(), &myErrCode, (SQLCHAR*) (myErrBuf.GetBuffer())+8, myErrBuf.Length()-8, &tlen)) {
					myErrBuf[0] = '(';
					memcpy(myErrBuf+1, (const char *)myErrState, 5);
					myErrBuf[6] = ')';
					myErrBuf[7] = ' ';
					myErrBuf.Grow(min(tlen+8,myErrBuf.Length()-8));
					myErrRes = nResult;
				} else {
					myErrState = "00000";
					myErrBuf = "(00000) No error.";
					myErrRes = nResult;
				}
				if (bFree) {
					SQLFreeHandle(myType, myHandle);
					myHandle = 0;
				}
				return false;
		}
		return true;
	}
Beispiel #11
0
	// Get an error of an ODBC handle
	bool __get_error(SQLSMALLINT _handle_type, SQLHANDLE _handle, _tstring & _error_desc, _tstring & _status_code)
	{
		SQLTCHAR status_code[64], error_message[511];
		SQLINTEGER i_native_error = 0;
		SQLSMALLINT total_bytes = 0;
		RETCODE rc;

		// Ask for info
		rc = SQLGetDiagRec(
			_handle_type,
			_handle,
			1,
			status_code,
			&i_native_error,
			error_message,
			sizeof(error_message),
			&total_bytes);

		if (TIODBC_SUCCESS_CODE(rc))
		{
			_status_code = sqltchar2ybstring(status_code, "");
			_error_desc = sqltchar2ybstring(error_message, "");
			return true;
		}

		_error_desc = _T("Can't get error message");
		_status_code = _T("UNKNOWN");
		return false;
	}
Beispiel #12
0
// Allocate environment handle, allocate connection handle,
// connect to data source, and allocate statement handle.
bool direxec::sqlconn(FILE* file)
{
	logFile = file;
	unsigned int timeout = 10; // seconds
	SQLAllocEnv(&henv);
	SQLAllocConnect(henv,&hdbc);
	SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, &timeout, 0);
	rc=SQLConnect(hdbc,chr_ds_name,SQL_NTS,NULL,0,NULL,0);
   
	// Deallocate handles, display error message, and exit.
	if (!MYSQLSUCCESS(rc))
	{
		SQLCHAR SqlState[6];
		SQLINTEGER NativeError;
		SQLSMALLINT MsgLen;

		SQLGetDiagRec(SQL_HANDLE_DBC, hdbc, 1, SqlState, &NativeError, (unsigned char *) szData, 2048, &MsgLen);
		SQLFreeEnv(henv);
		SQLFreeConnect(hdbc);

		fprintf(logFile, "! Error while connecting to database: %s\n", szData);
		errorstate = TRUE;
		return FALSE;
	}

	rc=SQLAllocStmt(hdbc,&hstmt);
	errorstate = FALSE;
	return TRUE;
}
Beispiel #13
0
void
print_diag(char *msg, SQLSMALLINT htype, SQLHANDLE handle)
{
	char		sqlstate[32];
	char		message[1000];
	SQLINTEGER	nativeerror;
	SQLSMALLINT textlen;
	SQLRETURN	ret;
	SQLSMALLINT	recno = 0;

	if (msg)
		printf("%s\n", msg);

	do
	{
		recno++;
		ret = SQLGetDiagRec(htype, handle, recno, sqlstate, &nativeerror,
							message, sizeof(message), &textlen);
		if (ret == SQL_INVALID_HANDLE)
			printf("Invalid handle\n");
		else if (SQL_SUCCEEDED(ret))
			printf("%s=%s\n", sqlstate, message);
	} while (ret == SQL_SUCCESS);

	if (ret == SQL_NO_DATA && recno == 1)
		printf("No error information\n");
}
Beispiel #14
0
void extract_error(
    char *fn,
    SQLHANDLE handle,
    SQLSMALLINT type)
{
    SQLINTEGER	 i = 0;
    SQLINTEGER	 native;
    SQLCHAR	 state[ 7 ];
    SQLCHAR	 text[256];
    SQLSMALLINT	 len;
    SQLRETURN	 ret;

    fprintf(stderr,
            "\n"
            "The driver reported the following diagnostics whilst running "
            "%s\n\n",
            fn);

    do
    {
        ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
                            sizeof(text), &len );
        if (SQL_SUCCEEDED(ret))
            printf("%s:%ld:%ld:%s\n", state, i, native, text);
    }
    while( ret == SQL_SUCCESS );
}
Beispiel #15
0
/**
 * When SQLExecute returns either SQL_ERROR or SQL_SUCCESS_WITH_INFO, 
 * an associated SQLSTATE value can be obtained by calling SQLGetDiagRec 
 * with a HandleType of SQL_HANDLE_STMT and a Handle of StatementHandle.  
 */
static SQLINTEGER
print_error_message(SQLSMALLINT hType, SQLHANDLE handle) {
	int i;
	SQLINTEGER ndiag=0;
	SQLRETURN ret;
	SQLCHAR state[6];
	SQLINTEGER error, maxerror=0;
	SQLCHAR text[1024];
	SQLSMALLINT len;

	ret = SQLGetDiagField(hType, handle, 0, SQL_DIAG_NUMBER, &ndiag, sizeof(ndiag), NULL);
	assert(ret == SQL_SUCCESS);

	for(i=1; i <= ndiag; i++) {
		memset(text, '\0', sizeof(text));
		ret = SQLGetDiagRec(hType, handle, i, state, &error, text, sizeof(text), &len);
		
		if (ret == SQL_SUCCESS && error == 0) {
			fprintf(stdout, "\"%s\"\n", text);
			continue;
		}
		
		fprintf(stderr, "%s: error %d: %s: %s\n", options.appname, (int)error, state, text);
		assert(ret == SQL_SUCCESS);
		
		if (error > maxerror)
			maxerror = error;
	}
	return maxerror;
}
Beispiel #16
0
int db__driver_execute_immediate(dbString * sql)
{
    char *s, msg[OD_MSG];
    cursor *c;
    SQLRETURN ret;
    SQLINTEGER err;

    s = db_get_string(sql);

    /* allocate cursor */
    c = alloc_cursor();
    if (c == NULL)
	return DB_FAILED;

    ret = SQLExecDirect(c->stmt, s, SQL_NTS);
    if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO)) {
	SQLGetDiagRec(SQL_HANDLE_STMT, c->stmt, 1, NULL, &err, msg,
		      sizeof(msg), NULL);
	db_d_append_error("SQLExecDirect():\n%s\n%s (%d)\n", s, msg,
			  (int)err);
	db_d_report_error();

	return DB_FAILED;
    }

    free_cursor(c);

    return DB_OK;
}
void displayError (SQLSMALLINT handleType, SQLHANDLE handle)		
{
	SQLSMALLINT	recNumber = 1;
	UCHAR	sqlstate[10];
	UCHAR	errmsg[SQL_MAX_MESSAGE_LENGTH];
	SDWORD	nativeerr;
	SWORD	actualmsglen;
	RETCODE	rc;

loop:  	rc = SQLGetDiagRec(handleType, handle, recNumber, sqlstate, &nativeerr, errmsg, strlen(errmsg), &actualmsglen);

	if (rc != SQL_SUCCESS) {
		printf ("SQLGetDiagRec failed!\n");
		getchar();
		return;
	}

	if (rc != SQL_NO_DATA_FOUND) {
		printf ("SQLSTATE = %s\n",sqlstate);
		printf ("NATIVE ERROR = %d\n",nativeerr);
		errmsg[actualmsglen] = '\0';
		printf ("MSG = %s\n\n",errmsg); 
		recNumber++;
		goto loop;
	}
}
SQLRETURN unixodbc_backend_debug::do_get_diagnostic_record(SQLSMALLINT handle_type, SQLHANDLE handle, SQLSMALLINT record_id, SQLCHAR * status_code_ptr, SQLINTEGER * native_error_ptr, SQLCHAR * message_text, SQLSMALLINT buffer_length, SQLSMALLINT * text_length_ptr) const
{
	std::cout << " *DEBUG* get_diagnostic_record (handle_type = " << handle_type << ")";
	auto const return_code = SQLGetDiagRec(handle_type, handle, record_id, status_code_ptr, native_error_ptr, message_text, buffer_length, text_length_ptr);
	std::cout << " (return code " << return_code << ")" << std::endl;
	return return_code;
}
Beispiel #19
0
void HandleDiagnosticRecord(SQLHANDLE      hHandle,
	SQLSMALLINT    hType,
	RETCODE        RetCode)
{
	SQLSMALLINT iRec = 0;
	SQLINTEGER  iError;
	SQLCHAR       wszMessage[1000];
	SQLCHAR       wszState[SQL_SQLSTATE_SIZE + 1];


	if (RetCode == SQL_INVALID_HANDLE)
	{
		fwprintf(stderr, L"Invalid handle!\n");
		return;
	}

	while (SQLGetDiagRec(hType,
		hHandle,
		++iRec,
		wszState,
		&iError,
		wszMessage,
		(SQLSMALLINT)(sizeof(wszMessage) / sizeof(WCHAR)),
		(SQLSMALLINT *)NULL) == SQL_SUCCESS)
	{
		// Hide data truncated.. 
		WCHAR state[SQL_SQLSTATE_SIZE + 1];
		//mbtowc(state, wszState, sizeof(wszState));
		if (wcsncmp(state, L"01004", 5))
		{
			fwprintf(stderr, L"[%5.5s] %s (%d)\n", wszState, wszMessage, iError);
		}
	}

}
Beispiel #20
0
int dump_sql_error(SQLRETURN retcode, SQLSMALLINT type, SQLHANDLE hsql, unsigned int statflag) {
	SQLCHAR SqlState[6], Msg[SQL_MAX_MESSAGE_LENGTH];
	SQLINTEGER error;
	SQLSMALLINT len;
	SQLRETURN rc;

	if (statflag > 0) printf("err\n");
	rc = SQLGetDiagRec(type, hsql, 1, SqlState, &error, Msg, SQL_MAX_MESSAGE_LENGTH, &len);
	if (rc != SQL_NO_DATA) {
		if (len >= SQL_MAX_MESSAGE_LENGTH) {
			Msg[SQL_MAX_MESSAGE_LENGTH] = '\0';
		}
		else {
			Msg[len] = '\0';
		}
		fprintf(stderr, "SQL error: %d -- %s\n%s\n", error, SqlState, Msg);
	}
	else {
		fprintf(stderr, "SQL error: %d\n", retcode);
	}

	close_handles();

	return 1;
}
Beispiel #21
0
void HandleError(SQLHANDLE	hHandle,
                 SQLSMALLINT	hType,
                 RETCODE	RetCode)
{
	fprintf(stderr, "in handle error %i %i\n", RetCode, hType);
	SQLSMALLINT	iRec = 0;
	SQLINTEGER	iError;
	TCHAR		szMessage[1000];
	TCHAR		szState[SQL_SQLSTATE_SIZE];


	if (RetCode == SQL_INVALID_HANDLE)
	{
		fprintf(stderr, "Invalid handle!\n");
		return;
	}


	while (SQLGetDiagRec(hType,
	                     hHandle,
	                     ++iRec,
	                     (SQLCHAR*)szState,
	                     &iError,
	                     (SQLCHAR*)szMessage,
	                     (SQLSMALLINT)(sizeof(szMessage) / sizeof(TCHAR)),
	                     (SQLSMALLINT *)NULL) == SQL_SUCCESS)
	{

		// Hide data truncated..
		if (_tcsncmp(szState, TEXT("01004"), 5))
			_ftprintf(stderr, TEXT("[%5.5s ] %s (%ld)\n"), szState, szMessage, iError);
	}

}
Beispiel #22
0
void extract_error(
char *fn,
SQLHANDLE handle,
SQLSMALLINT type,
char* stret)
{
	SQLINTEGER   i = 0;
	SQLINTEGER   native;
	SQLCHAR  state[ 7 ];
	SQLCHAR  text[256];
	SQLSMALLINT  len;
	SQLRETURN	ret;

	do
	{
		ret = SQLGetDiagRec(type, handle, ++i, state, &native, text,
			sizeof(text), &len );
		if (SQL_SUCCEEDED(ret)) {
			LM_ERR("unixodbc:%s=%s:%ld:%ld:%s\n", fn, state, (long)i, 
					(long)native, text);
			if(stret) strcpy( stret, (char*)state );
		}
	}
	while( ret == SQL_SUCCESS );
}
Beispiel #23
0
/**
 * Check if query was executed
 * 
 * @param chan R ODBC handle
 * @retval 0 if query not executed, 1 if query executed, -1 on error
 */
SEXP RODBCQueryStatus(SEXP chan){
  pRODBCHandle thisHandle = R_ExternalPtrAddr(chan);
  SQLRETURN res = 0;
  SQLINTEGER len;
  SQLCHAR sqlState[6];
  SQLINTEGER nativeError;
  SQLSMALLINT msgLen;

  res = SQLGetStmtAttr(thisHandle->hStmt, SQL_ATTR_ROW_NUMBER, NULL, 0, &len);
  if(res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO){
    /* get the error code */
    res = SQLGetDiagRec(SQL_HANDLE_STMT, thisHandle->hStmt, 1, sqlState, &nativeError, NULL, 0, &msgLen);
    if(res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO){
      return ScalarInteger(-1);
    }
    /* check if it is an INVALID CURSOR STATE error */
    if(strncmp((const char *)sqlState, "24000", 5) == 0){
      return ScalarInteger(0);
    }
    /* check if it is an NOT POSITIONED ON A VALID ROW error */
    if(strncmp((const char *)sqlState, "07005", 5) == 0){
      return ScalarInteger(1);
    }
    warning(_("SQL error code: %s"), sqlState);
    return ScalarInteger(-1);
  }

  return ScalarInteger(1);
}
Beispiel #24
0
int dbd_db2_statement_create(lua_State *L, connection_t *conn, const char *sql_query) { 
    SQLRETURN rc = SQL_SUCCESS;
    statement_t *statement = NULL;
    SQLHANDLE stmt;

    SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1];
    SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1];
    SQLINTEGER sqlcode;
    SQLSMALLINT length;	

    rc = SQLAllocHandle(SQL_HANDLE_STMT, conn->db2, &stmt);
    if (rc != SQL_SUCCESS) {
	SQLGetDiagRec(SQL_HANDLE_DBC, conn->db2, 1, sqlstate, &sqlcode, message, SQL_MAX_MESSAGE_LENGTH + 1, &length);

        lua_pushnil(L);
        lua_pushfstring(L, DBI_ERR_ALLOC_STATEMENT, message);
        return 2;
    }

    /*
     * turn off deferred prepare
     * statements will be sent to the server at prepare time,
     * and therefore we can catch errors now rather 
     * than at execute time
     */
    rc = SQLSetStmtAttr(stmt,SQL_ATTR_DEFERRED_PREPARE,(SQLPOINTER)SQL_DEFERRED_PREPARE_OFF,0);

    rc = SQLPrepare(stmt, (SQLCHAR *)sql_query, SQL_NTS);
    if (rc != SQL_SUCCESS) {
	SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, sqlstate, &sqlcode, message, SQL_MAX_MESSAGE_LENGTH + 1, &length);

	lua_pushnil(L);
	lua_pushfstring(L, DBI_ERR_PREP_STATEMENT, message);
	return 2;
    }

    statement = (statement_t *)lua_newuserdata(L, sizeof(statement_t));
    statement->stmt = stmt;
    statement->db2 = conn->db2;
    statement->resultset = NULL;
    statement->bind = NULL;

    luaL_getmetatable(L, DBD_DB2_STATEMENT);
    lua_setmetatable(L, -2);

    return 1;
} 
static void acf_odbc_error(SQLHSTMT stmt, int res)
{
	char state[10] = "", diagnostic[256] = "";
	SQLINTEGER nativeerror = 0;
	SQLSMALLINT diagbytes = 0;
	SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
	ast_log(LOG_WARNING, "SQL return value %d: error %s: %s (len %d)\n", res, state, diagnostic, diagbytes);
}
Beispiel #26
0
/**
 * Displays error message and prepare for program exit.
 */
int barf(SQLHENV c, char* failMsg) {
    char sqlhmsg[200], sqlhstat[10];
    SQLSMALLINT junksmall;
    SQLINTEGER errint;

    SQLGetDiagRec(SQL_HANDLE_DBC, c, 1, sqlhstat, &errint,
            sqlhmsg, 100, &junksmall);
    return print2_ret(failMsg, sqlhmsg, 1);
}
Beispiel #27
0
// 연결 핸들을 할당하고 연결한 후 명령핸들까지 같이 할당한다.
// Type=1:ConStr은 MDB 파일의 경로를 가진다. 경로 생략시 현재 디렉토리에서 MDB를 찾는다.
// Type=2:ConStr은 SQL 서버의 연결 정보를 가지는 DSN 파일의 경로를 가진다. 
//        경로는 반드시 완전 경로로 지정해야 한다.
// Type=3:SQLConnect 함수로 DSN에 직접 연결한다.
// 연결 또는 명령 핸들 할당에 실패하면 FALSE를 리턴한다.
BOOL CQuery::Connect(int Type, char *ConStr, char *UID, char *PWD)
{
	SQLCHAR InCon[255];
	SQLCHAR OutCon[255];
    SQLSMALLINT cbOutCon;

	int ii=1;
	SQLRETURN Ret;
	SQLINTEGER NativeError;
	SQLCHAR SqlState[6], Msg[255];
	SQLSMALLINT MsgLen;
	char str[256];

	m_Type = Type;
	strcpy(m_szConnect, ConStr);
	strcpy(m_Id, UID);
	strcpy(m_Pass, PWD);

	// 연결 타입에 따라 MDB 또는 SQL 서버, 또는 DSN에 연결한다.
	SQLAllocHandle(SQL_HANDLE_DBC,hEnv,&hDbc);
	switch (Type) {
	case 1:
		wsprintf((char *)InCon,"DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;",ConStr);
		ret=SQLDriverConnect(hDbc,NULL,(SQLCHAR *)InCon,sizeof(InCon),OutCon,
			sizeof(OutCon),&cbOutCon, SQL_DRIVER_NOPROMPT);
		break;
	case 2:
		wsprintf((char *)InCon, "FileDsn=%s",ConStr);
		ret=SQLDriverConnect(hDbc,NULL,(SQLCHAR *)InCon,sizeof(InCon),OutCon,
			sizeof(OutCon),&cbOutCon, SQL_DRIVER_NOPROMPT);
		break;
	case 3:
		ret=SQLConnect(hDbc,(SQLCHAR *)ConStr,SQL_NTS,(SQLCHAR *)UID,SQL_NTS,
			(SQLCHAR *)PWD,SQL_NTS);
		break;
	}

	// 접속 에러시 진단 정보를 보여준다.
	if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO)) {
		while (Ret=SQLGetDiagRec(SQL_HANDLE_DBC, hDbc, ii, SqlState, &NativeError, 
			Msg, sizeof(Msg), &MsgLen)!=SQL_NO_DATA) {
			wsprintf(str, "(1) SQLSTATE:%s, Diagnosis:%s",(LPCTSTR)SqlState,(LPCTSTR)Msg);
			//::MessageBox(NULL,str,"진단 정보",0);
			gWindow.PrintLog(str);
			ii++;
		}
		return FALSE;
	}

	// 명령 핸들을 할당한다.
	ret=SQLAllocHandle(SQL_HANDLE_STMT,hDbc,&hStmt);
	if ((ret != SQL_SUCCESS) && (ret != SQL_SUCCESS_WITH_INFO)) {
		hStmt=0;
		return FALSE;
	}
	return TRUE;
}
Beispiel #28
0
static void
ReadError(void)
{
	if (!SQL_SUCCEEDED(SQLGetDiagRec(SQL_HANDLE_STMT, Statement, 1, NULL, NULL, output, sizeof(output), NULL))) {
		printf("SQLGetDiagRec should not fail\n");
		exit(1);
	}
	printf("Message: %s\n", output);
}
Beispiel #29
0
ZBX_ODBC_ROW	odbc_DBfetch(ZBX_ODBC_RESULT pdbh)
{
	SQLCHAR 	
	 	err_stat[10],
	 	err_msg[100];

	SQLINTEGER 
		err_int;

	SQLSMALLINT	
		err_msg_len;

	SQLRETURN	retcode;
	SQLSMALLINT     i;
	
	if(pdbh == NULL)	return NULL;

	clean_odbc_strerror();
	
	zabbix_log(LOG_LEVEL_DEBUG, "ODBC fetch");

	retcode = SQLFetch(pdbh->hstmt);
	if (retcode == SQL_ERROR) goto lbl_err_exit;
	
	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO )
	{
		zabbix_log(LOG_LEVEL_DEBUG, "odbc_DBfetch [end of rows received]");
		return NULL;
	}

	for(i=0; i < pdbh->col_num; i++)
	{
		rtrim_spaces(pdbh->row_data[i]);
		zabbix_log(LOG_LEVEL_DEBUG, "Featched [%i col]: %s", i, pdbh->row_data[i]);
	}

	return pdbh->row_data;
	
lbl_err_exit:	
	
	SQLGetDiagRec(SQL_HANDLE_STMT, 
			pdbh->hstmt,
			1,
			err_stat,
			&err_int,
			err_msg,
			sizeof(err_msg),
			&err_msg_len
			);
	
	set_last_odbc_strerror("Failed data fetching [%s] (%d)", err_msg, err_int);

	zabbix_log(LOG_LEVEL_ERR, "%s", get_last_odbc_strerror());

	return NULL;
}
char* COdbcDS::GetLastError()
{
	SQLCHAR MsgTxt[300] = "";
	SQLSMALLINT MsgLen;
	SQLRETURN retVal = SQL_SUCCESS;
	int icount = 1;
	char* msg = NULL;
	int length = 0;

	retVal = SQLGetDiagRec(SQL_HANDLE_ENV, m_henv, icount++, NULL, NULL, MsgTxt,
						sizeof(MsgTxt), &MsgLen);

	while(retVal == SQL_SUCCESS)
	{
		length = strlen((const char*)MsgTxt);

		// New message
		if (msg == NULL)
		{
			msg = (char*) malloc(sizeof(char) * (length + 1));
			strcpy(msg, (const char*)MsgTxt);
		}
		// Append to message
		else
		{
			int length2 = strlen((const char*)msg);
			// include room for null and new line.
			char* tmp = (char*) malloc(sizeof(char) * (length + length2 + 2));
			strcpy(tmp, msg);
			strcat(tmp, "\n");
			strcat(tmp, (const char*)MsgTxt);
			free(msg);
			msg = tmp;
		}

		retVal = SQLGetDiagRec(SQL_HANDLE_ENV, m_henv, icount++, NULL, NULL,
							MsgTxt, sizeof(MsgTxt), &MsgLen);

	}

	return msg;
}