/*************************************************************************
 *
 *	Function: sql_query
 *
 *	Purpose: Issue a non-SELECT query (ie: update/delete/insert) to
 *	       the database.
 *
 *************************************************************************/
static sql_rcode_t sql_query(rlm_sql_handle_t *handle, rlm_sql_config_t *config, char const *query) {

	rlm_sql_iodbc_conn_t *conn = handle->conn;
	SQLRETURN rcode;

	rcode = SQLAllocStmt(conn->dbc_handle,
			     &conn->stmt_handle);
	if (!SQL_SUCCEEDED(rcode)) {
		ERROR("sql_create_socket: SQLAllocStmt failed:  %s",
				sql_error(handle, config));
		return -1;
	}

	if (!conn->dbc_handle) {
		ERROR("sql_query:  Socket not connected");
		return -1;
	}

	{
		SQLCHAR *statement;

		memcpy(&statement, &query, sizeof(statement));
		rcode = SQLExecDirect(conn->stmt_handle, statement, SQL_NTS);
	}

	if (!SQL_SUCCEEDED(rcode)) {
		ERROR("sql_query: failed:  %s",
				sql_error(handle, config));
		return -1;
	}

	return 0;
}
ResultSet_T SqlServerConnection_executeQuery(T C, const char *sql, va_list ap) {
	va_list ap_copy;
	const char *tail;
	SQLHSTMT hstmt;

	assert(C);
	StringBuffer_clear(C->sb);
	va_copy(ap_copy, ap);
	StringBuffer_vappend(C->sb, sql, ap_copy);
	va_end(ap_copy);

	C->lastError = SQLAllocStmt(C->db->hdbc,&hstmt);


	C->lastError = SQLPrepare(hstmt,
		StringBuffer_toString(C->sb), StringBuffer_length(C->sb)); 
	if(!SQLSERVERSUCCESS(C->lastError)) {
		getSqlErr(C,hstmt);
		return NULL;
	}
	C->lastError = SQLExecute(hstmt);
	if(SQLSERVERSUCCESS(C->lastError))
		return ResultSet_new(SqlServerResultSet_new(hstmt, C->maxRows, false), (Rop_T)&sqlserverrops);
	else {
		getSqlErr(C,hstmt);
	}
	return NULL;
}
int main(int argc, char **argv)
{
	int rc;
	HSTMT hstmt = SQL_NULL_HSTMT;
	char sql[100000];
	char *sqlend;
	int i;

	test_connect();

	rc = SQLAllocStmt(conn, &hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	rc = SQLTables(hstmt, "", SQL_NTS,
				   "public", SQL_NTS,
				   "%", SQL_NTS,
				   "TABLE", SQL_NTS);

	CHECK_STMT_RESULT(rc, "SQLTables failed", hstmt);
	print_result(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/* Clean up */
	test_disconnect();
}
Exemple #4
0
void
odbc_reset_statement_proc(SQLHSTMT *stmt, const char *file, int line)
{
	SQLFreeStmt(*stmt, SQL_DROP);
	*stmt = SQL_NULL_HSTMT;
	odbc_check_res(file, line, SQLAllocStmt(odbc_conn, stmt), SQL_HANDLE_DBC, odbc_conn, "SQLAllocStmt", "S");
}
Exemple #5
0
/* We allocate a new hstmt for this query, and leave it sitting in the
   db->hstmt slot.

   We need to free these things eventually, but that is the job of
   gsql_store_result() and gsql_free_result().  gsql_store_result() copies
   the hstmt pointer to a gsql_result structure, and sets the db->hstmt
   slot to NULL.  gsql_free_result is responsible for calling SQLFreeStmt().

   Thus, a call to gsql_query() should always be followed by a call to
   gsql_store_result(), and the result must eventually be freed using
   gsql_free_result(). */
static int
gsql_query (Database *db, char *query, int save_errors_p)
{
  pagefunc_set_variable ("odbc::recent-query", query);
  pagefunc_set_variable ("gsql::recent-query", query);

  if (db->connected)
    {
      /* If there is an old hstmt sitting here, free it. */
      if (db->hstmt)
	SQLFreeStmt (db->hstmt, SQL_DROP);

      if (SQLAllocStmt (db->hdbc, &(db->hstmt)) != SQL_SUCCESS)
	return (GSQL_ERROR);

      if (SQLExecDirect (db->hstmt, (UCHAR *) query, SQL_NTS) != SQL_SUCCESS)
	{
	  if (save_errors_p)
	    gsql_save_error_message (db, GSQL_DEFAULT_ERRMSG);
	  return (GSQL_ERROR);
	}
      else
	return (GSQL_SUCCESS);
    }
  else
    return (GSQL_ERROR);
}
Exemple #6
0
unsigned CMssqlConnection::GetInsertIdentity(const char *table_hint)
{
	HSTMT hStmt;

	m_lasterror=SQLAllocStmt(m_hDbc,&hStmt);
	if(!SQL_SUCCEEDED(m_lasterror))
		return 0;

	m_lasterror=SQLExecDirect(hStmt,(SQLWCHAR*)L"SELECT @@IDENTITY",SQL_NTS);
	if(!SQL_SUCCEEDED(m_lasterror))
	{
		SQLFreeStmt(hStmt,SQL_DROP);
		return 0;
	}

	long id;
	SQLINTEGER len;

	m_lasterror=SQLBindCol(hStmt,1,SQL_C_LONG,&id,sizeof(id),&len);
	if(!SQL_SUCCEEDED(m_lasterror))
	{
		SQLFreeStmt(hStmt,SQL_DROP);
		return 0;
	}

	m_lasterror=SQLFetch(hStmt);
	if(!SQL_SUCCEEDED(m_lasterror))
		return 0;

	SQLFreeStmt(hStmt,SQL_DROP);

	return (unsigned)id;
}
int MADB_KeyTypeCount(MADB_Dbc *Connection, char *TableName, int KeyFlag)
{
  int Count= 0;
  unsigned int i;
  char StmtStr[1024];
  char *p= StmtStr;
  char Database[65];
  SQLHSTMT Stmt= NULL;
  MADB_Stmt *KeyStmt;
  
  SQLGetConnectAttr((SQLHDBC)Connection, SQL_ATTR_CURRENT_CATALOG, Database, 65, NULL);
  p+= my_snprintf(p, 1024, "SELECT * FROM ");
  if (Database)
    p+= my_snprintf(p, 1024 - strlen(p), "`%s`.", Database);
  p+= my_snprintf(p, 1024 - strlen(p), "%s LIMIT 0", TableName);
  if (SQLAllocStmt((SQLHDBC)Connection, &Stmt) == SQL_ERROR ||
      SQLPrepare(Stmt, (SQLCHAR *)StmtStr, SQL_NTS) == SQL_ERROR ||
      SQLExecute(Stmt) == SQL_ERROR ||
      SQLFetch(Stmt) == SQL_ERROR)
      goto end;
  KeyStmt= (MADB_Stmt *)Stmt;
  for (i=0; i < mysql_stmt_field_count(KeyStmt->stmt); i++)
    if (KeyStmt->stmt->fields[i].flags & KeyFlag)
      Count++;
end:
  if (Stmt)
    SQLFreeHandle(SQL_HANDLE_STMT, Stmt);
  return Count;
}
Exemple #8
0
static void
newStatement(void)
{
    rc = SQLAllocStmt(hdbc, &hstmt);
    if(rc)
	errorPrint("@could not alloc singleton ODBC statement handle");
}				/* newStatement */
Exemple #9
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;
}
/*************************************************************************
 *
 *	Function: sql_init_socket
 *
 *	Purpose: Establish connection to the db
 *
 *************************************************************************/
static int sql_init_socket(rlm_sql_handle_t *handle, rlm_sql_config_t *config) {
    rlm_sql_unixodbc_sock *unixodbc_sock;
    long err_handle;

	if (!handle->conn) {
		handle->conn = (rlm_sql_unixodbc_sock *)rad_malloc(sizeof(rlm_sql_unixodbc_sock));
		if (!handle->conn) {
			return -1;
		}
	}
	unixodbc_sock = handle->conn;
	memset(unixodbc_sock, 0, sizeof(*unixodbc_sock));

    /* 1. Allocate environment handle and register version */
    err_handle = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&unixodbc_sock->env_handle);
    if (sql_state(err_handle, handle, config))
    {
	radlog(L_ERR, "rlm_sql_unixodbc: Can't allocate environment handle\n");
	return -1;
    }
    err_handle = SQLSetEnvAttr(unixodbc_sock->env_handle, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
    if (sql_state(err_handle, handle, config))
    {
	radlog(L_ERR, "rlm_sql_unixodbc: Can't register ODBC version\n");
	SQLFreeHandle(SQL_HANDLE_ENV, unixodbc_sock->env_handle);
	return -1;
    }
    /* 2. Allocate connection handle */
    err_handle = SQLAllocHandle(SQL_HANDLE_DBC, unixodbc_sock->env_handle, &unixodbc_sock->dbc_handle);
    if (sql_state(err_handle, handle, config))
    {
	radlog(L_ERR, "rlm_sql_unixodbc: Can't allocate connection handle\n");
	SQLFreeHandle(SQL_HANDLE_ENV, unixodbc_sock->env_handle);
	return -1;
    }

    /* 3. Connect to the datasource */
    err_handle = SQLConnect(unixodbc_sock->dbc_handle,
	(SQLCHAR*) config->sql_server, strlen(config->sql_server),
	(SQLCHAR*) config->sql_login, strlen(config->sql_login),
	(SQLCHAR*) config->sql_password, strlen(config->sql_password));
    if (sql_state(err_handle, handle, config))
    {
	radlog(L_ERR, "rlm_sql_unixodbc: Connection failed\n");
	SQLFreeHandle(SQL_HANDLE_DBC, unixodbc_sock->dbc_handle);
	SQLFreeHandle(SQL_HANDLE_ENV, unixodbc_sock->env_handle);
	return -1;
    }

    /* 4. Allocate the statement */
    err_handle = SQLAllocStmt(unixodbc_sock->dbc_handle, &unixodbc_sock->stmt_handle);
    if (sql_state(err_handle, handle, config))
    {
	radlog(L_ERR, "rlm_sql_unixodbc: Can't allocate the statement\n");
	return -1;
    }

    return 0;
}
/*************************************************************************
 *
 *	Function: sql_socket_init
 *
 *	Purpose: Establish connection to the db
 *
 *************************************************************************/
static sql_rcode_t sql_socket_init(rlm_sql_handle_t *handle, rlm_sql_config_t *config) {
    rlm_sql_unixodbc_conn_t *conn;
    long err_handle;

    MEM(conn = handle->conn = talloc_zero(handle, rlm_sql_unixodbc_conn_t));
    talloc_set_destructor((void *) conn, sql_socket_destructor);

    /* 1. Allocate environment handle and register version */
    err_handle = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&conn->env);
    if (sql_state(err_handle, handle, config)) {
        ERROR("rlm_sql_unixodbc: Can't allocate environment handle\n");
        return -1;
    }

    err_handle = SQLSetEnvAttr(conn->env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
    if (sql_state(err_handle, handle, config)) {
        ERROR("rlm_sql_unixodbc: Can't register ODBC version\n");
        SQLFreeHandle(SQL_HANDLE_ENV, conn->env);
        return -1;
    }

    /* 2. Allocate connection handle */
    err_handle = SQLAllocHandle(SQL_HANDLE_DBC, conn->env, &conn->dbc);
    if (sql_state(err_handle, handle, config)) {
        ERROR("rlm_sql_unixodbc: Can't allocate connection handle\n");
        SQLFreeHandle(SQL_HANDLE_ENV, conn->env);
        return -1;
    }

    /* 3. Connect to the datasource */
    {
        SQLCHAR *odbc_server, *odbc_login, *odbc_password;

        memcpy(&odbc_server, &config->sql_server, sizeof(odbc_server));
        memcpy(&odbc_login, &config->sql_login, sizeof(odbc_login));
        memcpy(&odbc_password, &config->sql_password, sizeof(odbc_password));
        err_handle = SQLConnect(conn->dbc,
                                odbc_server, strlen(config->sql_server),
                                odbc_login, strlen(config->sql_login),
                                odbc_password, strlen(config->sql_password));
    }

    if (sql_state(err_handle, handle, config)) {
        ERROR("rlm_sql_unixodbc: Connection failed\n");
        SQLFreeHandle(SQL_HANDLE_DBC, conn->dbc);
        SQLFreeHandle(SQL_HANDLE_ENV, conn->env);
        return -1;
    }

    /* 4. Allocate the statement */
    err_handle = SQLAllocStmt(conn->dbc, &conn->statement);
    if (sql_state(err_handle, handle, config)) {
        ERROR("rlm_sql_unixodbc: Can't allocate the statement\n");
        return -1;
    }

    return 0;
}
StoragePtr TableFunctionODBC::executeImpl(const ASTPtr & ast_function, const Context & context) const
{
    const ASTFunction & args_func = typeid_cast<const ASTFunction &>(*ast_function);

    if (!args_func.arguments)
        throw Exception("Table function 'odbc' must have arguments.", ErrorCodes::LOGICAL_ERROR);

    ASTs & args = typeid_cast<ASTExpressionList &>(*args_func.arguments).children;

    if (args.size() != 2)
        throw Exception("Table function 'odbc' requires exactly 2 arguments: ODBC connection string and table name.",
            ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    for (int i = 0; i < 2; ++i)
        args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context);

    std::string connection_string = static_cast<const ASTLiteral &>(*args[0]).value.safeGet<String>();
    std::string table_name = static_cast<const ASTLiteral &>(*args[1]).value.safeGet<String>();

    Poco::Data::ODBC::SessionImpl session(connection_string, DBMS_DEFAULT_CONNECT_TIMEOUT_SEC);
    SQLHDBC hdbc = session.dbc().handle();

    SQLHSTMT hstmt = nullptr;

    if (Poco::Data::ODBC::Utility::isError(SQLAllocStmt(hdbc, &hstmt)))
        throw Poco::Data::ODBC::ODBCException("Could not allocate connection handle.");

    SCOPE_EXIT(SQLFreeStmt(hstmt, SQL_DROP));

    /// TODO Why not do SQLColumns instead?
    std::string query = "SELECT * FROM " + table_name + " WHERE 1 = 0";
    if (Poco::Data::ODBC::Utility::isError(Poco::Data::ODBC::SQLPrepare(hstmt, reinterpret_cast<SQLCHAR *>(&query[0]), query.size())))
        throw Poco::Data::ODBC::DescriptorException(session.dbc());

    if (Poco::Data::ODBC::Utility::isError(SQLExecute(hstmt)))
        throw Poco::Data::ODBC::StatementException(hstmt);

    SQLSMALLINT cols = 0;
    if (Poco::Data::ODBC::Utility::isError(SQLNumResultCols(hstmt, &cols)))
        throw Poco::Data::ODBC::StatementException(hstmt);

    /// TODO cols not checked

    NamesAndTypesList columns;
    for (SQLSMALLINT ncol = 1; ncol <= cols; ++ncol)
    {
        SQLSMALLINT type = 0;
        /// TODO Why 301?
        SQLCHAR column_name[301];
        /// TODO Result is not checked.
        Poco::Data::ODBC::SQLDescribeCol(hstmt, ncol, column_name, sizeof(column_name), NULL, &type, NULL, NULL, NULL);
        columns.emplace_back(reinterpret_cast<char *>(column_name), getDataType(type));
    }

    auto result = StorageODBC::create(table_name, connection_string, "", table_name, ColumnsDescription{columns});
    result->startup();
    return result;
}
Exemple #13
0
static int  display_columns( SQLHDBC hDbc, char *sql )
{
    SQLHSTMT hStmt;
    SQLRETURN ret;
    char *args[10];
    int n_args;
    SQLCHAR *table;
    int len;

    if ( version3 )
    {
        if ( SQLAllocHandle( SQL_HANDLE_STMT, hDbc, &hStmt ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocHandle( SQL_HANDLE_STMT )\n" );
            return 0;
        }
    }
    else
    {
        if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" );
            return 0;
        }
    }

    n_args = get_args(sql, &args[0], sizeof(args) / sizeof(args[0]));

    if ( n_args == 0 )
    {
        table = NULL;
        len = 0;
    }
    else
    {
        table = (SQLCHAR*)args[ 0 ];
        len = SQL_NTS;
    }

    ret = SQLColumns( hStmt, NULL, 0, NULL, 0, table, len, NULL, 0 );
    if ( ret == SQL_ERROR )
    {
        if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
        fprintf( stderr, "[ISQL]ERROR: Could not SQLTables\n" );
    }
    else
    {
        display_result_set( hDbc, hStmt );
    }

    SQLFreeStmt( hStmt, SQL_DROP );
    free_args(args, sizeof(args) / sizeof(args[0]));

    return 1;
}
Exemple #14
0
static HB_ERRCODE odbcExecute( SQLDDCONNECTION * pConnection, PHB_ITEM pItem )
{
   SDDCONN *         pSDDConn = ( SDDCONN * ) pConnection->pSDDConn;
   const O_HB_CHAR * pchStatement;
   void *            hStatement;
   HB_SIZE           nStatementLen;
   SQLHSTMT          hStmt;
   SQLLEN            iCount;
   char *            szError;
   HB_ERRCODE        errCode;
   SQLRETURN         result;

#if ODBCVER >= 0x0300
   if( ! SQL_SUCCEEDED( SQLAllocHandle( SQL_HANDLE_STMT, pSDDConn->hConn, &hStmt ) ) )
#else
   if( ! SQL_SUCCEEDED( SQLAllocStmt( pSDDConn->hConn, &hStmt ) ) )
#endif
   {
      szError = odbcGetError( pSDDConn->hEnv, pSDDConn->hConn, SQL_NULL_HSTMT, &errCode );
      hb_errRT_ODBCDD( EG_OPEN, ESQLDD_STMTALLOC, szError, hb_itemGetCPtr( pItem ), errCode );
      hb_xfree( szError );
      return HB_FAILURE;
   }

   pchStatement = O_HB_ITEMGETSTR( pItem, &hStatement, &nStatementLen );
   result = SQLExecDirect( hStmt,
                           ( SQLTCHAR * ) HB_UNCONST( pchStatement ),
                           ( SQLINTEGER ) nStatementLen );
   hb_strfree( hStatement );

   if( SQL_SUCCEEDED( result ) )
   {

      if( SQL_SUCCEEDED( SQLRowCount( hStmt, &iCount ) ) )
      {
         /* TODO: new id */
         hb_rddsqlSetError( 0, NULL, hb_itemGetCPtr( pItem ), NULL, ( unsigned long ) iCount );
#if ODBCVER >= 0x0300
         SQLFreeHandle( SQL_HANDLE_STMT, hStmt );
#else
         SQLFreeStmt( hStmt, SQL_DROP );
#endif
         return HB_SUCCESS;
      }
   }

   szError = odbcGetError( pSDDConn->hEnv, pSDDConn->hConn, hStmt, &errCode );
   hb_rddsqlSetError( errCode, szError, hb_itemGetCPtr( pItem ), NULL, errCode );
   hb_xfree( szError );
#if ODBCVER >= 0x0300
   SQLFreeHandle( SQL_HANDLE_STMT, hStmt );
#else
   SQLFreeStmt( hStmt, SQL_DROP );
#endif
   return HB_FAILURE;
}
Exemple #15
0
void CheckEventJoin(CHARLIST *ch)		// 020115 LTS
{
	HSTMT	hStmt=NULL;
	RETCODE	ret;
	SWORD	nClos;
	char	query_stmt[80]={0,};
	SDWORD	cbValue;
	int		tempEventJoin[8];

	//ch->EventJoin=1;	// 나중에 나머지는 주석 처리 한다.

	SQLAllocStmt(hDBC,&hStmt);

	wsprintf(query_stmt,"select * from EventUser Where CharacterName='%s'",ch->Name);
	ret = SQLExecDirect(hStmt,(UCHAR*)query_stmt,SQL_NTS);
	if (ret!=SQL_SUCCESS_WITH_INFO && ret !=SQL_SUCCESS)
	{
		//MyLog(0,"Query Failure!! Event User Data.. (Not Join Event..)");
		SQLFreeStmt(hStmt,SQL_DROP);
		memset(&ch->EventJoin,0,1);
		return;
	}
	SQLNumResultCols(hStmt,&nClos);

	ret=SQLFetch(hStmt);
	if (ret!=SQL_SUCCESS_WITH_INFO && ret !=SQL_SUCCESS)
	{
		//MyLog(0,"Query Failure!! Event User Data.. (Not Join Event..)");
		SQLFreeStmt(hStmt,SQL_DROP);
		memset(&ch->EventJoin,0,1);
		return ;
	}
	for (int i=0;i<8;i++)
	{
		ret=SQLGetData(hStmt,3+i,SQL_C_SLONG,&tempEventJoin[i],sizeof(int),&cbValue);	// Event1
		if (ret!=SQL_SUCCESS_WITH_INFO && ret!=SQL_SUCCESS)
		{
			MyLog(0,"Query Failure!! Event User Data.. (Get Data..)",ret);
			SQLFreeStmt(hStmt,SQL_DROP);
			memset(&ch->EventJoin,0,1);
			return ;
		}   
	}

    SQLFreeStmt(hStmt,SQL_DROP);

	ch->EventJoin.Event1=tempEventJoin[0];
	ch->EventJoin.Event2=tempEventJoin[1];
	ch->EventJoin.Event3=tempEventJoin[2];
	ch->EventJoin.Event4=tempEventJoin[3];
	ch->EventJoin.Event5=tempEventJoin[4];
	ch->EventJoin.Event6=tempEventJoin[5];
	ch->EventJoin.Event7=tempEventJoin[6];
	ch->EventJoin.Event8=tempEventJoin[7];
}
Exemple #16
0
/*
 *  Perform a disconnect/reconnect using the DSN stored from the original
 *  SQLDriverConnect
 */
int 
ODBC_Reconnect (void)
{
  SQLRETURN status;
  SQLTCHAR buf[4096];
  SQLSMALLINT len;

  /*
   *  Free old statement handle
   */
#if (ODBCVER < 0x0300)
  SQLFreeStmt (hstmt, SQL_DROP);
#else
  SQLFreeHandle (SQL_HANDLE_STMT, hstmt);
#endif

  /*
   *  Disconnect
   */
  SQLDisconnect (hdbc);

  /*
   *  Reconnect
   */
  status = SQLDriverConnect (hdbc, 0, outdsn, SQL_NTS,
      buf, sizeof (buf), &len, SQL_DRIVER_NOPROMPT);

  /*
   *  Allocate new statement handle
   */
  if (SQL_SUCCEEDED (status))
    {
#if (ODBCVER < 0x0300)
      status = SQLAllocStmt (hdbc, &hstmt);
#else
      status = SQLAllocHandle (SQL_HANDLE_STMT, hdbc, &hstmt);
#endif
    }

  /*
   *  Show why we where unsuccessful and return an error
   */
  if (!SQL_SUCCEEDED (status))
    {
      ODBC_Errors ("DriverConnect (reconnect)");
      return -1;
    }

  /*
   *  Success
   */
  return 0;
}
Exemple #17
0
void CSQLDirect::Close( void )
{
	if( m_hStmt!=NULL ) {
		// Free
		SQLFreeStmt( m_hStmt, SQL_DROP );

		KillCols();

		// Allocate again.
		SQLAllocStmt( m_hDBC,&m_hStmt );
	}
}
Exemple #18
0
void
tw_exec (t1_window_t * tw, char * text)
{
  HSTMT stmt;
  SQLAllocStmt (tw->tw_hdbc, &stmt);
  tw->tw_rc = SQLExecDirect (stmt, (SQLCHAR *) text, SQL_NTS);
  SQLRowCount (stmt, &tw->tw_row_count);
  if (!quiet)
    printf ("Exec %s = %d, %ld rows\n", text, tw->tw_rc, tw->tw_row_count);
  IF_ERR_GO (stmt, err, tw->tw_rc);
 err:
  SQLFreeStmt (stmt, SQL_DROP);
}
Exemple #19
0
void
t1_delete (t1_window_t * tw, long row_no)
{
  int rc;
  HSTMT upd;
  SQLAllocStmt (tw->tw_hdbc, &upd);
  IBINDL (upd, 1, row_no);
  rc = SQLExecDirect (upd, (SQLCHAR *) "delete from T1 where  ROW_NO = ?", SQL_NTS);
  printf ("delete from T1 where ROW_NO = %ld == %d\n",row_no, rc);
  IF_ERR_GO (upd, err, rc);
 err:
  SQLFreeStmt (upd, SQL_DROP);
}
Exemple #20
0
void classTable::LoadColumns()
{
	SQLHSTMT        hstmt;
	SQLRETURN		nReturn             = -1;
	SQLCHAR         szTableName[101]	= "";
	SQLCHAR         szColumnName[101]	= "";
	SQLCHAR         szColumnType[101]	= "";
	SQLCHAR         szDescription[301]	= "";
	QString         qsError;
    classColumn     *pColumn = NULL;

	// CREATE A STATEMENT
	nReturn = SQLAllocStmt( hDbc, &hstmt );
	if ( nReturn != SQL_SUCCESS )
	{
		QMessageBox::warning( pCanvas, "Data Manager",  "Failed to SQLAllocStmt" );
		return;
	}

	// EXECUTE OUR SQL/CALL
	strcpy( (char *)szTableName, qsName.data() );

	if ( SQL_SUCCESS != (nReturn=SQLColumns( hstmt, 0, 0, 0, 0, szTableName, SQL_NTS, 0, 0 )) )
	{
		QMessageBox::warning( pCanvas, "Data Manager",  "Failed to SQLColumns" );
		return;
	}

	// GET RESULTS
	nReturn = SQLFetch( hstmt );
	while ( nReturn == SQL_SUCCESS || nReturn == SQL_SUCCESS_WITH_INFO )
	{
        szDescription[0] = '\0';

		nReturn = SQLGetData( hstmt, SQLColumns_COLUMN_NAME, SQL_C_CHAR, &szColumnName[0], sizeof(szColumnName), 0 );
		if ( nReturn != SQL_SUCCESS )
			strcpy( (char *)szColumnName, "Unknown" );

		nReturn = SQLGetData( hstmt, SQLColumns_TYPE_NAME, SQL_C_CHAR, &szColumnType[0], sizeof(szColumnType), 0 );

		listColumns.append( pColumn = new classColumn( this, pColumn, pCanvas, hDbc, (char *)szColumnName, (char*)szColumnType, (char*)szDescription ) );

		nReturn = SQLFetch( hstmt );
	}

	// FREE STATEMENT
	nReturn = SQLFreeStmt( hstmt, SQL_DROP );
	if ( nReturn != SQL_SUCCESS )
		QMessageBox::warning( pCanvas, "Data Manager",  "Failed to SQLFreeStmt" );

}
Exemple #21
0
void
t1_update (t1_window_t * tw, long row_no, char * fs1)
{
  int rc;
  HSTMT upd;
  SQLAllocStmt (tw->tw_hdbc, &upd);
  IBINDNTS (upd, 1, fs1);
  IBINDL (upd, 2, row_no);
  rc = SQLExecDirect (upd, (SQLCHAR *) "update T1 set FS1 = ? where ROW_NO = ?", SQL_NTS);
  printf ("Update T1 set FS1 = %s where ROW_NO = %ld == %d\n", fs1, row_no, rc);
  IF_ERR_GO (upd, err, rc);
 err:
  SQLFreeStmt (upd, SQL_DROP);
}
Exemple #22
0
/* We need also a separate database-table-info command, like the
   database-field-info command, which you can use to get more info
   about a specific table. */
static gsql_result *
gsql_db_list_tables (Database *db, 
		     char *table_qualifier, 
		     char *table_owner,
		     char *table_name,
		     char *table_type)
{
  gsql_result *gr = (gsql_result *) NULL;
  HSTMT hstmt;
  RETCODE status;

  /* Issue an SQLTables request, and then create a result set. */
  gsql_clear_error_message ();

  if (table_qualifier == (char *) NULL)
    table_qualifier = "";
  if (table_owner == (char *) NULL)
    table_owner = "";
  if (table_name == (char *) NULL)
    table_name = "";
  if (table_type == (char *) NULL)
    table_type = "";

  if (SQLAllocStmt (db->hdbc, &hstmt) != SQL_SUCCESS)
    {
      gsql_save_error_message (db, "SQLAllocStmt");
      return ((gsql_result *)NULL);
    }

  status = SQLTables (hstmt,
		      (unsigned char *)table_qualifier, SQL_NTS,
		      (unsigned char *)table_owner, SQL_NTS,
		      (unsigned char *)table_name, SQL_NTS,
		      (unsigned char *)table_type, SQL_NTS);

  if (status != SQL_SUCCESS)
    {
      gsql_save_error_message (db, "SQLTables");
      return ((gsql_result *)NULL);
    }

  /* gsql_store_result() will copy the HSTMT to a result struct,
     and it will eventually be freed when someone calls gsql_free_result. */
  db->hstmt = hstmt;
  gr = gsql_store_result (db);

  return (gr);
}
Exemple #23
0
int LoadChangeItem()//010708 lsw
{
	HSTMT		hStmt = NULL;
	RETCODE		retCode;
	SDWORD		cbValue;

	SQLAllocStmt(hDBC, &hStmt);
	retCode = SQLExecDirect(hStmt, (UCHAR *)"Select * from item_change order by original", SQL_NTS);
	if(retCode == SQL_SUCCESS || retCode == SQL_SUCCESS_WITH_INFO)
	{		
		int i = 0;
		retCode = SQLFetch(hStmt);
		while( retCode == SQL_SUCCESS || retCode == SQL_SUCCESS_WITH_INFO)
		{
			if(i >= MAX_CHANGE_ITEM_COUNT)//020730 lsw
			{
				SQLFreeStmt(hStmt, SQL_DROP);
				return 0;
			}

			retCode = SQLGetData(hStmt, 1, SQL_C_LONG,	&itemchange[i].origin_item_no		, 0, &cbValue);
			retCode = SQLGetData(hStmt, 2, SQL_C_LONG,	&itemchange[i].will_change_item_no	, 0, &cbValue);
			retCode = SQLGetData(hStmt, 3, SQL_C_LONG,	&itemchange[i].add_soksung			, 0, &cbValue);
			retCode = SQLGetData(hStmt, 4, SQL_C_LONG,	&itemchange[i].add_grade			, 0, &cbValue);
			
			ichangeItemCount=i;			
			i++;

			retCode = SQLFetch(hStmt);
			if(retCode == SQL_SUCCESS || retCode == SQL_SUCCESS_WITH_INFO)
			{
			}
			else if( retCode == SQL_NO_DATA ) 
			{
				break;
			}
			else
			{
				SQLFreeStmt(hStmt, SQL_DROP);
				return 0;
			}
		}	
	}		


	SQLFreeStmt(hStmt, SQL_DROP);		// 0308 YGI
	return(1);
}
Exemple #24
0
int odbc_command(ClipMachine* cm,SQLSTMT* s,ClipVar* ap){
	ODBC_STMT* stmt = (ODBC_STMT*)s;
	SQLRETURN er;
	SDWORD count;

	odbc_bindpars(stmt,ap);
	if((er = SQLAllocStmt(stmt->conn->conn,&stmt->hstmt))) goto err;
	if((er = SQLPrepare(stmt->hstmt,stmt->sql,strlen(stmt->sql)))) goto err;
	if((er = SQLExecute(stmt->hstmt))) goto err;
	if((er = SQLRowCount(stmt->hstmt,&count))) goto err;
	if(count < 0)
		count = 0;
	return count;
err:
	return odbc_error(cm,stmt->conn->loc,0,stmt->conn->conn,stmt->hstmt,__LINE__,er_execute);
}
Exemple #25
0
int main(int argc, char **argv)
{
	SQLRETURN rc;
	HSTMT hstmt = SQL_NULL_HSTMT;

	test_connect();

	rc = SQLAllocStmt(conn, &hstmt);
	if (!SQL_SUCCEEDED(rc))
	{
		print_diag("failed to allocate stmt handle", SQL_HANDLE_DBC, conn);
		exit(1);
	}

	/* Create a table to test with */
	rc = SQLExecDirect(hstmt, (SQLCHAR *) "CREATE TEMPORARY TABLE testtbl(t varchar(40))", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	/**** A simple query against the table, fetch column info ****/

	rc = SQLExecDirect(hstmt, "SELECT * FROM testtbl", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	/* Get column metadata */
	print_result_meta(hstmt);

	rc = SQLFreeStmt(hstmt, SQL_CLOSE);
	CHECK_STMT_RESULT(rc, "SQLFreeStmt failed", hstmt);

	/* Alter the table */
	rc = SQLExecDirect(hstmt, (SQLCHAR *) "ALTER TABLE testtbl ALTER COLUMN t TYPE varchar(80)", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	/* Run the query again, check if the metadata was updated */

	rc = SQLExecDirect(hstmt, "SELECT * FROM testtbl", SQL_NTS);
	CHECK_STMT_RESULT(rc, "SQLExecDirect failed", hstmt);

	/* Get column metadata */
	print_result_meta(hstmt);

	/* Clean up */
	test_disconnect();

	return 0;
}
void classSpecialColumns::LoadColumns()
{
	SQLHSTMT        hstmt;
	SQLRETURN		nReturn             = -1;
	SQLCHAR         szTableName[101]	= "";
	SQLCHAR         szColumnName[101]	= "";
	QString         qsError;

	// CREATE A STATEMENT
	nReturn = SQLAllocStmt( hDbc, &hstmt );
	if ( nReturn != SQL_SUCCESS )
	{
		QMessageBox::warning( pCanvas, "Data Manager",  "Failed to SQLAllocStmt" );
		return;
	}

	// EXECUTE OUR SQL/CALL
	strcpy( (char *)szTableName, qsTable.data() );

	if ( SQL_SUCCESS != (nReturn=SQLSpecialColumns( hstmt, SQL_BEST_ROWID, 0, 0, 0, 0, szTableName, SQL_NTS, SQL_SCOPE_SESSION, SQL_NULLABLE )) )
	{
		QMessageBox::warning( pCanvas, "Data Manager",  "Failed to SQLSpecialColumns" );
		return;
	}

	// GET RESULTS
	nReturn = SQLFetch( hstmt );
	while ( nReturn == SQL_SUCCESS || nReturn == SQL_SUCCESS_WITH_INFO )
	{
		nReturn = SQLGetData( hstmt, 2, SQL_C_CHAR, &szColumnName[0], sizeof(szColumnName), 0 );
		if ( nReturn != SQL_SUCCESS )
			strcpy( (char *)szColumnName, "Unknown" );

		listColumns.append( new classColumn( this, pCanvas, hDbc, (char *)szColumnName ) );

		nReturn = SQLFetch( hstmt );
	}

	// FREE STATEMENT
	nReturn = SQLFreeStmt( hstmt, SQL_DROP );
	if ( nReturn != SQL_SUCCESS )
		QMessageBox::warning( pCanvas, "Data Manager",  "Failed to SQLFreeStmt" );

}
Exemple #27
0
int cezdb::SendSQL( char *str )
{
	RETCODE res;
	if ( flag != CEZDB_MODE_DBCREADY ) return -1;

	res = SQLAllocStmt( hdbc, &hstmt );
	if ( res != SQL_SUCCESS ) {
		return -2;
	}
//	strcpy( (char *)sendsql, str );
//	res = SQLExecDirect( hstmt, sendsql, strlen( (char *)sendsql ) );
	res = SQLExecDirect( hstmt, (unsigned char *)str, SQL_NTS );
	if (( res != SQL_SUCCESS )&&( res != SQL_SUCCESS_WITH_INFO )) {
		return -3;
	}

	flag = CEZDB_MODE_SQLFETCH;
	return 0;
}
Exemple #28
0
void RecvCMD_SET_WARFIELD_POSSESSION(t_packet *p, t_connection c[], int cn )
{
	HSTMT	hStmt=NULL;
	RETCODE	ret;
	char	query_stmt[80]={0,};

	SQLAllocStmt(hDBC,&hStmt);

	wsprintf(query_stmt,"update WarfieldTBL set NationCode=%d where WarfieldCode=%d",p->u.NationWar.SWarfieldPossession.Possession,p->u.NationWar.SWarfieldPossession.WarfieldNo);

	ret = SQLExecDirect(hStmt,(UCHAR*)query_stmt,SQL_NTS);
	if (ret!=SQL_SUCCESS_WITH_INFO && ret !=SQL_SUCCESS)
	{
		MyLog(0,"Update Query Failure!! RecvCMD_SET_WARFIELD_POSSESION");
		SQLFreeStmt(hStmt,SQL_DROP);
		return;
	}
	SQLFreeStmt(hStmt,SQL_DROP);
}
Exemple #29
0
void RecvCMD_SAVE_WARNO(t_packet *p, t_connection c[], int cn )
{
	HSTMT	hStmt=NULL;
	RETCODE	ret;
	char	query_stmt[80]={0,};

	SQLAllocStmt(hDBC,&hStmt);
	wsprintf(query_stmt,"update WarStartUpTBL set DayofWeek=%d where Type=-1",p->u.NationWar.CommonDataDw);

	ret = SQLExecDirect(hStmt,(UCHAR*)query_stmt,SQL_NTS);
	if (ret!=SQL_SUCCESS_WITH_INFO && ret !=SQL_SUCCESS)
	{
		MyLog(0,"Update WarNo Error!!");
		SQLFreeStmt(hStmt,SQL_DROP);
		return;
	}
	MyLog(0,"Update WarNo : %d",p->u.NationWar.CommonDataDw.Data);
	SQLFreeStmt(hStmt,SQL_DROP);
}
Exemple #30
0
/**********************************************************************
** get_table_info
**
** This function fills in the needed information into the array of table
** descriptions.
**********************************************************************/
short get_table_info(table_description *table_ptr[],short table_count)
{
   short i;
   ReturnStatus *RSPtr;
	HENV	henv;
	HDBC	hdbc;
	HSTMT hstmt;
	Boolean connected;
	RETCODE rc;

	RSPtr=NULL;
	// start a connection so we can use it to get the table info
	connected=FullConnect(gDataSource,gUID,gPWD,&henv,&hdbc);
	if(!connected) return(FAILURE);
	rc=SQLAllocStmt(hdbc,&hstmt);
	//>>>> check return code ???

   /* for each table, determine its format */
   for(i=0;i<table_count;i++){

      /* get format of table records, including column names */
      if(table_ptr[i]->Organization==KEY_SEQ){
         table_ptr[i]->pTable=GetTableInfo(hdbc,table_ptr[i]->TableName,FALSE,&RSPtr);
         }
      else{
         table_ptr[i]->pTable=GetTableInfo(hdbc,table_ptr[i]->TableName,TRUE,&RSPtr);
         }

      if(table_ptr[i]->pTable==NULL) {
			LogReturnStatus(RSPtr);
			FreeReturnStatus(RSPtr);
			return(FAILURE);
			}
		else{
			table_ptr[i]->henv=NULL;
			table_ptr[i]->hdbc=NULL;
			table_ptr[i]->hstmt=NULL;
			}
      }

	FullDisconnect(henv,hdbc);
   return(SUCCESS);
   } /* end of get_table_info() */