Esempio n. 1
0
OdbcHandle odbcConnect(const char* dbname,
                       const char* servername,
                       const char* username,
                       const char* driver,
                       const char* password)

{
   OdbcHandle handle = new OdbcControlStruct;

   if (handle)
   {
      if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV,
                                        SQL_NULL_HANDLE,
                                        &handle->mEnvironmentHandle)))
      {
         Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                       "odbcConnect: Failed to allocate "
                       "environment handle");
         delete handle;
         handle = NULL;
      }
      else
      {
         SQLSetEnvAttr(handle->mEnvironmentHandle, SQL_ATTR_ODBC_VERSION,
                       (void*) SQL_OV_ODBC3, 0);

         if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC,
                                            handle->mEnvironmentHandle,
                                            &handle->mConnectionHandle)))
         {
            Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                          "odbcConnect: Failed to allocate "
                          "connection handle");
            extract_error("SQLSetEnvAttr", handle->mEnvironmentHandle, SQL_HANDLE_ENV);
            SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle);
            delete handle;
            handle = NULL;
         }
         else
         {
            // Connect - contruct connection string
            UtlString connectionString;
            char temp[128];

            if (dbname)
            {
               sprintf(temp, "DATABASE=%s;", dbname);
               connectionString.append(temp);
            }
            if (servername)
            {
               sprintf(temp, "SERVER=%s;", servername);
               connectionString.append(temp);
            }
            if (username)
            {
               sprintf(temp, "UID=%s;", username);
               connectionString.append(temp);
            }
            if (password)
            {
               sprintf(temp, "PWD=%s;", password);
               connectionString.append(temp);
            }
            else
            {
               connectionString.append("PWD=;");
            }
            if (driver)
            {
               sprintf(temp, "DRIVER=%s;", driver);
               connectionString.append(temp);
            }
            // Connect in read/write mode
            connectionString.append("READONLY=0;");

            SQLRETURN sqlRet =
                  SQLDriverConnect(handle->mConnectionHandle,
                                   NULL,
                                   (SQLCHAR*)connectionString.data(),
                                   SQL_NTS,
                                   NULL,
                                   0,
                                   NULL,
                                   SQL_DRIVER_NOPROMPT);

            if (!SQL_SUCCEEDED(sqlRet))
            {
               Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                             "odbcConnect: Failed to connect %s, error code %d",
                             connectionString.data(), sqlRet);
               extract_error("SQLDriverConnect", handle->mConnectionHandle, SQL_HANDLE_DBC);

               SQLFreeHandle(SQL_HANDLE_DBC, handle->mConnectionHandle);
               SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle);
               delete handle;
               handle = NULL;
            }
            else
            {
               // Connected to database, now alloc a statement handle
               if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_STMT,
                                                handle->mConnectionHandle,
                                                &handle->mStatementHandle)))
               {
                  Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                                "odbcConnect: Failed to allocate "
                                "statement handle");
                  extract_error("SQLAllocHandle", handle->mStatementHandle, SQL_HANDLE_STMT);

                  // Disconnect from database
                  SQLDisconnect(handle->mConnectionHandle);
                  // Free resources

                  SQLFreeHandle(SQL_HANDLE_DBC, handle->mConnectionHandle);
                  SQLFreeHandle(SQL_HANDLE_ENV, handle->mEnvironmentHandle);
                  delete handle;
                  handle = NULL;
               }
               else
               {
                  Os::Logger::instance().log(FAC_ODBC, PRI_DEBUG,
                                "odbcConnect: Connected to database "
                                "%s, OdbcHandle %p",
                                connectionString.data(), handle);
                }
            }
         }
      }
   }
   else
   {
      Os::Logger::instance().log(FAC_ODBC, PRI_ERR,
                    "odbcConnect: Couldn't create OdbcHandle");
   }

   return handle;
}
Esempio n. 2
0
/****************************
 * OpenDatabase - do everything we have to do to get a viable connection to szDSN
 ***************************/
static int
OpenDatabase( SQLHENV *phEnv, SQLHDBC *phDbc, char *szDSN, char *szUID, char *szPWD )
{
    if ( version3 )
    {
        if ( SQLAllocHandle( SQL_HANDLE_ENV, NULL, phEnv ) != SQL_SUCCESS )
        {
            fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocHandle( SQL_HANDLE_ENV )\n" );
            return 0;
        }

        if ( SQLSetEnvAttr( *phEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) 3, 0 ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, 0, 0 );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLSetEnvAttr( SQL_HANDLE_DBC )\n" );
            SQLFreeHandle( SQL_HANDLE_ENV, *phEnv );
            return 0;
        }

        if ( SQLAllocHandle( SQL_HANDLE_DBC, *phEnv, phDbc ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, 0, 0 );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocHandle( SQL_HANDLE_DBC )\n" );
            SQLFreeHandle( SQL_HANDLE_ENV, *phEnv );
            return 0;
        }

        if ( !SQL_SUCCEEDED( SQLConnect( *phDbc, (SQLCHAR*)szDSN, SQL_NTS, (SQLCHAR*)szUID, SQL_NTS, (SQLCHAR*)szPWD, SQL_NTS )))
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLConnect\n" );
            SQLFreeHandle( SQL_HANDLE_DBC, *phDbc );
            SQLFreeHandle( SQL_HANDLE_ENV, *phEnv );
            return 0;
        }
    }
    else
    {
        if ( SQLAllocEnv( phEnv ) != SQL_SUCCESS )
        {
            fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocEnv\n" );
            return 0;
        }

        if ( SQLAllocConnect( *phEnv, phDbc ) != SQL_SUCCESS )
        {
            if ( bVerbose ) DumpODBCLog( hEnv, 0, 0 );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocConnect\n" );
            SQLFreeEnv( *phEnv );
            return 0;
        }

        if ( !SQL_SUCCEEDED( SQLConnect( *phDbc, (SQLCHAR*)szDSN, SQL_NTS, (SQLCHAR*)szUID, SQL_NTS, (SQLCHAR*)szPWD, SQL_NTS )))
        {
            if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
            fprintf( stderr, "[ISQL]ERROR: Could not SQLConnect\n" );
            SQLFreeConnect( *phDbc );
            SQLFreeEnv( *phEnv );
            return 0;
        }
    }

    /*
     * does the driver support SQLMoreResults
     */

    if ( !SQL_SUCCEEDED( SQLGetFunctions( *phDbc, SQL_API_SQLMORERESULTS, &has_moreresults )))
    {
        has_moreresults = 0;
    }

    return 1;
}
Esempio n. 3
0
int main(int argc, char **argv)
{
  std::string app_name = base::basename(argv[0]);

  base::threading_init();
  
  TaskQueue tables;

  std::string source_password;
  std::string source_connstring;
  bool source_use_cleartext_plugin = false;
  bool source_is_utf8 = false;
  std::string source_charset;
  SourceType source_type = ST_MYSQL;

  std::string target_connstring;
  std::string target_password;
  bool target_use_cleartext_plugin = false;
  std::string log_level;
  std::string log_file;

  bool passwords_from_stdin = false;
  bool count_only = false;
  bool check_types_only = false;
  bool truncate_target = false;
  bool show_progress = false;
  bool abort_on_oversized_blobs = false;
  bool disable_triggers = false;
  bool reenable_triggers = false;
  bool disable_triggers_on_copy = true;
  bool resume = false;
  int thread_count = 1;
  long long bulk_insert_batch = 100;
  long long max_count = 0;

  std::string table_file;

  std::set<std::string> trigger_schemas;
  std::string source_rdbms_type = "unknown";

  bool log_level_set = false;
  int i = 1;
  while (i < argc)
  {
    char *argval = NULL;

    if (check_arg_with_value(argv, i, "--log-level", argval, true))
      log_level = argval;
    else if (check_arg_with_value(argv, i, "--log-file", argval, true))
      log_file = argval;
    else if (check_arg_with_value(argv, i, "--odbc-source", argval, true))
    {
      source_type = ST_ODBC;
      source_connstring = base::trim(argval, "\"");
    }
    else if (check_arg_with_value(argv, i, "--mysql-source", argval, true))
    {
      source_type = ST_MYSQL;
      source_connstring = base::trim(argval, "\"");
    }
    else if (check_arg_with_value(argv, i, "--pythondbapi-source", argval, true))
    {
      source_type = ST_PYTHON;
      source_connstring = base::trim(argval, "\"");
    }
    else if (check_arg_with_value(argv, i, "--source-password", argval, true))
      source_password = argval;
    else if (check_arg_with_value(argv, i, "--target-password", argval, true))
      target_password = argval;
    else if (strcmp(argv[i], "--force-utf8-for-source") == 0)
      source_is_utf8 = true;
    else if (check_arg_with_value(argv, i, "--source-charset", argval, true))
      source_charset = argval;
    else if (strcmp(argv[i], "--progress") == 0)
      show_progress = true;
    else if (strcmp(argv[i], "--truncate-target") == 0)
      truncate_target = true;
    else if (strcmp(argv[i], "--count-only") == 0)
    {
      // Count only will be allowed only if one of the trigger
      // operations has not been indicated first
      if ( !disable_triggers && !reenable_triggers)
        count_only = true;
    }
    else if (strcmp(argv[i], "--check-types-only") == 0)
      check_types_only = true;
    else if (strcmp(argv[i], "--passwords-from-stdin") == 0)
      passwords_from_stdin = true;
    else if (strcmp(argv[i], "--abort-on-oversized-blobs") == 0)
      abort_on_oversized_blobs = true;
    else if (strcmp(argv[i], "--dont-disable-triggers") == 0)
      disable_triggers_on_copy = false;
    else if (strcmp(argv[i], "--resume") == 0)
      resume = true;
    else if (check_arg_with_value(argv, i, "--disable-triggers-on", argval, true))
    {
      // disabling/enabling triggers are standalone operations and mutually exclusive
      // so here it ensures a request for trigger enabling was not found first
      if (!reenable_triggers && !count_only)
      {
        disable_triggers = true;
        trigger_schemas.insert(argval);
      }
    }
    else if (check_arg_with_value(argv, i, "--reenable-triggers-on", argval, true))
    {
      // disabling/enabling triggers are standalone operations and mutually exclusive
      // so here it ensures a request for trigger enabling was not found first
      if (!disable_triggers && !count_only)
      {
        reenable_triggers = true;
        trigger_schemas.insert(argval);
      }
    }
    else if (check_arg_with_value(argv, i, "--thread-count", argval, true))
    {
      thread_count = base::atoi<int>(argval, 0);
      if (thread_count < 1)
        thread_count = 1;
    }
    else if (check_arg_with_value(argv, i, "--bulk-insert-batch-size", argval, true))
    {
      bulk_insert_batch = base::atoi<int>(argval, 0);
      if (bulk_insert_batch < 1)
        bulk_insert_batch = 100;
    }
    else if (strcmp(argv[i], "--version") == 0)
    {
      const char *type = APP_EDITION_NAME;
      if (strcmp(APP_EDITION_NAME, "Community") == 0)
        type = "CE";

      printf("%s %s (%s) %i.%i.%i %s build %i\n"
             , base::basename(argv[0]).c_str()
             , type, APP_LICENSE_TYPE
             , APP_MAJOR_NUMBER
             , APP_MINOR_NUMBER
             , APP_RELEASE_NUMBER
             , APP_RELEASE_TYPE
             , APP_BUILD_NUMBER
            );
      exit(0);
    }
    else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
    {
      show_help();
      exit(0);
    }
    else if (check_arg_with_value(argv, i, "--target", argval, true))
    {
      target_connstring = base::trim(argval, "\"");
    }
    else if (check_arg_with_value(argv, i, "--table-file", argval, true))
      table_file = argval;
    else if (strcmp(argv[i], "--table") == 0)
    {
      TableParam param;

      if ((!count_only && i + 7 >= argc) || (count_only && i + 2 >= argc))
      {
        fprintf(stderr, "%s: Missing value for table copy specification\n", argv[0]);
        exit(1);
      }

      param.source_schema = argv[++i];
      param.source_table = argv[++i];
      if (!(count_only && !resume))
      {
        param.target_schema = argv[++i];
        param.target_table = argv[++i];
        if(std::strcmp(argv[++i], "-") != 0)
          param.source_pk_columns = base::split(argv[i], ",", -1);
        if(std::strcmp(argv[++i], "-") != 0)
          param.target_pk_columns = base::split(argv[i], ",", -1);
        param.select_expression = argv[++i];

        trigger_schemas.insert(param.target_schema);
      }

      param.copy_spec.resume = resume;
      param.copy_spec.max_count = max_count;

      param.copy_spec.type = CopyAll;

      tables.add_task(param);
    }
    else if (strcmp(argv[i], "--table-range") == 0)
    {
      TableParam param;

      if ((!count_only && i + 10 >= argc) || (count_only && i + 5 >= argc))
      {
        fprintf(stderr, "%s: Missing value for table copy specification\n", argv[0]);
        exit(1);
      }
      param.source_schema = argv[++i];
      param.source_table = argv[++i];
      if (!(count_only && !resume))
      {
        param.target_schema = argv[++i];
        param.target_table = argv[++i];
        if(std::strcmp(argv[++i], "-") != 0)
          param.source_pk_columns = base::split(argv[i], ",", -1);
        if(std::strcmp(argv[++i], "-") != 0)
          param.target_pk_columns = base::split(argv[i], ",", -1);
        param.select_expression = argv[++i];

        trigger_schemas.insert(param.target_schema);
      }
      param.copy_spec.range_key = argv[++i];
      param.copy_spec.range_start = base::atoi<long long>(argv[++i], 0ll);
      param.copy_spec.range_end = base::atoi<long long>(argv[++i], 0ll);
      param.copy_spec.type = CopyRange;

      tables.add_task(param);
    }
    else if (strcmp(argv[i], "--table-row-count") == 0)
    {
      TableParam param;

      if ((!count_only && i + 8 >= argc) || (count_only && i + 3 >= argc))
      {
        fprintf(stderr, "%s: Missing value for table copy specification\n", argv[0]);
        exit(1);
      }
      param.source_schema = argv[++i];
      param.source_table = argv[++i];
      if (!(count_only && !resume))
      {
        param.target_schema = argv[++i];
        param.target_table = argv[++i];
        if(std::strcmp(argv[++i], "-") != 0)
          param.source_pk_columns = base::split(argv[i], ",", -1);
        if(std::strcmp(argv[++i], "-") != 0)
          param.target_pk_columns = base::split(argv[i], ",", -1);
        param.select_expression = argv[++i];
      }
      param.copy_spec.row_count = base::atoi<long long>(argv[++i], 0ll);
      param.copy_spec.resume = resume;
      param.copy_spec.type = CopyCount;

      tables.add_task(param);
    }
    else if (check_arg_with_value(argv, i, "--source-rdbms-type", argval, false))
    	source_rdbms_type = argval;
    else if (strcmp(argv[i], "--table-where") == 0)
    {
      TableParam param;

      if ((!count_only && i + 8 >= argc) || (count_only && i + 4 >= argc))
      {
        fprintf(stderr, "%s: Missing value for table copy specification\n", argv[0]);
        exit(1);
      }
      param.source_schema = argv[++i];
      param.source_table = argv[++i];
      if (!(count_only && !resume))
      {
        param.target_schema = argv[++i];
        param.target_table = argv[++i];
        if(std::strcmp(argv[++i], "-") != 0)
          param.source_pk_columns = base::split(argv[i], ",", -1);
        if(std::strcmp(argv[++i], "-") != 0)
          param.target_pk_columns = base::split(argv[i], ",", -1);
        param.select_expression = argv[++i];
        param.copy_spec.where_expression = argv[++i];

        trigger_schemas.insert(param.target_schema);
      }
      else
      {
        param.select_expression = argv[++i];
        param.copy_spec.where_expression = argv[++i];
      }
      param.copy_spec.type = CopyWhere;

      tables.add_task(param);
    }
    else if (check_arg_with_value(argv, i, "--max-count", argval, true))
    {
      max_count = base::atoi<int>(argval, 0);
    }
    else if (strcmp(argv[i], "--source-use-cleartext") == 0)
      source_use_cleartext_plugin = true;
    else if (strcmp(argv[i], "--target-use-cleartext") == 0)
      target_use_cleartext_plugin = true;
    else
    {
      fprintf(stderr, "%s: Invalid option %s\n", argv[0], argv[i]);
      exit(1);
    }

    i++;
  }

  // Creates the log to the target file if any, if not
  // uses std_error
  base::Logger logger(true, log_file);

  if (!log_level.empty())
  {
      if (!set_log_level(log_level))
      {
        fprintf(stderr, "%s: invalid argument '%s' for option %s\n", argv[0], log_level.data(), "--log-level");
        exit(1);
      }
      else
        log_level_set = true;
  }

  // Set the log level from environment var WB_LOG_LEVEL if specified or set a default log level.
  if (!log_level_set)
  {
    const char* log_setting = getenv("WB_LOG_LEVEL");
    if (log_setting == NULL)
      log_setting = "info";
    else
      log_level_set = true;

    std::string level = base::tolower(log_setting);
    base::Logger::active_level(level);
  }

  // If needed, reads the tasks from the table definition file
  if (!table_file.empty())
  {
    if (!read_tasks_from_file(table_file, count_only, tables, trigger_schemas, resume, max_count))
    {
      fprintf(stderr, "Invalid table definitions format in file: %s\n", table_file.data());
      exit(1);
    }
  }

  // Not having the source connection data is an error unless
  // the standalone operations to disable or reenable triggers
  // are called
  if (source_connstring.empty() && !reenable_triggers && ! disable_triggers)
  {
    fprintf(stderr, "Missing source DB server\n");
    exit(1);
  }

  if (target_connstring.empty() && !(count_only && !resume))
  {
    fprintf(stderr, "Missing target DB server\n");
    exit(1);
  }

  // Table definitions will be required only if the standalone operations to
  // Reenable or disable triggers are not called
  if (tables.empty() && !reenable_triggers && ! disable_triggers)
  {
    log_warning("Missing table list specification\n");
    exit(0);
  }

  std::string source_host;
  std::string source_user;
  int source_port = -1;
  std::string source_socket;

  // Source connection is parsed only when NOT executing the
  // Standalone operatios on triggers
  if (source_type == ST_MYSQL && !reenable_triggers && ! disable_triggers)
  {
    if (!parse_mysql_connstring(source_connstring, source_user, source_password,
                                source_host, source_port, source_socket))
    {
      fprintf(stderr, "Invalid MySQL connection string %s for source database. Must be in format user[:pass]@host:port or user[:pass]@::socket\n", target_connstring.c_str());
      exit(1);
    }
  }

  std::string target_host;
  std::string target_user;
  int target_port = -1;
  std::string target_socket;
  if (!(count_only && !resume) && !parse_mysql_connstring(target_connstring, target_user, target_password,
                                             target_host, target_port, target_socket))
  {
    fprintf(stderr, "Invalid MySQL connection string %s for target database. Must be in format user[:pass]@host:port or user[:pass]@::socket\n", target_connstring.c_str());
    exit(1);
  }

  if (passwords_from_stdin)
  {
    char password[200];
    if (!fgets(password, sizeof(password), stdin))
    {
      log_error("Error reading passwords from stdin\n");
      exit(1);
    }

    if ((count_only && !resume)|| reenable_triggers || disable_triggers)
    {
      char *ptr = strtok(password, "\t\r\n");
      if (ptr)
      {
        if (count_only)
          source_password = ptr;
        else
          target_password = ptr;
      }
    }
    else
    {
      char *ptr = strtok(password, "\r\n");
      if (ptr)
      {
        ptr = strchr(password, '\t');
        if (ptr)
        {
          source_password = std::string(password, ptr-password);
          target_password = ptr+1;
        }
        else
          source_password = password;
      }
    }
  }

  static SQLHENV odbc_env;

  PyThreadState *state = NULL;
  if (source_type == ST_PYTHON)
  {
    Py_Initialize();
    PyEval_InitThreads();
    state = PyEval_SaveThread();
  }
  try
  {
    if (count_only)
    {
      boost::scoped_ptr<CopyDataSource> psource;

      if (source_type == ST_ODBC)
      {
        SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &odbc_env);
        SQLSetEnvAttr(odbc_env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

        psource.reset(new ODBCCopyDataSource(odbc_env, source_connstring, source_password, source_is_utf8, source_rdbms_type));
      }
      else if (source_type == ST_MYSQL)
        psource.reset(new MySQLCopyDataSource(source_host, source_port, source_user, source_password, source_socket, source_use_cleartext_plugin));
      else
        psource.reset(new PythonCopyDataSource(source_connstring, source_password));

      boost::scoped_ptr<MySQLCopyDataTarget> ptarget;
      TableParam task;
      while(tables.get_task(task))
      {
        std::vector<std::string> last_pkeys;
        if (task.copy_spec.resume)
        {
          if(!ptarget.get())
            ptarget.reset(new MySQLCopyDataTarget(target_host, target_port, target_user, target_password, target_socket, target_use_cleartext_plugin, app_name, source_charset, source_rdbms_type));
          last_pkeys = ptarget->get_last_pkeys(task.target_pk_columns, task.target_schema, task.target_table);
        }
        count_rows(psource, task.source_schema, task.source_table, task.source_pk_columns, task.copy_spec, last_pkeys);
      }
    }
    else if (reenable_triggers || disable_triggers)
    {
      boost::scoped_ptr<MySQLCopyDataTarget> ptarget;
      ptarget.reset(new MySQLCopyDataTarget(target_host, target_port, target_user, target_password, target_socket, target_use_cleartext_plugin, app_name, source_charset, source_rdbms_type));

      if (disable_triggers)
        ptarget->backup_triggers(trigger_schemas);
      else
        ptarget->restore_triggers(trigger_schemas);
    }
    else
    {
      std::vector<CopyDataTask*> threads;

      boost::scoped_ptr<MySQLCopyDataTarget> ptarget_conn;
      MySQLCopyDataTarget *ptarget = NULL;
      CopyDataSource *psource = NULL;

      if (disable_triggers_on_copy)
      {
        ptarget_conn.reset(new MySQLCopyDataTarget(target_host, target_port, target_user, target_password, target_socket, target_use_cleartext_plugin, app_name, source_charset, source_rdbms_type));
        ptarget_conn->backup_triggers(trigger_schemas);
      }

      for (int index = 0; index < thread_count; index++)
      {
        if (source_type == ST_ODBC)
        {
          SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &odbc_env);
          SQLSetEnvAttr(odbc_env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

          psource = new ODBCCopyDataSource(odbc_env, source_connstring, source_password, source_is_utf8, source_rdbms_type);
        }
        else if (source_type == ST_MYSQL)
          psource = new MySQLCopyDataSource(source_host, source_port, source_user, source_password, source_socket, source_use_cleartext_plugin);
        else
          psource = new PythonCopyDataSource(source_connstring, source_password);

        ptarget = new MySQLCopyDataTarget(target_host, target_port, target_user, target_password, target_socket, target_use_cleartext_plugin, app_name, source_charset, source_rdbms_type);

        psource->set_max_blob_chunk_size(ptarget->get_max_allowed_packet());
        psource->set_max_parameter_size((unsigned long)ptarget->get_max_long_data_size());
        psource->set_abort_on_oversized_blobs(abort_on_oversized_blobs);
        ptarget->set_truncate(truncate_target);
        if (max_count > 0)
          bulk_insert_batch = max_count;
        ptarget->set_bulk_insert_batch_size((int)bulk_insert_batch);

        if (check_types_only)
        {
          //XXXX
          delete psource;
        }
        else
        {
          threads.push_back(new CopyDataTask(base::strfmt("Task %d", index + 1), psource, ptarget, &tables, show_progress));
        }
      }

      // Waits for all the threads to complete
      for (size_t index = 0; index < threads.size(); index++)
        threads[index]->wait();

      // Finally destroys the threads and connections
      for (size_t index = 0; index < threads.size(); index++)
        delete threads[index];

      // Finally restores the triggers
      if (disable_triggers_on_copy)
        ptarget_conn->restore_triggers(trigger_schemas);
    }
  }
  catch (std::exception &e)
  {
    log_error("Exception: %s\n", e.what());
    if (source_type == ST_PYTHON)
    {
      PyEval_RestoreThread(state);
      Py_Finalize();
    }
    exit(1);
  }

  if (source_type == ST_PYTHON)
  {
    PyEval_RestoreThread(state);
    Py_Finalize();
  }

  printf("FINISHED\n");
  fflush(stdout);

  return 0;
}
bool OdbcConnection::Connect()
{
	if (m_szDSN.empty())
		return false;

	FastGuard lock(m_lock);

	tstring szConn = _T("DSN=") + m_szDSN + _T(";");
	// Reconnect if we need to.
	if (isConnected())
		Disconnect();

	// Allocate enviroment handle
	if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_envHandle)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLAllocHandle"), _T("Unable to allocate environment handle."));
		goto error_handler;
	}

	// Request ODBC3 support
	if (!SQL_SUCCEEDED(SQLSetEnvAttr(m_envHandle, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLSetEnvAttr"), _T("Unable to set environment attribute (SQL_ATTR_ODBC_VERSION)."));
		goto error_handler;
	}

	// Allocate the connection handle
	if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC, m_envHandle, &m_connHandle)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLAllocHandle"), _T("Unable to allocate connection handle."));
		goto error_handler;
	}

	if (m_szUser.length())
	{
		szConn += _T("UID=") + m_szUser + _T(";");
		if (m_szPass.length())
			szConn += _T("PWD=") + m_szPass + _T(";");
	}

	// Enable multiple active result sets
	if (m_bMarsEnabled)
	{
		if (!SQL_SUCCEEDED(SQLSetConnectAttr(m_connHandle, SQL_COPT_SS_MARS_ENABLED, SQL_MARS_ENABLED_YES, SQL_IS_UINTEGER)))
		{
			printf("** WARNING **\n\n");
			printf("Attempted to used MARS (Multiple Active Result Sets), but this\n");
			printf("feature is not supported by your ODBC driver or SQL Server version.\n\n");
			printf("To benefit from MARS, you need to be using at least SQL Server 2005, and at\n");
			printf("least the 'SQL Native Client' ODBC driver (as opposed to the vastly outdated\n'SQL Server' driver).\n\n");
			printf("Continuing to connect without MARS.\n\n");
			m_bMarsEnabled = false;
		}

		// NOTE: We can enable MARS via specifying the following, but we are unable to detect if it's supported this way.
		// szConn += _T("MARS_Connection=yes;");
	}

	if (!SQL_SUCCEEDED(SQLDriverConnect(m_connHandle, SQL_NULL_HANDLE, (SQLTCHAR *)szConn.c_str(), SQL_NTS, 0, 0, 0, 0)))
	{
		ReportSQLError(SQL_HANDLE_DBC, m_connHandle, _T("SQLDriverConnect"), _T("Unable to establish connection."));
		goto error_handler;
	}

	for (auto itr = m_commandSet.begin(); itr != m_commandSet.end(); itr++)
		(*itr)->SetConnectionHandle(m_connHandle);

	return true;

error_handler:
	ResetHandles();
	return false;
}
Esempio n. 5
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_db_connect                                                   *
 *                                                                            *
 * Purpose: connect to the database                                           *
 *                                                                            *
 * Return value: ZBX_DB_OK - succefully connected                             *
 *               ZBX_DB_DOWN - database is down                               *
 *               ZBX_DB_FAIL - failed to connect                              *
 *                                                                            *
 ******************************************************************************/
int	zbx_db_connect(char *host, char *user, char *password, char *dbname, char *dbschema, char *dbsocket, int port)
{
	int		ret = ZBX_DB_OK;
#if defined(HAVE_IBM_DB2)
	char		*connect = NULL;
#elif defined(HAVE_ORACLE)
	char		*connect = NULL;
	sword		err = OCI_SUCCESS;
#elif defined(HAVE_POSTGRESQL)
	char		*cport = NULL;
	DB_RESULT	result;
	DB_ROW		row;
#endif

	txn_init = 1;

	assert(NULL != host);

#if defined(HAVE_IBM_DB2)
	connect = zbx_strdup(connect, "PROTOCOL=TCPIP;");
	if ('\0' != *host)
		connect = zbx_strdcatf(connect, "HOSTNAME=%s;", host);
	if (NULL != dbname && '\0' != *dbname)
		connect = zbx_strdcatf(connect, "DATABASE=%s;", dbname);
	if (0 != port)
		connect = zbx_strdcatf(connect, "PORT=%d;", port);
	if (NULL != user && '\0' != *user)
		connect = zbx_strdcatf(connect, "UID=%s;", user);
	if (NULL != password && '\0' != *password)
		connect = zbx_strdcatf(connect, "PWD=%s;", password);

	memset(&ibm_db2, 0, sizeof(ibm_db2));

	/* allocate an environment handle */
	if (SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &ibm_db2.henv)))
		ret = ZBX_DB_FAIL;

	/* set attribute to enable application to run as ODBC 3.0 application; */
	/* recommended for pure IBM DB2 CLI, but not required */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetEnvAttr(ibm_db2.henv, SQL_ATTR_ODBC_VERSION,
			(void *)SQL_OV_ODBC3, 0)))
		ret = ZBX_DB_FAIL;

	/* allocate a database connection handle */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_DBC, ibm_db2.henv,
			&ibm_db2.hdbc)))
		ret = ZBX_DB_FAIL;

	/* connect to the database */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLDriverConnect(ibm_db2.hdbc, NULL, (SQLCHAR *)connect,
			SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT)))
		ret = ZBX_DB_FAIL;

	/* set autocommit on */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_AUTOCOMMIT,
								(SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* we do not generate vendor escape clause sequences */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_NOSCAN,
								(SQLPOINTER)SQL_NOSCAN_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* set current schema */
	if (NULL != dbschema && '\0' != *dbschema && ZBX_DB_OK == ret)
	{
		char	*dbschema_esc;

		dbschema_esc = DBdyn_escape_string(dbschema);
		DBexecute("set current schema='%s'", dbschema_esc);
		zbx_free(dbschema_esc);
	}

	/* output error information */
	if (ZBX_DB_OK != ret)
	{
		zbx_ibm_db2_log_errors(SQL_HANDLE_ENV, ibm_db2.henv);
		zbx_ibm_db2_log_errors(SQL_HANDLE_DBC, ibm_db2.hdbc);

		zbx_db_close();
	}

	zbx_free(connect);
#elif defined(HAVE_MYSQL)
	conn = mysql_init(NULL);

	if (!mysql_real_connect(conn, host, user, password, dbname, port, dbsocket, CLIENT_MULTI_STATEMENTS))
	{
		zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
		ret = ZBX_DB_FAIL;
	}

	if (ZBX_DB_OK == ret)
	{
		if (0 != mysql_select_db(conn, dbname))
		{
			zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		DBexecute("set names utf8");
	}

	if (ZBX_DB_FAIL == ret)
	{
		switch (mysql_errno(conn))
		{
			case CR_CONN_HOST_ERROR:
			case CR_SERVER_GONE_ERROR:
			case CR_CONNECTION_ERROR:
			case CR_SERVER_LOST:
			case CR_UNKNOWN_HOST:
			case ER_SERVER_SHUTDOWN:
			case ER_ACCESS_DENIED_ERROR:		/* wrong user or password */
			case ER_ILLEGAL_GRANT_FOR_TABLE:	/* user without any privileges */
			case ER_TABLEACCESS_DENIED_ERROR:	/* user without some privilege */
			case ER_UNKNOWN_ERROR:
				ret = ZBX_DB_DOWN;
				break;
			default:
				break;
		}
	}
#elif defined(HAVE_ORACLE)
#if defined(HAVE_GETENV) && defined(HAVE_PUTENV)
	if (NULL == getenv("NLS_LANG"))
		putenv("NLS_LANG=.UTF8");
#endif
	memset(&oracle, 0, sizeof(oracle));

	/* connection string format: [//]host[:port][/service name] */

	if ('\0' != *host)
	{
		connect = zbx_strdcatf(connect, "//%s", host);
		if (0 != port)
			connect = zbx_strdcatf(connect, ":%d", port);
		if (NULL != dbname && '\0' != *dbname)
			connect = zbx_strdcatf(connect, "/%s", dbname);
	}
	else
		ret = ZBX_DB_FAIL;

	if (ZBX_DB_OK == ret)
	{
		/* initialize environment */
		err = OCIEnvCreate((OCIEnv **)&oracle.envhp, (ub4)OCI_DEFAULT,
				(dvoid *)0, (dvoid * (*)(dvoid *,size_t))0,
				(dvoid * (*)(dvoid *, dvoid *, size_t))0,
				(void (*)(dvoid *, dvoid *))0, (size_t)0, (dvoid **)0);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		/* allocate an error handle */
		(void)OCIHandleAlloc((dvoid *)oracle.envhp, (dvoid **)&oracle.errhp, OCI_HTYPE_ERROR,
				(size_t)0, (dvoid **)0);

		/* get the session */
		err = OCILogon2(oracle.envhp, oracle.errhp, &oracle.svchp,
				(text *)user, (ub4)(NULL != user ? strlen(user) : 0),
				(text *)password, (ub4)(NULL != password ? strlen(password) : 0),
				(text *)connect, (ub4)strlen(connect),
				OCI_DEFAULT);

		if (OCI_SUCCESS == err)
		{
			err = OCIAttrGet((void *)oracle.svchp, OCI_HTYPE_SVCCTX, (void *)&oracle.srvhp, (ub4 *)0,
					OCI_ATTR_SERVER, oracle.errhp);
		}

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_DOWN;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		/* initialize statement handle */
		err = OCIHandleAlloc((dvoid *)oracle.envhp, (dvoid **)&oracle.stmthp, OCI_HTYPE_STMT,
				(size_t)0, (dvoid **)0);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_DOWN;
		}
	}

	if (ZBX_DB_OK == ret)
		DBexecute("alter session set nls_numeric_characters='. '");

	zbx_free(connect);

	if (ZBX_DB_OK != ret)
		zbx_db_close();
#elif defined(HAVE_POSTGRESQL)
	if (0 != port)
		cport = zbx_dsprintf(cport, "%d", port);

	conn = PQsetdbLogin(host, cport, NULL, NULL, dbname, user, password);

	zbx_free(cport);

	/* check to see that the backend connection was successfully made */
	if (CONNECTION_OK != PQstatus(conn))
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, PQerrorMessage(conn));
		ret = ZBX_DB_DOWN;
	}
	else
	{
		result = DBselect("select oid from pg_type where typname='bytea'");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_BYTEAOID = atoi(row[0]);
		DBfree_result(result);
	}

#ifdef HAVE_FUNCTION_PQSERVERVERSION
	ZBX_PG_SVERSION = PQserverVersion(conn);
	zabbix_log(LOG_LEVEL_DEBUG, "PostgreSQL Server version: %d", ZBX_PG_SVERSION);
#endif

	if (80100 <= ZBX_PG_SVERSION)
	{
		/* disable "nonstandard use of \' in a string literal" warning */
		DBexecute("set escape_string_warning to off");

		result = DBselect("show standard_conforming_strings");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_ESCAPE_BACKSLASH = (0 == strcmp(row[0], "off"));
		DBfree_result(result);
	}

	if (90000 <= ZBX_PG_SVERSION)
	{
		/* change the output format for values of type bytea from hex (the default) to escape */
		DBexecute("set bytea_output=escape");
	}
#elif defined(HAVE_SQLITE3)
#ifdef HAVE_FUNCTION_SQLITE3_OPEN_V2
	if (SQLITE_OK != sqlite3_open_v2(dbname, &conn, SQLITE_OPEN_READWRITE, NULL))
#else
	if (SQLITE_OK != sqlite3_open(dbname, &conn))
#endif
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, sqlite3_errmsg(conn));
		sqlite3_close(conn);
		ret = ZBX_DB_DOWN;
	}
	else
	{
		char	*p, *path;

		/* do not return SQLITE_BUSY immediately, wait for N ms */
		sqlite3_busy_timeout(conn, SEC_PER_MIN * 1000);

		path = strdup(dbname);
		if (NULL != (p = strrchr(path, '/')))
			*++p = '\0';
		else
			*path = '\0';

		DBexecute("PRAGMA synchronous = 0");	/* OFF */
		DBexecute("PRAGMA temp_store = 2");	/* MEMORY */
		DBexecute("PRAGMA temp_store_directory = '%s'", path);

		zbx_free(path);
	}
#endif	/* HAVE_SQLITE3 */

	txn_init = 0;

	return ret;
}
Esempio n. 6
0
/* ------------------------------------------------------------- */
static PJXSQLCONNECT jx_sqlNewConnection(void )
{
   // static SQLHSTMT      hstmt = 0 ;
   // SQLINTEGEREGER    len;
   // UCHAR Label [256];
   // LGL  err = ON;
   // LONG rows =0;

   PJXSQLCONNECT pConnection;
   LONG          attrParm;
   PUCHAR        server = "*LOCAL";
   int rc;
   PSQLOPTIONS po;

   pConnection = memAlloc(sizeof(JXSQLCONNECT));
   memset(pConnection , 0 , sizeof(JXSQLCONNECT));
   pConnection->pCd = XlateXdOpen (13488, 0);
   po = &pConnection->options;
   po->upperCaseColName = OFF;
   po->autoParseContent = ON;
   po->DecimalPoint     = '.';
   po->hexSort          = OFF;
   po->sqlNaming        = OFF;
   po->DateSep          = '-';
   po->DateFmt          = 'y';
   po->TimeSep          = ':';
   po->TimeFmt          = 'H';


   // allocate an environment handle
   rc = SQLAllocEnv (&pConnection->henv);
   if (rc != SQL_SUCCESS ) {
     check_error (NULL);
     jx_sqlDisconnect (pConnection);
     return NULL; // we have an error
   }

   // Note - this is invers: Default to IBMi naming
   attrParm = pConnection->options.sqlNaming == ON ? SQL_FALSE : SQL_TRUE;
   rc = SQLSetEnvAttr  (pConnection->henv, SQL_ATTR_SYS_NAMING, &attrParm  , 0);
   if (rc != SQL_SUCCESS ) {
     check_error (NULL);
     jx_sqlDisconnect (pConnection);
     return NULL; // we have an error
   }

   /*
   attrParm = SQL_TRUE;
   rc = SQLSetEnvAttr  (pConnection->henv, SQL_ATTR_UTF8 , &attrParm  , 0);
   if (pSQL->rc != SQL_SUCCESS ) {
     jx_sqlDisconnect (pConnection);
     return NULL; // we have an error
   }
   */

   rc = SQLAllocConnect (pConnection->henv, &pConnection->hdbc);  // allocate a connection handle
   if (rc != SQL_SUCCESS ) {
     check_error (NULL);
     jx_sqlDisconnect (pConnection);
     return NULL; // we have an error
   }

   attrParm = SQL_TXN_NO_COMMIT;
   rc = SQLSetConnectAttr (pConnection->hdbc, SQL_ATTR_COMMIT , &attrParm  , 0);
   if (rc != SQL_SUCCESS ) {
     check_error (NULL);
     jx_sqlDisconnect (pConnection);
     return NULL; // we have an error
   }

   rc = SQLConnect (pConnection->hdbc, server , SQL_NTS, NULL, SQL_NTS, NULL, SQL_NTS);
   if (rc != SQL_SUCCESS ) {
     check_error (NULL);
     jx_sqlDisconnect (pConnection);
     return NULL; // we have an error
   }

   return pConnection; // we are ok

}
Esempio n. 7
0
//*************************************************************************
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
   SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
   
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the DSN mydsn
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=localhost;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=localhost;PORT=5678;"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));


  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
       
     
  }
   else
   {
        printf("connection failed\n");
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__); 
        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__);
        return 1;
   }

   ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt);
   checkrc(ret,__LINE__);

   SQLCHAR table[100]="CREATE TABLE EMP(EID INT,SALARY INT)";
   
   ret = SQLPrepare(stmt,table,SQL_NTS);
   checkrc(ret,__LINE__);

   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   //AFTER CLOSE THE CONNECTION ,CALL execute
      
   ret = SQLExecute(stmt);
   int rettype = ret;
   if(ret )
   printf("After closing the connection, Execution failed\n"); 
   
      
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
  
   if(rettype ==0)return 1;
     

  return 0;
}         
Esempio n. 8
0
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
   SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
   
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the DSN mydsn
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "test", (SQLSMALLINT) strlen ("test"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));

  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
     
     
  }
   else
   {
        printf("error in connection\n");
        
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__); 
        return 1;
    }

   
   //******************************************************************
   // TABLE CREATED
   ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt);
   checkrc(ret,__LINE__);
   
   SQLCHAR table[200]=
     "CREATE TABLE T1(F1 INT,F2 INT)";
   ret = SQLPrepare(stmt,table,SQL_NTS);
   checkrc(ret,__LINE__);
   ret = SQLExecute(stmt);
   printf("\nTABLE CREATED\n"); 
   //****************************************************************
   
   InsertTest(env,dbc,stmt);  
   //*****************************************************************
    int ret1;
    ret1=FetchTest(env,dbc,stmt);

   //****************************************************************      
   ret = SQLPrepare(stmt,(unsigned char*)"drop table T1;",SQL_NTS);
   checkrc(ret,__LINE__);

   ret = SQLExecute(stmt);
   checkrc(ret,__LINE__);
   printf("Table 'T1' Dropped\n");

   ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt);
   checkrc(ret,__LINE__);

   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
   
   if(ret1 == 0)return 1;
   return 0;
}         
Esempio n. 9
0
int	odbc_DBconnect(ZBX_ODBC_DBH *pdbh, char *db_dsn, char *user, char *pass, int login_timeout)
{
	const char	*__function_name = "odbc_DBconnect";
	int		ret = FAIL;
	SQLRETURN	rc;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() db_dsn:'%s' user:'******'", __function_name, db_dsn, user);

	clean_odbc_strerror();

	memset(pdbh, 0, sizeof(ZBX_ODBC_DBH));

	/* allocate environment handle */
	if (0 == SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(pdbh->henv))))
	{
		set_last_odbc_strerror("%s", "Cannot create ODBC environment handle.");
		goto end;
	}

	/* set the ODBC version environment attribute */
	if (0 != CALLODBC(SQLSetEnvAttr(pdbh->henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0), rc, SQL_HANDLE_ENV,
			pdbh->henv, "Cannot set ODBC version"))
	{
		goto end;
	}

	/* allocate connection handle */
	if (0 != CALLODBC(SQLAllocHandle(SQL_HANDLE_DBC, pdbh->henv, &(pdbh->hdbc)), rc, SQL_HANDLE_ENV, pdbh->henv,
			"Cannot create ODBC connection handle"))
	{
		goto end;
	}

	/* set login timeout */
	if (0 != CALLODBC(SQLSetConnectAttr(pdbh->hdbc, (SQLINTEGER)SQL_LOGIN_TIMEOUT,
			(SQLPOINTER)(intptr_t)login_timeout, (SQLINTEGER)0), rc, SQL_HANDLE_DBC, pdbh->hdbc,
			"Cannot set ODBC login timeout"))
	{
		goto end;
	}

	/* connect to data source */
	if (0 != CALLODBC(SQLConnect(pdbh->hdbc, (SQLCHAR *)db_dsn, SQL_NTS, (SQLCHAR *)user, SQL_NTS, (SQLCHAR *)pass,
			SQL_NTS), rc, SQL_HANDLE_DBC, pdbh->hdbc, "Cannot connect to ODBC DSN"))
	{
		goto end;
	}

	/* allocate statement handle */
	if (0 != CALLODBC(SQLAllocHandle(SQL_HANDLE_STMT, pdbh->hdbc, &(pdbh->hstmt)), rc, SQL_HANDLE_DBC, pdbh->hdbc,
			"Cannot create ODBC statement handle."))
	{
		goto end;
	}

	pdbh->connected = 1;

	ret = SUCCEED;
end:
	if (SUCCEED != ret)
		odbc_DBclose(pdbh);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Esempio n. 10
0
SWITCH_DECLARE(switch_odbc_status_t) switch_odbc_handle_connect(switch_odbc_handle_t *handle)
{
#ifdef SWITCH_HAVE_ODBC
	int result;
	SQLINTEGER err;
	int16_t mlen;
	unsigned char msg[200], stat[10];
	SQLSMALLINT valueLength = 0;
	int i = 0;

	if (handle->env == SQL_NULL_HANDLE) {
		result = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &handle->env);

		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error AllocHandle\n");
			return SWITCH_ODBC_FAIL;
		}

		result = SQLSetEnvAttr(handle->env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error SetEnv\n");
			SQLFreeHandle(SQL_HANDLE_ENV, handle->env);
			return SWITCH_ODBC_FAIL;
		}

		result = SQLAllocHandle(SQL_HANDLE_DBC, handle->env, &handle->con);

		if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error AllocHDB %d\n", result);
			SQLFreeHandle(SQL_HANDLE_ENV, handle->env);
			return SWITCH_ODBC_FAIL;
		}
		SQLSetConnectAttr(handle->con, SQL_LOGIN_TIMEOUT, (SQLPOINTER *) 10, 0);
	}
	if (handle->state == SWITCH_ODBC_STATE_CONNECTED) {
		switch_odbc_handle_disconnect(handle);
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG1, "Re-connecting %s\n", handle->dsn);
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG1, "Connecting %s\n", handle->dsn);

	if (!strstr(handle->dsn, "DRIVER")) {
		result = SQLConnect(handle->con, (SQLCHAR *) handle->dsn, SQL_NTS, (SQLCHAR *) handle->username, SQL_NTS, (SQLCHAR *) handle->password, SQL_NTS);
	} else {
		SQLCHAR outstr[1024] = { 0 };
		SQLSMALLINT outstrlen = 0;
		result =
			SQLDriverConnect(handle->con, NULL, (SQLCHAR *) handle->dsn, (SQLSMALLINT) strlen(handle->dsn), outstr, sizeof(outstr), &outstrlen,
							 SQL_DRIVER_NOPROMPT);
	}

	if ((result != SQL_SUCCESS) && (result != SQL_SUCCESS_WITH_INFO)) {
		char *err_str;
		if ((err_str = switch_odbc_handle_get_error(handle, NULL))) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "%s\n", err_str);
			free(err_str);
		} else {
			SQLGetDiagRec(SQL_HANDLE_DBC, handle->con, 1, stat, &err, msg, 100, &mlen);
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error SQLConnect=%d errno=%d %s\n", result, (int) err, msg);
		}
		SQLFreeHandle(SQL_HANDLE_ENV, handle->env);
		return SWITCH_ODBC_FAIL;
	}

	result = SQLGetInfo(handle->con, SQL_DRIVER_NAME, (SQLCHAR *) handle->odbc_driver, 255, &valueLength);
	if (result == SQL_SUCCESS || result == SQL_SUCCESS_WITH_INFO) {
		for (i = 0; i < valueLength; ++i)
			handle->odbc_driver[i] = (char) toupper(handle->odbc_driver[i]);
	}

	if (strstr(handle->odbc_driver, "FIREBIRD") != 0 || strstr(handle->odbc_driver, "FB32") != 0 || strstr(handle->odbc_driver, "FB64") != 0) {
		handle->is_firebird = TRUE;
	} else {
		handle->is_firebird = FALSE;
	}

	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG1, "Connected to [%s]\n", handle->dsn);
	handle->state = SWITCH_ODBC_STATE_CONNECTED;
	return SWITCH_ODBC_SUCCESS;
#else
	return SWITCH_ODBC_FAIL;
#endif
}
Esempio n. 11
0
int main(int argc, char **argv)
{
  SQLHENV     hEnv = NULL;
  SQLHDBC     hDbc = NULL;
  SQLHSTMT    hStmt = NULL;
  char*       pConnStr;
  char        pQuery[1000];
  bool        silent = true;

  if (argc != 5) {
    fprintf(stderr, "Usage: %s <ConnString> <pkey range> <ccol range> <rand seed>\n", argv[0]);
    return 1;
  }
  pConnStr = argv[1];
  char *endptr;
  long long numkeys = strtoll(argv[2], &endptr, 10);
  long long rowsperkey = strtoll(argv[3], &endptr, 10);
  int seed = atoi(argv[4]);
  struct drand48_data lcg;
  srand48_r(seed, &lcg);

  // Allocate an environment
  if (!silent)
    fprintf(stderr, "Allocating Handle Enviroment\n");
  if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv) == SQL_ERROR)
    {
      fprintf(stderr, "Unable to allocate an environment handle\n");
      exit(-1);
    }

  // Register this as an application that expects 3.x behavior,
  // you must register something if you use AllocHandle
  if (!silent)
    fprintf(stderr, "Setting to ODBC3\n");
  TRYODBC(hEnv,
	  SQL_HANDLE_ENV,
	  SQLSetEnvAttr(hEnv,
			SQL_ATTR_ODBC_VERSION,
			(SQLPOINTER)SQL_OV_ODBC3,
			0));

  // Allocate a connection
  if (!silent)
    fprintf(stderr, "Allocating Handle\n");
  TRYODBC(hEnv,
	  SQL_HANDLE_ENV,
	  SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc));

  // Connect to the driver.  Use the connection string if supplied
  // on the input, otherwise let the driver manager prompt for input.
  if (!silent)
    fprintf(stderr, "Connecting to driver\n");
  TRYODBC(hDbc,
	  SQL_HANDLE_DBC,
	  SQLDriverConnect(hDbc,
			   NULL,
			   pConnStr,
			   SQL_NTS,
			   NULL,
			   0,
			   NULL,
			   SQL_DRIVER_COMPLETE));

  fprintf(stderr, "Connected!\n");

  if (!silent)
    fprintf(stderr, "Allocating statement\n");
  TRYODBC(hDbc,
	  SQL_HANDLE_DBC,
	  SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt));

  RETCODE     RetCode;
  SQLSMALLINT sNumResults;

  // Execute the query
  if (!silent)
    fprintf(stderr, "Executing query\n");
  long long i;
  double rval;
  for (i = 0; i < 100000; i++) {
    drand48_r(&lcg, &rval);
    sprintf(pQuery, "SELECT MAX(col1) FROM otest.test10 WHERE ccol = %lld", (long long)(rval * numkeys));
    RetCode = SQLExecDirect(hStmt, pQuery, SQL_NTS);

    switch(RetCode)
      {
      case SQL_SUCCESS_WITH_INFO:
	{
	  HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode);
	  // fall through
	}
      case SQL_SUCCESS:
	{
	  // If this is a row-returning query, display
	  // results
	  TRYODBC(hStmt,
		  SQL_HANDLE_STMT,
		  SQLNumResultCols(hStmt,&sNumResults));
	  
	  if (sNumResults > 0)
	    {
	      DisplayResults(hStmt,sNumResults, silent);
	    } 
	  else
	    {
	      SQLLEN cRowCount;
	      
	      TRYODBC(hStmt,
		      SQL_HANDLE_STMT,
		      SQLRowCount(hStmt,&cRowCount));
	      
	      if (cRowCount >= 0)
		{
		  printf("%d %s returned\n",
			 (int)cRowCount,
			 (cRowCount == 1) ? "row" : "rows");
		}
	    }
	  break;
	}
	
      case SQL_ERROR:
	{
	  HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode);
	  break;
	}
	
      default:
	fprintf(stderr, "Unexpected return code %hd!\n", RetCode);
	
      }
  }

  TRYODBC(hStmt,
	  SQL_HANDLE_STMT,
	  SQLFreeStmt(hStmt, SQL_CLOSE));

 Exit:

  // Free ODBC handles and exit

  if (hStmt)
    {
      SQLFreeHandle(SQL_HANDLE_STMT, hStmt);
    }

  if (hDbc)
    {
      SQLDisconnect(hDbc);
      SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
    }

  if (hEnv)
    {
      SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
    }

  return 0;

}
Esempio n. 12
0
// Main Program
int main (int argc, char **argv)
{
	SQLCHAR		*dsnName;
	SQLCHAR		*user;
	SQLCHAR		*password;
	SQLRETURN	returnCode;
	bool		testPassed = true;
	SQLCHAR		InConnStr[MAX_CONNECT_STRING];
	SQLCHAR		OutConnStr[MAX_CONNECT_STRING];
	SQLSMALLINT	ConnStrLength;
	int c, errflag = 0;
	
	optarg = NULL;
	if (argc != 7)
		errflag++;

	while (!errflag && (c = getopt(argc, argv, ARGS)) != -1)
		switch (c) {
			case 'd':
				dsnName = (SQLCHAR*)optarg;	
				break;
			case 'u':
				user = (SQLCHAR*)optarg;
				break;
			case 'p':
				password = (SQLCHAR*)optarg;
				break;
			default :
				errflag++;
		}
	if (errflag) {
		printf("Command line error.\n");
		printf("Usage: %s [-d <datasource>] [-u <userid>] [-p <password>]\n", argv[0] );
		return FALSE;
	}

	// Initialize handles to NULL
	henv = SQL_NULL_HANDLE;
	hstmt = SQL_NULL_HANDLE;
	hdbc = SQL_NULL_HANDLE;

	// Allocate Environment Handle
	returnCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv)",returnCode);

	// Set ODBC version to 3.0
	returnCode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0)",returnCode,false);

	// Allocate Connection handle
	returnCode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc)", returnCode);

	//Connect to the database
	sprintf((char*)InConnStr,"DSN=%s;UID=%s;PWD=%s;%c",(char*)dsnName, (char*)user, (char*)password,'\0');
	printf("Using Connect String: %s\n", InConnStr);
	returnCode = SQLDriverConnect(hdbc,hWnd,InConnStr,SQL_NTS,OutConnStr,sizeof(OutConnStr),&ConnStrLength,SQL_DRIVER_NOPROMPT);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLDriverConnect",returnCode);

	//Allocate Statement handle
	returnCode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt)", returnCode);

	//Free Statement handle
	returnCode = SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLFreeHandle(SQL_HANDLE_STMT, hstmt)", returnCode);
	hstmt = SQL_NULL_HANDLE;

	//Disconnect
	returnCode = SQLDisconnect(hdbc);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLDisconnect(hdbc)", returnCode);

	//Free Connection handle
	returnCode = SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLFreeHandle(SQL_HANDLE_DBC, hdbc)", returnCode);
	hdbc = SQL_NULL_HANDLE;

	//Free Environment handle
	returnCode = SQLFreeHandle(SQL_HANDLE_ENV, henv);
	if(returnCode != SQL_SUCCESS)
		LogDiagnostics("SQLFreeHandle(SQL_HANDLE_ENV, henv)", returnCode);
	henv = SQL_NULL_HANDLE;

	printf("\nConnect Test Passed...\n");
	exit(EXIT_SUCCESS);
}
Esempio n. 13
0
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
   ret =SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
   checkrc(ret,__LINE__);
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the DSN mydsn
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));

  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source..\n");
       
     
  }
   else
   {
        printf("error in connection\n");
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__); 
        return 1;
   }

   ret = SQLSetConnectAttr(dbc,SQL_ATTR_AUTOCOMMIT,(void*)SQL_AUTOCOMMIT_OFF,SQL_IS_UINTEGER);
   checkrc(ret,__LINE__);
   //******************************************************************
   // TABLE CREATED
   ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt);
   checkrc(ret,__LINE__);
   
   SQLCHAR table[200]=
     "CREATE TABLE T1(F1 INT,F2 INT);";
   ret = SQLPrepare(stmt,table,SQL_NTS);
   checkrc(ret,__LINE__);
   ret = SQLExecute(stmt);
   checkrc(ret,__LINE__);
   SQLFreeStmt(stmt, SQL_CLOSE);
   
   printf("\nTABLE CREATED\n"); 
   //****************************************************************
    ret = SQLPrepare(stmt,(unsigned char*)"INSERT INTO T1 VALUES(1,1);",SQL_NTS);
    checkrc(ret,__LINE__);
    ret = SQLExecute(stmt);
    checkrc(ret,__LINE__);
    
    SQLFreeStmt(stmt, SQL_CLOSE);
    ret = SQLEndTran(SQL_HANDLE_DBC,dbc,SQL_COMMIT);
    if(ret!=SQL_SUCCESS && ret !=SQL_SUCCESS_WITH_INFO)
    printf("error in commit\n");
   //InsertTest(env,dbc,stmt);  
   //*****************************************************************
    
    //update
    ret = SQLPrepare(stmt,(unsigned char*)"UPDATE T1 SET F2=100;",SQL_NTS);
    checkrc(ret,__LINE__);
    ret = SQLExecute(stmt);
    checkrc(ret,__LINE__);
    SQLFreeStmt(stmt, SQL_CLOSE);
    ret = SQLEndTran(SQL_HANDLE_DBC,dbc,SQL_COMMIT);
    if(ret!=SQL_SUCCESS && ret !=SQL_SUCCESS_WITH_INFO)
    printf("error in commit\n");
    checkrc(ret,__LINE__);
   //***********************************************************
     //FETCH
    FetchTest(env,dbc,stmt);

   //****************************************************************      
   ret = SQLExecDirect(stmt,(unsigned char*)"DROP TABLE T1",SQL_NTS);
   checkrc(ret,__LINE__);
   SQLFreeStmt(stmt, SQL_CLOSE);
   printf("Table T1 dropped\n");

   ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt);
   checkrc(ret,__LINE__);

   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
   return 0;
}         
bool OdbcConnection::Connect()
{
	if (m_szDSN.length() == 0)
		return false;

	m_lock.Acquire();

	tstring szConn = _T("DSN=") + m_szDSN + _T(";");
	// Reconnect if we need to.
	if (isConnected())
		Disconnect();

	// Allocate enviroment handle
	if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_envHandle)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLAllocHandle"), _T("Unable to allocate environment handle."));
		goto error_handler;
	}

	// Request ODBC3 support
	if (!SQL_SUCCEEDED(SQLSetEnvAttr(m_envHandle, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLSetEnvAttr"), _T("Unable to set environment attribute (SQL_ATTR_ODBC_VERSION)."));
		goto error_handler;
	}

	// Allocate the connection handle
	if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_DBC, m_envHandle, &m_connHandle)))
	{
		ReportSQLError(SQL_HANDLE_ENV, m_envHandle, _T("SQLAllocHandle"), _T("Unable to allocate connection handle."));
		goto error_handler;
	}

	if (m_szUser.length())
	{
		szConn += _T("UID=") + m_szUser + _T(";");
		if (m_szPass.length())
			szConn += _T("PWD=") + m_szPass + _T(";");
	}

	// Enable multiple active result sets
	if (m_bMarsEnabled)
		szConn += _T("MARS_Connection=yes;");

	if (!SQL_SUCCEEDED(SQLDriverConnect(m_connHandle, NULL, (SQLTCHAR *)szConn.c_str(), SQL_NTS, NULL, NULL, NULL, NULL)))
	{
		ReportSQLError(SQL_HANDLE_DBC, m_connHandle, _T("SQLDriverConnect"), _T("Unable to establish connection."));
		goto error_handler;
	}

	for (auto itr = m_commandSet.begin(); itr != m_commandSet.end(); itr++)
		(*itr)->SetConnectionHandle(m_connHandle);

	m_lock.Release();
	return true;

error_handler:
	ResetHandles();
	m_lock.Release();
	return false;
}
Esempio n. 15
0
// Establish an Oracle DSN.  Oracle does not have a constant name, but rather
// a formulated one based on installed instance.  We'll look for the substrings
// "Oracle" and "10g", unless the user has overridden this pattern using
// the "odbcoracledriver" environment variable.
void OdbcConnectionUtil::SetupOracleDSN()
{
    char driverDesc[1024];
    char driverAttrs[1024];
    theOracleDriverName[0] = '\0';
	char teststr[1024];
	BOOL ret = false;
	SQLRETURN rc = SQL_ERROR;
    m_SetupOracleDSNdone = true;

    SQLHENV sqlenv = SQL_NULL_HENV;
    rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HENV, &sqlenv);
    if ( SQLRETURN_OK(rc) )
        rc = SQLSetEnvAttr(sqlenv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);

    if ( SQLRETURN_OK(rc) )
    {
        SQLUSMALLINT direction = SQL_FETCH_FIRST;
        SQLSMALLINT driverDescLength = 0;
        SQLSMALLINT driverAttrsLength = 0;
        do
        {
            driverDescLength = 0;
            driverAttrsLength = 0;
            rc = SQLDrivers(sqlenv, direction, (SQLCHAR *) driverDesc, (SQLSMALLINT) sizeof(driverDesc), &driverDescLength,
                (SQLCHAR *) driverAttrs, (SQLSMALLINT) sizeof(driverAttrs), &driverAttrsLength);
            if (SQLRETURN_OK(rc))
            {
                #ifdef WIN32
                #pragma message("TODO: update this with each Oracle version update")
                #endif
                if (NULL != strstr(driverDesc, "Oracle") && (NULL != strstr(driverDesc, "10") || NULL != strstr(driverDesc, "11")))
                    strcpy(theOracleDriverName, driverDesc);
            }
            direction = SQL_FETCH_NEXT;
        }
        while ( SQLRETURN_OK(rc) && SQL_NO_DATA != rc && '\0' == theOracleDriverName[0] );
	    
        if (m_SetupValues->PropertyExist( L"enableOracleSetup" ))
	    {
		    FdoStringP pValue = m_SetupValues->GetPropertyValue( L"enableOracleSetup" );
		    if (pValue != L"true")
			    return;
	    }
        if (SQL_NO_DATA == rc)
            rc = SQL_SUCCESS;
		direction = SQL_FETCH_FIRST;
		FdoStringP pDSNOracle = m_SetupValues->GetPropertyValue( L"DSNOracle");
		while(SQLRETURN_OK(SQLDataSources(sqlenv, direction, (SQLCHAR *)teststr, sizeof(teststr), &driverAttrsLength, (SQLCHAR *)driverDesc, sizeof(driverDesc), &driverDescLength)))
		{
			direction = SQL_FETCH_NEXT;
			if (pDSNOracle == (FdoStringP)teststr)
			{
				SQLFreeHandle(SQL_HANDLE_ENV, sqlenv);
				return;
			}
		}
    }
    if (SQLRETURN_OK(rc) && '\0' != theOracleDriverName[0])
    {
        char* datastoreUpper = driverDesc;
        sprintf(datastoreUpper, "%ls", (FdoString*) UnitTestUtil::GetEnviron("datastore", L""));
        (void) _strupr_s(datastoreUpper, 1024);

        sprintf ( teststr, "DSN=%s%cDescription=Oracle DSN for FDO ODBC provider%cServerName=%s%cUserID=%s%c%c", (const char*)(FdoStringP)m_SetupValues->GetPropertyValue( L"DSNOracle"), '\0',
            '\0', (const char*)(FdoStringP)m_SetupValues->GetPropertyValue( L"serviceOracle" ), '\0', datastoreUpper, '\0', '\0', '\0');
		ret = SQLConfigDataSource (NULL, ODBC_ADD_DSN, theOracleDriverName, teststr);
    }

    if (!SQLRETURN_OK(rc))
    {
    	SQLSMALLINT cRecNmbr = 1;
	    UCHAR		szSqlState[MAX_PATH] = "";
	    UCHAR 	 	szErrorMsg[MAX_PATH] = "";
	    SDWORD		pfNativeError = 0L;
	    SWORD	 	pcbErrorMsg = 0;

		rc = SQLGetDiagRec(SQL_HANDLE_ENV, sqlenv, 1, szSqlState, &pfNativeError, szErrorMsg, MAX_PATH-1, &pcbErrorMsg);
        printf("%.200s\n", (char *)szErrorMsg);
        throw FdoException::Create (L"Oracle DSN setup failed");
    }
	if (sqlenv != SQL_NULL_HENV)
		SQLFreeHandle(SQL_HANDLE_ENV, sqlenv);
    if (!ret )
    {
        DWORD error;
        WORD count;
        SQLInstallerError (1, &error, teststr, sizeof (teststr), &count);
        printf (teststr);
        throw FdoException::Create (L"Oracle DSN setup failed");
    }

    if ('\0' == theOracleDriverName[0])
        throw FdoException::Create (L"Oracle DSN setup failed");
}
Esempio n. 16
0
/* Changed ... Have to implement the same for translators */
void
adddrivers_to_list (ControlRef widget, WindowRef dlg, BOOL addNotify)
{
  wchar_t drvdesc[1024], drvattrs[1024], driver[1024];
  DataBrowserItemID item = DBITEM_ID + 1;
  DataBrowserCallbacks dbCallbacks;
  ThemeDrawingState outState = NULL;
  UInt16 colSize[5] = { 150, 150, 100, 50 , 50};
  void *handle;
  SInt16 outBaseline;
  Point ioBound;
  struct stat _stat;
  SQLSMALLINT len, len1;
  SQLRETURN ret;
  HENV henv, drv_henv;
  HDBC drv_hdbc;
  pSQLGetInfoFunc funcHdl;
  pSQLAllocHandle allocHdl;
  pSQLAllocEnv allocEnvHdl = NULL;
  pSQLAllocConnect allocConnectHdl = NULL;
  pSQLFreeHandle freeHdl;
  pSQLFreeEnv freeEnvHdl;
  pSQLFreeConnect freeConnectHdl;
  char *_drv_u8 = NULL;
  int i;

  if (!widget)
    return;

  GetThemeDrawingState (&outState);

  /* Install an event handler on the component databrowser */
  dbCallbacks.version = kDataBrowserLatestCallbacks;
  InitDataBrowserCallbacks (&dbCallbacks);

  if (addNotify)
    dbCallbacks.u.v1.itemNotificationCallback =
      NewDataBrowserItemNotificationUPP (drivers_notification_item);

  /* On Mac OS X 10.0.x : clientDataCallback */
  dbCallbacks.u.v1.itemDataCallback =
      NewDataBrowserItemDataUPP (drivers_getset_item);
  SetDataBrowserCallbacks (widget, &dbCallbacks);
  /* Begin the draw of the data browser */
  SetDataBrowserTarget (widget, DBITEM_ID);

  /* Make the clean up */
  for (i = 0; i < Drivers_nrows; i++, item++)
    {
      CFRelease (Drivers_array[0][i]);
      Drivers_array[0][i] = NULL;
      CFRelease (Drivers_array[1][i]);
      Drivers_array[1][i] = NULL;
      CFRelease (Drivers_array[2][i]);
      Drivers_array[2][i] = NULL;
      CFRelease (Drivers_array[3][i]);
      Drivers_array[3][i] = NULL;
      CFRelease (Drivers_array[4][i]);
      Drivers_array[4][i] = NULL;
      RemoveDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
    }

  /* Global Initialization */
  Drivers_nrows = 0;
  item = DBITEM_ID + 1;

  /* Create a HENV to get the list of drivers then */
  ret = SQLAllocHandle (SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
  if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO)
    {
      _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE, SQL_NULL_HANDLE);
      goto end;
    }

  /* Set the version ODBC API to use */
  SQLSetEnvAttr (henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3,
      SQL_IS_UINTEGER);

  /* Get the list of drivers */
  ret =
      SQLDriversW (henv, SQL_FETCH_FIRST, drvdesc, sizeof (drvdesc)/sizeof(wchar_t),
        &len, drvattrs, sizeof (drvattrs)/sizeof(wchar_t), &len1);
  if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO && ret != SQL_NO_DATA)
    {
      _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE, SQL_NULL_HANDLE);
      goto error;
    }

  while (ret != SQL_NO_DATA)
    {
      Drivers_array[0][Drivers_nrows] = convert_wchar_to_CFString(drvdesc);

      /* Get the driver library name */
      SQLSetConfigMode (ODBC_BOTH_DSN);
      SQLGetPrivateProfileStringW (drvdesc, L"Driver", L"", driver,
	  sizeof (driver)/sizeof(wchar_t), L"odbcinst.ini");
      if (driver[0] == L'\0')
	SQLGetPrivateProfileStringW (L"Default", L"Driver", L"", driver,
	    sizeof (driver)/sizeof(wchar_t), L"odbcinst.ini");
      if (driver[0] == L'\0')
	{
	  if (Drivers_array[0][Drivers_nrows])
            {
              CFRelease (Drivers_array[0][Drivers_nrows]);
              Drivers_array[0][Drivers_nrows] = NULL;
            }
	  goto skip;
	}

      Drivers_array[1][Drivers_nrows] = convert_wchar_to_CFString(driver);

      /* Alloc a connection handle */
      drv_hdbc = NULL;
      drv_henv = NULL;

      _drv_u8 = (char *) dm_SQL_WtoU8((SQLWCHAR*)driver, SQL_NTS);
      if (_drv_u8 == NULL)
        goto skip;

      if ((handle = DLL_OPEN(_drv_u8)) != NULL)
        {
          if ((allocHdl = (pSQLAllocHandle)DLL_PROC(handle, "SQLAllocHandle")) != NULL)
            {
              ret = allocHdl(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &drv_henv);
	      if (ret == SQL_ERROR) goto nodriverver;
              ret = allocHdl(SQL_HANDLE_DBC, drv_henv, &drv_hdbc);
	      if (ret == SQL_ERROR) goto nodriverver;
            }
          else
            {
              if ((allocEnvHdl = (pSQLAllocEnv)DLL_PROC(handle, "SQLAllocEnv")) != NULL)
                {
                  ret = allocEnvHdl(&drv_henv);
	          if (ret == SQL_ERROR) goto nodriverver;
                }
              else goto nodriverver;

              if ((allocConnectHdl = (pSQLAllocConnect)DLL_PROC(handle, "SQLAllocConnect")) != NULL)
                {
                  ret = allocConnectHdl(drv_henv, &drv_hdbc);
	          if (ret == SQL_ERROR) goto nodriverver;
                }
              else goto nodriverver;
            }

	  /*
	   *  Use SQLGetInfoA for Unicode drivers
	   *  and SQLGetInfo  for ANSI drivers
	   */
          funcHdl = (pSQLGetInfoFunc)DLL_PROC(handle, "SQLGetInfoA");
	  if (!funcHdl)
	      funcHdl = (pSQLGetInfoFunc)DLL_PROC(handle, "SQLGetInfo");

	  if (funcHdl)
            {
              /* Retrieve some informations */
              ret = funcHdl (drv_hdbc, SQL_DRIVER_VER, drvattrs, sizeof(drvattrs), &len);
              if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
                {
		  char *p = drvattrs;

                  /* Find the description if one provided */
		  for (; *p ; p++) 
		    {
		      if (*p == ' ')
		        {
			  *p++ = '\0';
			  break;
			}
		    }

		  /*
		   * Store Version
		   */
                  Drivers_array[2][Drivers_nrows] = CFStringCreateWithCString(NULL, (char *)drvattrs, kCFStringEncodingUTF8);
                }
              else goto nodriverver;
            }
	  else if ((funcHdl = (pSQLGetInfoFunc)DLL_PROC(handle, "SQLGetInfoW")) != NULL) 
	    {
              /* Retrieve some informations */
              ret = funcHdl (drv_hdbc, SQL_DRIVER_VER, drvattrs, sizeof(drvattrs), &len);
              if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO)
                {
		  wchar_t *p = drvattrs;

                  /* Find the description if one provided */
		  for (; *p ; p++) 
		    {
		      if (*p == L' ')
		        {
			  *p++ = L'\0';
			  break;
			}
		    }

		  /*
		   * Store Version
		   */
                  Drivers_array[2][Drivers_nrows] = convert_wchar_to_CFString(drvattrs);
                }
              else goto nodriverver;
	        
	    }
          else goto nodriverver;
        }
      else
        {
nodriverver:
          Drivers_array[2][Drivers_nrows] = CFStringCreateWithCString(NULL,
            "##.##", kCFStringEncodingUTF8);
        }

      if(drv_hdbc || drv_henv)
        {
          if(allocConnectHdl &&
            (freeConnectHdl = (pSQLFreeConnect)DLL_PROC(handle, "SQLFreeConnect")) != NULL)
            { freeConnectHdl(drv_hdbc); drv_hdbc = NULL; }

          if(allocEnvHdl &&
            (freeEnvHdl = (pSQLFreeEnv)DLL_PROC(handle, "SQLFreeEnv")) != NULL)
            { freeEnvHdl(drv_henv); drv_henv = NULL; }
        }

      if ((drv_hdbc || drv_henv) &&
         (freeHdl = (pSQLFreeHandle)DLL_PROC(handle, "SQLFreeHandle")) != NULL)
        {
          if(drv_hdbc) freeHdl(SQL_HANDLE_DBC, drv_hdbc);
          if(drv_henv) freeHdl(SQL_HANDLE_ENV, drv_henv);
        }

      DLL_CLOSE(handle);

      /* Get the size and date of the driver */
      if (!stat (_drv_u8, &_stat))
	{
          CFStringRef strRef;
	  struct tm drivertime;
	  char buf[100];

          Drivers_array[3][Drivers_nrows] = 
            CFStringCreateWithFormat(NULL, NULL,
              strRef = CFStringCreateWithCString(NULL, "%d Kb", kCFStringEncodingUTF8),
              (int) (_stat.st_size / 1024));
	  CFRelease(strRef);

	  localtime_r (&_stat.st_mtime, &drivertime);
	  strftime (buf, sizeof (buf), "%c", &drivertime);
	  Drivers_array[4][Drivers_nrows] = CFStringCreateWithCString(NULL, 
	  	buf, kCFStringEncodingUTF8);
        }
      else
        {
	    Drivers_array[3][Drivers_nrows] = CFStringCreateWithCString(NULL,
	      "-", kCFStringEncodingUTF8);
	    Drivers_array[4][Drivers_nrows] = CFStringCreateWithCString(NULL,
	      "-", kCFStringEncodingUTF8);
	}

      for(i = 0 ; i < 5 ; i++)
        {
          GetThemeTextDimensions (Drivers_array[i][Drivers_nrows], kThemeSystemFont,
            kThemeStateActive, false, &ioBound, &outBaseline);
          if(colSize[i] < ioBound.h) colSize[i] = ioBound.h;
        }

      AddDataBrowserItems (widget, DBITEM_ID, 1, &item, DBNAME_ID);
      item++;
      Drivers_nrows++;

      /* Process next one */
    skip:
      MEM_FREE (_drv_u8);
      _drv_u8 = NULL;

      ret = SQLDriversW (henv, SQL_FETCH_NEXT, drvdesc,
	  sizeof (drvdesc)/sizeof(wchar_t), &len, drvattrs,
	  sizeof (drvattrs)/sizeof(wchar_t), &len1);
      if (ret != SQL_SUCCESS && ret != SQL_SUCCESS_WITH_INFO && ret != SQL_NO_DATA)
	{
	  _iodbcdm_nativeerrorbox (dlg, henv, SQL_NULL_HANDLE,
	      SQL_NULL_HANDLE);
	  goto error;
	}
    }

error:
  /* Clean all that */
  SQLFreeHandle (SQL_HANDLE_ENV, henv);

end:
  ActivateControl (widget);
  /* Resize the columns to have a good look */
  SetDataBrowserTableViewNamedColumnWidth (widget, DBNAME_ID, colSize[0] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBFILE_ID, colSize[1] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBVERSION_ID, colSize[2] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBSIZE_ID, colSize[3] + 20);
  SetDataBrowserTableViewNamedColumnWidth (widget, DBDATE_ID, colSize[4] + 20);
  DrawOneControl (widget);
  /* Remove the DataBrowser callback */
  SetDataBrowserCallbacks (NULL, &dbCallbacks);
  if(outState) DisposeThemeDrawingState (outState);
}
Esempio n. 17
0
void DataBaseMgr::Init()
{
	int char_id = 0;
	wchar_t char_name[100] = { 0, };
	int char_level = 0;
	float posX = 0, posY = 0;
	int exp = 0;
	int atk = 0;
	int def = 0;
	int hp = 0;

	SQLINTEGER  pIndicators[8];

	//setlocale(LC_ALL, "korean");

	SQLCHAR * OutConnStr = (SQLCHAR *)malloc(255);
	SQLSMALLINT * OutConnStrLen = (SQLSMALLINT *)malloc(255);

	// Allocate environment handle
	retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

	// Set the ODBC version environment attribute
	if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
		retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);

		// Allocate connection handle
		if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
			retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

			// Set login timeout to 5 seconds
			if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
				SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, 0);

				// Connect to data source
				retcode = SQLConnect(hdbc, (SQLCHAR*)"2010180020", SQL_NTS, (SQLCHAR*)"sa", SQL_NTS, (SQLCHAR*)"gamedb", SQL_NTS);

				// Allocate statement handle
				if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {
					retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);

					// Process data
					if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) {

						std::cout << "Connection Success \n";

						//retcode = SQLExecDirect(hstmt,
						//	// ID -> 1, Name -> 2, CLevel -> 3 column
						//	//(SQLCHAR*)"INSERT INTO dbo.exp_user_table VALUES (2, 'Hello', 1, 2.2, 3.3, 3, 5, 8)",
						//	//(SQLCHAR*)"SELECT ID, Nick, CLevel, XPos, YPos, EXP, Attack, Defence FROM dbo.exp_user_table",
						//	//(SQLCHAR*)"SELECT ID, Nick, CLevel, XPos, YPos, EXP, Attack, Defence FROM dbo.exp_user_table",
						//	//(SQLCHAR*)"EXEC dbo.SELECT_HIGHLEVEL 10",
						//	(SQLCHAR*)"SELECT * FROM dbo.exp_user_table WHERE Nick = 'Hello'",
						//	SQL_NTS);



						//if (retcode != SQL_ERROR)
						//{

						//	// Retrieve data from row set.
						//	SQLBindCol(hstmt, 1, SQL_C_LONG, (SQLPOINTER)&char_id, sizeof(char_id),
						//		&pIndicators[0]);

						//	// Retrieve data from row set.
						//	SQLBindCol(hstmt, 2, SQL_C_WCHAR, (SQLPOINTER)char_name, sizeof(char_name),
						//		&pIndicators[1]);

						//	// Retrieve data from row set.
						//	SQLBindCol(hstmt, 3, SQL_C_LONG, (SQLPOINTER)&char_level, sizeof(char_level),
						//		&pIndicators[2]);

						//	SQLBindCol(hstmt, 4, SQL_C_FLOAT, (SQLPOINTER)&posX, sizeof(posX),
						//		&pIndicators[3]);

						//	SQLBindCol(hstmt, 5, SQL_C_FLOAT, (SQLPOINTER)&posY, sizeof(posY),
						//		&pIndicators[4]);

						//	SQLBindCol(hstmt, 6, SQL_C_LONG, (SQLPOINTER)&exp, sizeof(exp),
						//		&pIndicators[5]);

						//	SQLBindCol(hstmt, 7, SQL_C_LONG, (SQLPOINTER)&atk, sizeof(atk),
						//		&pIndicators[6]);

						//	SQLBindCol(hstmt, 8, SQL_C_LONG, (SQLPOINTER)&def, sizeof(def),
						//		&pIndicators[7]);

						//	while (SQLFetch(hstmt) == SQL_SUCCESS)
						//	{
						//		std::wcout << "char_id: " << char_id << "\n";
						//		std::wcout << "char_name: " << char_name << "\n";
						//		std::wcout << "pos: " << posX << ", " << posY << "\n";
						//		std::wcout << "exp: " << exp << "\n";
						//		std::wcout << "atk: " << atk << "\n";
						//		std::wcout << "def: " << def << "\n";
						//	}
						//}
						if (retcode == SQL_ERROR)
						{
							// Error Handle
							HandleDiagnosticRecord(hstmt, SQL_HANDLE_STMT, retcode);
						}

						//SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
					}

					//SQLDisconnect(hdbc);
				}
				else
				{
					HandleDiagnosticRecord(hdbc, SQL_HANDLE_DBC, retcode);
				}

				//SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
			}
		}
		//SQLFreeHandle(SQL_HANDLE_ENV, henv);
	}
}
Esempio n. 18
0
File: core.c Progetto: NaldoDj/core
/* --- SDD METHODS --- */
static HB_ERRCODE odbcConnect( SQLDDCONNECTION * pConnection, PHB_ITEM pItem )
{
   SQLHENV    hEnv     = NULL;
   SQLHDBC    hConnect = NULL;
   char *     szError;
   HB_ERRCODE errCode;

#if ODBCVER >= 0x0300
   if( SQL_SUCCEEDED( SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv ) ) )
#else
   if( SQL_SUCCEEDED( SQLAllocEnv( &hEnv ) ) )
#endif
   {
#if ODBCVER >= 0x0300
      SQLSetEnvAttr( hEnv, SQL_ATTR_ODBC_VERSION, ( SQLPOINTER ) SQL_OV_ODBC3, SQL_IS_UINTEGER );
#endif

#if ODBCVER >= 0x0300
      if( SQL_SUCCEEDED( SQLAllocHandle( SQL_HANDLE_DBC, hEnv, &hConnect ) ) )
#else
      if( SQL_SUCCEEDED( SQLAllocConnect( hEnv, &hConnect ) ) )
#endif
      {
         const O_HB_CHAR * pchConStr;
         void *            hConnStr;
         HB_SIZE           nConnLen;
         SQLTCHAR          cBuffer[ 1024 ];
         SQLSMALLINT       iLen = HB_SIZEOFARRAY( cBuffer );

         cBuffer[ 0 ] = '\0';
         pchConStr = O_HB_ARRAYGETSTR( pItem, 2, &hConnStr, &nConnLen );

         if( SQL_SUCCEEDED( SQLDriverConnect( hConnect,
                                              NULL,
                                              ( SQLTCHAR * ) HB_UNCONST( pchConStr ),
                                              ( SQLSMALLINT ) nConnLen,
                                              cBuffer,
                                              HB_SIZEOFARRAY( cBuffer ),
                                              &iLen,
                                              SQL_DRIVER_NOPROMPT ) ) )
         {
            hb_strfree( hConnStr );
            pConnection->pSDDConn = hb_xgrab( sizeof( SDDCONN ) );
            ( ( SDDCONN * ) pConnection->pSDDConn )->hConn = hConnect;
            ( ( SDDCONN * ) pConnection->pSDDConn )->hEnv  = hEnv;
            return HB_SUCCESS;
         }
         else
         {
            hb_strfree( hConnStr );
            szError = odbcGetError( hEnv, hConnect, SQL_NULL_HSTMT, &errCode );
            hb_rddsqlSetError( errCode, szError, NULL, NULL, 0 );
            hb_xfree( szError );
         }
#if ODBCVER >= 0x0300
         SQLFreeHandle( SQL_HANDLE_DBC, hConnect );
#else
         SQLFreeConnect( hConnect );
#endif
      }
      else
      {
         szError = odbcGetError( hEnv, SQL_NULL_HDBC, SQL_NULL_HSTMT, &errCode );
         hb_errRT_ODBCDD( EG_OPEN, ESQLDD_CONNALLOC, szError, hb_arrayGetCPtr( pItem, 2 ), errCode );
         hb_xfree( szError );
      }
#if ODBCVER >= 0x0300
      SQLFreeHandle( SQL_HANDLE_ENV, hEnv );
#else
      SQLFreeEnv( hEnv );
#endif
   }
   else
   {
      szError = odbcGetError( SQL_NULL_HENV, SQL_NULL_HDBC, SQL_NULL_HSTMT, &errCode );
      hb_errRT_ODBCDD( EG_OPEN, ESQLDD_ENVALLOC, szError, hb_arrayGetCPtr( pItem, 2 ), errCode );
      hb_xfree( szError );
   }
   return HB_FAILURE;
}
Esempio n. 19
0
int	odbc_DBconnect(ZBX_ODBC_DBH *pdbh, const char *db_dsn, const char *user, const char *pass)
{
	SQLCHAR 	
	 	err_stat[10],
	 	err_msg[100];

	SQLINTEGER 
		err_int;

	SQLSMALLINT	
		err_msg_len;
	
	SQLRETURN	retcode;

	clean_odbc_strerror();

	memset(pdbh, 0 , sizeof(ZBX_ODBC_DBH));
	
	zabbix_log(LOG_LEVEL_DEBUG, "ODBC connect [%s] [%s]", db_dsn, user);

	/*Allocate environment handle */
	retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(pdbh->henv));
	if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
	{
		set_last_odbc_strerror("%s","failed environment handle allocation.");
	}
	else
	{
		/* Set the ODBC version environment attribute */
		retcode = SQLSetEnvAttr(pdbh->henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 
		if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
		{
			set_last_odbc_strerror("%s","failed ODBC version setting.");
		}
		else
		{
			/* Allocate connection handle */
			retcode = SQLAllocHandle(SQL_HANDLE_DBC, pdbh->henv, &(pdbh->hdbc)); 
			if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
			{
				set_last_odbc_strerror("%s","failed connection handle allocation.");
			}
			else
			{
				/* Set login timeout to 5 seconds. */
				SQLSetConnectAttr(pdbh->hdbc, (SQLINTEGER)SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, (SQLINTEGER)0);

				/* Connect to data source */
				retcode = SQLConnect(pdbh->hdbc,
					(SQLCHAR*) db_dsn, SQL_NTS,
					(SQLCHAR*) user, SQL_NTS,
					(SQLCHAR*) pass, SQL_NTS
					);
				if (retcode != SQL_SUCCESS && retcode != SQL_SUCCESS_WITH_INFO)
				{
	
					SQLGetDiagRec(SQL_HANDLE_DBC, 
							pdbh->hdbc,
							1,
							err_stat,
							&err_int,
							err_msg,
							sizeof(err_msg),
							&err_msg_len
							);
					
					set_last_odbc_strerror("failed connection [%s] (%d)", err_msg, err_int);
				}
				else
				{
					pdbh->connected = 1;

					/* Allocate statement handle */
					retcode = SQLAllocHandle(SQL_HANDLE_STMT, pdbh->hdbc, &(pdbh->hstmt)); 

					if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
					{
						return SUCCEED;
					}
					else
					{
						SQLFreeHandle(SQL_HANDLE_STMT, pdbh->hstmt);
						pdbh->hstmt = NULL;
					}
					SQLDisconnect(pdbh->hdbc);
				}
				SQLFreeHandle(SQL_HANDLE_DBC, pdbh->hdbc);
				pdbh->hdbc = NULL;
			}
		}
		SQLFreeHandle(SQL_HANDLE_ENV, pdbh->henv);
		pdbh->henv = NULL;
	}

	zabbix_log(LOG_LEVEL_ERR, "Failed to connect to DSN '%s' : Error: %s", db_dsn, get_last_odbc_strerror());
	return FAIL; /* error */
}
Esempio n. 20
0
int
main(int argc, char *argv[])
{
    LOGINREC *login;
    SQLHENV hEnv = 0;
    SQLHDBC hDbc = 0;
    SQLRETURN erc;
    const char *sql;

    setlocale(LC_ALL, "");

    memset(&options, 0, sizeof(options));
    options.headers = stderr;
    login = get_login(argc, argv, &options); /* get command-line parameters and call dblogin() */
    assert(login != NULL);

    /*
     * Override stdin, stdout, and stderr, as required
     */
    if (options.input_filename) {
        if (freopen(options.input_filename, "r", stdin) == NULL) {
            fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.input_filename, strerror(errno));
            exit(1);
        }
    }

    if (options.output_filename) {
        if (freopen(options.output_filename, "w", stdout) == NULL) {
            fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.output_filename, strerror(errno));
            exit(1);
        }
    }

    if (options.error_filename) {
        if (freopen(options.error_filename, "w", stderr) == NULL) {
            fprintf(stderr, "%s: unable to open %s: %s\n", options.appname, options.error_filename, strerror(errno));
            exit(1);
        }
    }

    if (options.fverbose) {
        options.verbose = stderr;
    } else {
        static const char null_device[] = "/dev/null";
        options.verbose = fopen(null_device, "w");
        if (options.verbose == NULL) {
            fprintf(stderr, "%s:%d unable to open %s for verbose operation: %s\n",
                    options.appname, __LINE__, null_device, strerror(errno));
            exit(1);
        }
    }

    fprintf(options.verbose, "%s:%d: Verbose operation enabled\n", options.appname, __LINE__);

    /*
     * Connect to the server
     */
    if ((erc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv)) != SQL_SUCCESS) {
        odbc_herror(SQL_HANDLE_ENV, hEnv, erc, "SQLAllocHandle", "failed to allocate an environment");
        exit(EXIT_FAILURE);
    }
    assert(hEnv);

    if ((erc = SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)options.odbc_version, SQL_IS_UINTEGER)) != SQL_SUCCESS) {
        odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLSetEnvAttr", "failed to set SQL_OV_ODBC3");
        exit(EXIT_FAILURE);
    }

    if ((erc = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc)) != SQL_SUCCESS) {
        odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLAllocHandle", "failed to allocate a connection");
        exit(EXIT_FAILURE);
    }
    assert(hDbc);

    if ((erc = SQLConnect(hDbc, 	(SQLCHAR *) options.servername, SQL_NTS,
                          (SQLCHAR *) login->username, SQL_NTS,
                          (SQLCHAR *) login->password, SQL_NTS)) != SQL_SUCCESS) {
        odbc_herror(SQL_HANDLE_DBC, hDbc, erc, "SQLConnect", "failed");
        exit(EXIT_FAILURE);
    }

#if 0
    /* Switch to the specified database, if any */
    if (options.database)
        dbuse(dbproc, options.database);
#endif

    /*
     * Read the queries and write the results
     */
    while ((sql = next_query()) != NULL ) {
        SQLHSTMT hStmt;

        if ((erc = SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt)) != SQL_SUCCESS) {
            odbc_perror(hStmt, erc, "SQLAllocHandle", "failed to allocate a statement handle");
            exit(EXIT_FAILURE);
        }

        /* "Prepare" the query and send it to the server */
        if ((erc = SQLPrepare(hStmt, (SQLCHAR *) sql, SQL_NTS)) != SQL_SUCCESS) {
            odbc_perror(hStmt, erc, "SQLPrepare", "failed");
            exit(EXIT_FAILURE);
        }

        if((erc = SQLExecute(hStmt)) != SQL_SUCCESS) {
            switch(erc) {
            case SQL_NEED_DATA:
                goto FreeStatement;
            case SQL_SUCCESS_WITH_INFO:
                if (0 != print_error_message(SQL_HANDLE_STMT, hStmt)) {
                    fprintf(stderr, "SQLExecute: continuing...\n");
                }
                break;
            default:
                odbc_perror(hStmt, erc, "SQLExecute", "failed");
                exit(EXIT_FAILURE);
            }
        }

        /* Write the output */
        print_results(hStmt);

FreeStatement:
        if ((erc = SQLFreeHandle(SQL_HANDLE_STMT, hStmt)) != SQL_SUCCESS) {
            odbc_perror(hStmt, erc, "SQLFreeHandle", "failed");
            exit(EXIT_FAILURE);
        }
    }

    SQLDisconnect(hDbc);
    SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
    SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

    return 0;
}
Esempio n. 21
0
/*%
 * create an instance of the driver.  Remember, only 1 copy of the driver's
 * code is ever loaded, the driver has to remember which context it's
 * operating in.  This is done via use of the dbdata argument which is
 * passed into all query functions.
 */
static isc_result_t
odbc_create(const char *dlzname, unsigned int argc, char *argv[],
	    void *driverarg, void **dbdata)
{
	isc_result_t result;
	odbc_instance_t *odbc_inst = NULL;
	dbinstance_t *db = NULL;
	SQLRETURN sqlRes;

#ifdef ISC_PLATFORM_USETHREADS
	/* if multi-threaded, we need a few extra variables. */
	int dbcount;
	int i;
	char *endp;

#endif /* ISC_PLATFORM_USETHREADS */

	UNUSED(dlzname);
	UNUSED(driverarg);

#ifdef ISC_PLATFORM_USETHREADS
	/* if debugging, let user know we are multithreaded. */
	isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
		      DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1),
		      "Odbc driver running multithreaded");
#else /* ISC_PLATFORM_USETHREADS */
	/* if debugging, let user know we are single threaded. */
	isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
		      DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1),
		      "Odbc driver running single threaded");
#endif /* ISC_PLATFORM_USETHREADS */

	/* verify we have at least 5 arg's passed to the driver */
	if (argc < 5) {
		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
			      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
			      "Odbc driver requires at least "
			      "4 command line args.");
		return (ISC_R_FAILURE);
	}

	/* no more than 8 arg's should be passed to the driver */
	if (argc > 8) {
		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
			      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
			      "Odbc driver cannot accept more than "
			      "7 command line args.");
		return (ISC_R_FAILURE);
	}

	/* multithreaded build can have multiple DB connections */
#ifdef ISC_PLATFORM_USETHREADS

	/* check how many db connections we should create */
	dbcount = strtol(argv[1], &endp, 10);
	if (*endp != '\0' || dbcount < 0) {
		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
			      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
			      "Odbc driver database connection count "
			      "must be positive.");
		return (ISC_R_FAILURE);
	}

#endif /* ISC_PLATFORM_USETHREADS */

	/* allocate memory for odbc instance */
	odbc_inst = isc_mem_get(ns_g_mctx, sizeof(odbc_instance_t));
	if (odbc_inst == NULL)
		return (ISC_R_NOMEMORY);
	memset(odbc_inst, 0, sizeof(odbc_instance_t));

	/* parse connection string and get paramters. */

	/* get odbc database dsn - required */
	odbc_inst->dsn = (SQLCHAR *) getParameterValue(argv[2],
						       "dsn=");
	if (odbc_inst->dsn == NULL) {
		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
			      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
			      "odbc driver requires a dns parameter.");
		result = ISC_R_FAILURE;
		goto cleanup;
	}
	/* get odbc database username */
	/* if no username was passed, set odbc_inst.user = NULL; */
	odbc_inst->user = (SQLCHAR *) getParameterValue(argv[2],
							"user="******"pass="******"Odbc driver unable to allocate memory");
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
		/*set ODBC version = 3 */
		sqlRes = SQLSetEnvAttr(odbc_inst->sql_env,
				       SQL_ATTR_ODBC_VERSION,
				       (void *) SQL_OV_ODBC3, 0);
		if (!sqlOK(sqlRes)) {
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
				      DNS_LOGMODULE_DLZ, ISC_LOG_INFO,
				      "Unable to configure ODBC environment");
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}
	}

#ifdef ISC_PLATFORM_USETHREADS

	/* allocate memory for database connection list */
	odbc_inst->db = isc_mem_get(ns_g_mctx, sizeof(db_list_t));
	if (odbc_inst->db == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}


	/* initialize DB connection list */
	ISC_LIST_INIT(*odbc_inst->db);

	/* create the appropriate number of database instances (DBI) */
	/* append each new DBI to the end of the list */
	for (i=0; i < dbcount; i++) {

#endif /* ISC_PLATFORM_USETHREADS */

		/* how many queries were passed in from config file? */
		switch(argc) {
		case 5:
			result = build_sqldbinstance(ns_g_mctx, NULL, NULL,
						     NULL, argv[3], argv[4],
						     NULL, &db);
			break;
		case 6:
			result = build_sqldbinstance(ns_g_mctx, NULL, NULL,
						     argv[5], argv[3], argv[4],
						     NULL, &db);
			break;
		case 7:
			result = build_sqldbinstance(ns_g_mctx, argv[6], NULL,
						     argv[5], argv[3], argv[4],
						     NULL, &db);
			break;
		case 8:
			result = build_sqldbinstance(ns_g_mctx, argv[6],
						     argv[7], argv[5], argv[3],
						     argv[4], NULL, &db);
			break;
		default:
			/* not really needed, should shut up compiler. */
			result = ISC_R_FAILURE;
		}

		/* unsuccessful?, log err msg and cleanup. */
		if (result != ISC_R_SUCCESS) {
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
				      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
				      "Odbc driver could not create "
				      "database instance object.");
			goto cleanup;
		}

#ifdef ISC_PLATFORM_USETHREADS

		/* when multithreaded, build a list of DBI's */
		ISC_LINK_INIT(db, link);
		ISC_LIST_APPEND(*odbc_inst->db, db, link);

#endif

		result = odbc_connect(odbc_inst, (odbc_db_t **) &(db->dbconn));

		if (result != ISC_R_SUCCESS) {

#ifdef ISC_PLATFORM_USETHREADS

			/*
			 * if multi threaded, let user know which
			 * connection failed.  user could be
			 * attempting to create 10 db connections and
			 * for some reason the db backend only allows
			 * 9.
			 */
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
				      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
				      "Odbc driver failed to create database "
				      "connection number %u after 3 attempts",
				      i+1);
#else
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
				      DNS_LOGMODULE_DLZ, ISC_LOG_ERROR,
				      "Odbc driver failed to create database "
				      "connection after 3 attempts");
#endif
			goto cleanup;
		}

#ifdef ISC_PLATFORM_USETHREADS

		/* set DB = null for next loop through. */
		db = NULL;

	}	/* end for loop */

#else
	/* tell odbc_inst about the db connection we just created. */
	odbc_inst->db = db;

#endif

	/* set dbdata to the odbc_instance we created. */
	*dbdata = odbc_inst;

	/* hey, we got through all of that ok, return success. */
	return(ISC_R_SUCCESS);

 cleanup:

	destroy_odbc_instance(odbc_inst);

	return result;
}
bool DbHelper::Initialize(const wchar_t* connInfoStr, int workerThreadCount)
{


	//todo: mSqlConnPool, mDbWorkerThreadCount를 워커스레스 수에 맞추어 초기화
	mDbWorkerThreadCount = workerThreadCount;
	mSqlConnPool = new SQL_CONN[mDbWorkerThreadCount];

	// 	SQLRETURN ret = SQL_ERROR;
	// 
	// 	for ( int i = 0; i < mDbWorkerThreadCount; ++i )
	// 	{
	// 		ret = SQLConnect( mSqlConnPool[i].mSqlHdbc, NULL, (SQLWCHAR*)connInfoStr, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT );
	// 	}


	if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &mSqlHenv))
	{
		printf_s("DbHelper Initialize SQLAllocHandle failed\n");
		return false;
	}

	if (SQL_SUCCESS != SQLSetEnvAttr(mSqlHenv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER))
	{
		printf_s("DbHelper Initialize SQLSetEnvAttr failed\n");
		return false;
	}


	/// 스레드별로 SQL connection을 풀링하는 방식. 즉, 스레드마다 SQL서버로의 연결을 갖는다.
	for (int i = 0; i < mDbWorkerThreadCount; ++i)
	{
		//todo: SQLAllocHandle을 이용하여 SQL_CONN의 mSqlHdbc 핸들 사용가능하도록 처리
		///# 왜 에러처리 안함? SQLAllocHandle( SQL_HANDLE_DBC, mSqlHenv, &mSqlConnPool[i].mSqlHdbc );

		
		if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, mSqlHenv, &mSqlConnPool[i].mSqlHdbc))
		{
			printf_s("DbHelper Initialize SQLAllocHandle failed\n");
			return false;
		}
		
		//이거 어디서 쓰지?
		//http://msdn.microsoft.com/en-us/library/ms715433(v=vs.85).aspx
		//예제코드 참고
		SQLSMALLINT resultLen = 0;
		
		//todo: SQLDriverConnect를 이용하여 SQL서버에 연결하고 그 핸들을 SQL_CONN의 mSqlHdbc에 할당
		//마지막 인자를 PROMPT로 하면 a dialog box prompts the user to specify whether the file should be overwritten
		SQLRETURN ret = SQLDriverConnect( mSqlConnPool[i].mSqlHdbc, NULL, (SQLWCHAR*)connInfoStr, SQL_NTS, NULL, 0, &resultLen, SQL_DRIVER_NOPROMPT );

		if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret)
		{
			SQLWCHAR sqlState[1024] = { 0, } ;
			SQLINTEGER nativeError = 0;
			SQLWCHAR msgText[1024] = { 0, } ;
			SQLSMALLINT textLen = 0 ;

			SQLGetDiagRec(SQL_HANDLE_DBC, mSqlConnPool[i].mSqlHdbc, 1, sqlState, &nativeError, msgText, 1024, &textLen);

			wprintf_s(L"DbHelper Initialize SQLDriverConnect failed: %s \n", msgText);

			return false;
		}

		//todo: SQLAllocHandle를 이용하여 SQL_CONN의 mSqlHstmt 핸들 사용가능하도록 처리
		///# 에러처리... SQLAllocHandle(SQL_HANDLE_STMT, mSqlConnPool[i].mSqlHdbc, &mSqlConnPool[i].mSqlHstmt);

		if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, mSqlConnPool[i].mSqlHdbc, &mSqlConnPool[i].mSqlHstmt))
		{
			printf_s("DbHelper Initialize SQLAllocHandle SQL_HANDLE_STMT failed\n");
			return false;
		}

	
	}

	return true;
}
Esempio n. 23
0
int main()
{
  SQLHENV env;
  SQLHDBC dbc;
  SQLHSTMT stmt;
  SQLRETURN ret;
  SQLCHAR outstr[1024];
  SQLSMALLINT outstrlen;
  
  // Aloocate an environment handle
  ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
  checkrc(ret,__LINE__);
  
   //we need odbc3 support
  ret =  SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
  checkrc(ret,__LINE__); 
  //ALLOCATE A Connection handle
  ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
  checkrc(ret,__LINE__);
    
  // connect to the DSN mydsn
   ret = SQLConnect (dbc,
                   (SQLCHAR *) "test", (SQLSMALLINT) strlen ("test"),
                   (SQLCHAR *) "root",
                   (SQLSMALLINT) strlen ("root"),
                   (SQLCHAR *) "manager",
                   (SQLSMALLINT) strlen (""));
 
  if(SQL_SUCCEEDED(ret))
  {
     printf("\nConnected to the Data Source SUCCESSFULLY..\n");
     
 
  }
   else
   {
        printf("error in connection\n");                
        return 1;
 
        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__);
        return 1;      
   
  }

   
   //******************************************************************
   // TABLE CREATED
   ret = SQLAllocHandle(SQL_HANDLE_STMT,dbc,&stmt);
   checkrc(ret,__LINE__);
   
   SQLCHAR table[200]=
     "CREATE TABLE T1(F1 INT,F2 SMALLINT,F3 CHAR(30),F4 FLOAT,F5 FLOAT,F6 DATE,F7 TIME,F8 TIMESTAMP,F9 TINYINT,F10 BIGINT)";
   ret = SQLPrepare(stmt,table,SQL_NTS);
   checkrc(ret,__LINE__);
   ret = SQLExecute(stmt);
   checkrc(ret,__LINE__);
   printf("\nTABLE CREATED\n"); 
   //*****************************
   InsertTest(env,dbc,stmt);  
   FetchTest(env,dbc,stmt);

   //****************************************************************      
    SQLCHAR drop[100]="DROP TABLE T1";
    ret = SQLPrepare(stmt,drop,SQL_NTS);
    checkrc(ret,__LINE__);
    ret = SQLExecute(stmt);
    if(ret!=SQL_SUCCESS && ret !=SQL_SUCCESS_WITH_INFO)
    {   
     printf("Statement failed\n");
     return 2;
    }
    else
       printf("Table  'T1' dropped successfully\n");  

    ret = SQLFreeHandle(SQL_HANDLE_STMT,stmt);
    checkrc(ret,__LINE__);

   ret = SQLDisconnect(dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
   checkrc(ret,__LINE__);
   
   ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
   checkrc(ret,__LINE__);
   return 0;
}         
Esempio n. 24
0
int main()
{

	GET_LOGIN_VARS();
	VERBOSE("calling SQLAllocHandle(EnvHandle) \n");

	rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvHandle);
	assert(rc == SQL_SUCCESS);
	assert(EnvHandle != (SQLHANDLE) NULL);

	rc = SQLSetEnvAttr(EnvHandle, SQL_ATTR_ODBC_VERSION,
			   (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER);

	assert(rc == SQL_SUCCESS);

	VERBOSE("calling SQLAllocHandle(ConHandle) \n");

	rc = SQLAllocHandle(SQL_HANDLE_DBC, EnvHandle, &ConHandle);
	assert(ConHandle != (SQLHANDLE) NULL);
	assert(rc == SQL_SUCCESS);

	if (dsn[0])
		rc = SQLDriverConnect(ConHandle, NULL, dsn,
				      SQL_NTS, NULL, 0, NULL,
				      SQL_DRIVER_NOPROMPT);
	else
		rc = SQLConnect(ConHandle, twoTask, SQL_NTS,
				(SQLCHAR *) userName, SQL_NTS, (SQLCHAR *) pswd,
				SQL_NTS);
	assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO);

	VERBOSE("connected to  database %s\n", twoTask);

	rc = SQLAllocStmt(ConHandle, &StmtHandle);
	assert(rc == SQL_SUCCESS);

	sprintf(SQLStmt, "drop table some_types");
	rc = SQLExecDirect(StmtHandle, SQLStmt, SQL_NTS);

	sprintf(SQLStmt,
		"create table some_types (an_int integer primary key, ");
	strcat(SQLStmt, " a_float float, a_string varchar(255)) ");

	rc = SQLExecDirect(StmtHandle, SQLStmt, SQL_NTS);

	assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO);
	VERBOSE("success: executed statement: %s \n", SQLStmt);

	VERBOSE("calling SQLFreeStmt\n");
	if (StmtHandle != NULL)
		rc = SQLFreeHandle(SQL_HANDLE_STMT, StmtHandle);
	assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO);

	rc = SQLDisconnect(ConHandle);
	assert(rc == SQL_SUCCESS);
	VERBOSE("disconnected from  database\n");

	VERBOSE("calling SQLFreeHandle(ConHandle) \n");

	assert(ConHandle != (SQLHANDLE) NULL);
	rc = SQLFreeHandle(SQL_HANDLE_DBC, ConHandle);
	assert(rc == SQL_SUCCESS);

	VERBOSE("calling SQLFreeHandle(EnvHandle) \n");

	assert(EnvHandle != (SQLHANDLE) NULL);
	rc = SQLFreeHandle(SQL_HANDLE_ENV, EnvHandle);
	assert(rc == SQL_SUCCESS);

	return (rc);
}
Esempio n. 25
0
my_bool DSNDialog(HWND hwndParent,
                  WORD fRequest,
                  LPCSTR lpszDriver,
                  LPCSTR lpszAttributes,
                  MADB_Dsn *Dsn)
{
  MSG msg;
  BOOL ret;
  char *DsnName= NULL;
  my_bool DsnExists= FALSE;

  if (Dsn->isPrompt < 0 || Dsn->isPrompt > MAODBC_PROMPT_REQUIRED)
  {
    Dsn->isPrompt= MAODBC_CONFIG;
  }

  EffectiveDisabledPages=     DisabledPages[Dsn->isPrompt];
  EffectiveDisabledControls=  DisabledControls[Dsn->isPrompt];

  if (lpszAttributes)
    DsnName= strchr((char *)lpszAttributes, '=');
  
  if (lpszDriver)
    MADB_DriverGet((char *)lpszDriver);

  if (DsnName)
  {
    ++DsnName;
    /* In case of prompting we are supposed to show dialog even DSN name is incorrect */
    if (!Dsn->isPrompt && !SQLValidDSN(DsnName))
    {
      if (hwndParent)
        MessageBox(hwndParent, "Validation of data source name failed", "Error", MB_ICONERROR | MB_OK);
      return FALSE;
    }
  }

  if (!DsnName && Dsn && Dsn->DSNName)
  {
    DsnName= Dsn->DSNName;
  }
  else if (DsnName && Dsn)
  {
    /* Need to free current value in Dsn->DSNName */
    MADB_SUBSTITUTE(Dsn->DSNName, _strdup(DsnName));
  }

  /* Even if DsnName invalid(in case of prompt) - we should not have problem */
  DsnExists= MADB_DSN_Exists(DsnName);
 
  InitCommonControls();

  if (lpszDriver)
    Dsn->Driver= _strdup(lpszDriver);

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

  if (fRequest == ODBC_ADD_DSN)
  {
    if (DsnExists && hwndParent)
    {
      if (MessageBox(hwndParent, "Data source name already exists, do you want to replace it?", 
                      "Question", MB_ICONQUESTION | MB_YESNO) != IDYES)
        return FALSE;
    }
    Dsn->IsTcpIp= 1;
  }
  else
  {
    /* i.e. not a prompt */
    if (Dsn->isPrompt == MAODBC_CONFIG)
    {
      if (!DsnExists)
      {
        MessageBox(0, "Data source name not found", "Error", MB_ICONERROR | MB_OK);
        return FALSE;
      }
      else if (!MADB_ReadDSN(Dsn, (char *)lpszAttributes, TRUE))
      {
        SQLPostInstallerError(ODBC_ERROR_INVALID_DSN, Dsn->ErrorMsg);
        return FALSE;
      }
    }
  }

  notCanceled= TRUE;
  hwndMain= CreateDialogParam(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), 0, DialogProc, 0);
  SetWindowLongPtr(hwndMain, DWLP_USER, (LONG)Dsn);

  /* Setting first not disabled page */
  CurrentPage= -1;
  SetPage(hwndMain, 1);

  Edit_SetReadOnly(GetDlgItem(hwndTab[0], txtDsnName), 
                   (hwndParent && DsnName && fRequest == ODBC_ADD_DSN) ? TRUE : FALSE);

  SetDialogFields();
  CenterWindow(hwndMain);
  ShowWindow(hwndMain, SW_SHOW);

  while((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
    if(ret == -1)
      break;

    if(!IsDialogMessage(hwndTab[CurrentPage], &msg)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  SQLFreeHandle(SQL_HANDLE_ENV, Environment);

  return notCanceled;
}
Esempio n. 26
0
//*************************************************************************
int main()
{
    SQLHENV env;
    SQLHDBC dbc;
    SQLHSTMT stmt;
    SQLRETURN ret;
    SQLCHAR outstr[1024];
    SQLSMALLINT outstrlen;

    // Aloocate an environment handle
    ret=SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
    checkrc(ret,__LINE__);

    //we need odbc3 support
    SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);

    //ALLOCATE A Connection handle
    ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&dbc);
    checkrc(ret,__LINE__);
    //**************************************************************************************************
    // connect to the DSN mydsn
    ret = SQLConnect (dbc,
                      (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;"),
                      (SQLCHAR *) "root",
                      (SQLSMALLINT) strlen ("root"),
                      (SQLCHAR *) "manager",
                      (SQLSMALLINT) strlen (""));


    if(SQL_SUCCEEDED(ret))
    {
        printf("\nConnected to the Data Source successfully..\n");

    }
    else
    {
        printf("connection failed\n");

        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__);

        return 1;
    }

    ret = SQLDisconnect(dbc);
    checkrc(ret,__LINE__);
    printf("Disconnected from the Datasource\n");
    //**************************************************************************************************
    // again sqlconnect




    ret =   SQLConnect (dbc,
                        (SQLCHAR *) "DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;", (SQLSMALLINT) strlen ("DSN=mycsql;MODE=csql;SERVER=127.0.0.1;PORT=5678;"),
                        (SQLCHAR *) "root",
                        (SQLSMALLINT) strlen ("root"),
                        (SQLCHAR *) "manager",
                        (SQLSMALLINT) strlen (""));

    int rettype =ret;

    if(SQL_SUCCEEDED(ret))
    {
        printf("Again Connected to the Data Source successfully..\n");


    }
    else
    {
        printf("connection failed\n");

        ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
        checkrc(ret,__LINE__);

        ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
        checkrc(ret,__LINE__);

        return 1;
    }

    ret = SQLDisconnect(dbc);
    checkrc(ret,__LINE__);

    //**************************************************************************************************
    ret = SQLFreeHandle(SQL_HANDLE_DBC,dbc);
    checkrc(ret,__LINE__);

    ret = SQLFreeHandle(SQL_HANDLE_ENV,env);
    checkrc(ret,__LINE__);
    if(rettype !=0)return 1;
    return 0;
}
Esempio n. 27
0
int
ODBC_Connect (char *connStr)
{
  short buflen;
  SQLCHAR dataSource[1024];
  SQLTCHAR dsn[33];
  SQLTCHAR desc[255];
  SQLTCHAR driverInfo[255];
  SQLSMALLINT len1, len2;
  int status;
#ifdef UNICODE
  SQLWCHAR wdataSource[1024];
#endif

#if (ODBCVER < 0x0300)
  if (SQLAllocEnv (&henv) != SQL_SUCCESS)
    return -1;

  if (SQLAllocConnect (henv, &hdbc) != SQL_SUCCESS)
    return -1;
#else
  if (SQLAllocHandle (SQL_HANDLE_ENV, NULL, &henv) != SQL_SUCCESS)
    return -1;

  SQLSetEnvAttr (henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3,
      SQL_IS_UINTEGER);

  if (SQLAllocHandle (SQL_HANDLE_DBC, henv, &hdbc) != SQL_SUCCESS)
    return -1;
#endif


  /*
   *  Set the application name
   */
  SQLSetConnectOption (hdbc, SQL_APPLICATION_NAME,
	(SQLULEN) TEXT ("odbctest"));


  /*
   *  Show the version number of the driver manager
   */
  status = SQLGetInfo (hdbc, SQL_DM_VER,
      driverInfo, sizeof (driverInfo), &len1);
  if (status == SQL_SUCCESS)
    {
#ifdef UNICODE
      printf ("Driver Manager: %S\n", driverInfo);
#else
      printf ("Driver Manager: %s\n", driverInfo);
#endif
    }


  /*
   *  Either use the connect string provided on the command line or
   *  ask for one. If an empty string or a ? is given, show a nice
   *  list of options
   */
  if (connStr && *connStr)
    strcpy ((char *) dataSource, connStr);
  else
    while (1)
      {
	/*
	 *  Ask for the connect string
	 */
	printf ("\nEnter ODBC connect string (? shows list): ");
	if (fgets ((char *) dataSource, sizeof (dataSource), stdin) == NULL)
	  return 1;

	/*
	 *  Remove trailing '\n'
	 */
	dataSource[strlen ((char *) dataSource) - 1] = '\0';

	/*
	 * Check if the user wants to quit
	 */
	if (!strcmp ((char *)dataSource, "quit") || !strcmp ((char *)dataSource, "exit"))
	  return -1;

	/*
	 *  If the user entered something other than a ?
	 *  break out of the while loop
	 */
	if (*dataSource && *dataSource != '?')
	  break;


	/*
	 *  Print headers
	 */
	fprintf (stderr, "\n%-32s | %-40s\n", "DSN", "Driver");
	fprintf (stderr,
	    "------------------------------------------------------------------------------\n");

	/*
	 *  Goto the first record
	 */
	if (SQLDataSources (henv, SQL_FETCH_FIRST,
		dsn, NUMTCHAR (dsn), &len1,
		desc, NUMTCHAR (desc), &len2) != SQL_SUCCESS)
	  continue;

	/*
	 *  Show all records
	 */
	do
	  {
#ifdef UNICODE
	    fprintf (stderr, "%-32S | %-40S\n", dsn, desc);
#else
	    fprintf (stderr, "%-32s | %-40s\n", dsn, desc);
#endif
	  }
	while (SQLDataSources (henv, SQL_FETCH_NEXT,
		dsn, NUMTCHAR (dsn), &len1,
		desc, NUMTCHAR (desc), &len2) == SQL_SUCCESS);
      }

#ifdef UNICODE
  strcpy_A2W (wdataSource, (char *) dataSource);
  status = SQLDriverConnectW (hdbc, 0, (SQLWCHAR *) wdataSource, SQL_NTS,
      (SQLWCHAR *) outdsn, NUMTCHAR (outdsn), &buflen, SQL_DRIVER_COMPLETE);
  if (status != SQL_SUCCESS)
    ODBC_Errors ("SQLDriverConnectW");
#else
  status = SQLDriverConnect (hdbc, 0, (SQLCHAR *) dataSource, SQL_NTS,
      (SQLCHAR *) outdsn, NUMTCHAR (outdsn), &buflen, SQL_DRIVER_COMPLETE);
  if (status != SQL_SUCCESS)
    ODBC_Errors ("SQLDriverConnect");
#endif

  if (status != SQL_SUCCESS && status != SQL_SUCCESS_WITH_INFO)
    return -1;

  connected = 1;


  /*
   *  Print out the version number and the name of the connected driver
   */
  status = SQLGetInfo (hdbc, SQL_DRIVER_VER,
      driverInfo, NUMTCHAR (driverInfo), &len1);
  if (status == SQL_SUCCESS)
    {
#ifdef UNICODE
      printf ("Driver: %S", driverInfo);
#else
      printf ("Driver: %s", driverInfo);
#endif

      status = SQLGetInfo (hdbc, SQL_DRIVER_NAME,
	  driverInfo, NUMTCHAR (driverInfo), &len1);
      if (status == SQL_SUCCESS)
	{
#ifdef UNICODE
	  printf (" (%S)", driverInfo);
#else
	  printf (" (%s)", driverInfo);
#endif
	}
      printf ("\n");
    }


  /*
   *  Show the list of supported functions in trace log
   */
#if (ODBCVER < 0x0300)
  {
     SQLUSMALLINT exists[100];

     SQLGetFunctions (hdbc, SQL_API_ALL_FUNCTIONS, exists);
  }
#else
  {
     SQLUSMALLINT exists[SQL_API_ODBC3_ALL_FUNCTIONS_SIZE];

     SQLGetFunctions (hdbc, SQL_API_ODBC3_ALL_FUNCTIONS, exists);
  }
#endif



  /*
   *  Allocate statement handle
   */
#if (ODBCVER < 0x0300)
  if (SQLAllocStmt (hdbc, &hstmt) != SQL_SUCCESS)
    return -1;
#else
  if (SQLAllocHandle (SQL_HANDLE_STMT, hdbc, &hstmt) != SQL_SUCCESS)
    return -1;
#endif

  return 0;
}
Esempio n. 28
0
int main()
{
    int i;
    int sz = sizeof(cmds) / sizeof(*cmds);

    if (getenv("NO_CLEANUP"))
        return 0;

    GET_LOGIN_VARS();
    VERBOSE("calling SQLAllocHandle(EnvHandle) \n");

    rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvHandle);
    assert(rc == SQL_SUCCESS);
    assert(EnvHandle != (SQLHANDLE) NULL);

    rc = SQLSetEnvAttr(EnvHandle, SQL_ATTR_ODBC_VERSION,
                       (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER);

    assert(rc == SQL_SUCCESS);

    VERBOSE("calling SQLAllocHandle(ConHandle) \n");

    rc = SQLAllocHandle(SQL_HANDLE_DBC, EnvHandle, &ConHandle);
    assert(ConHandle != (SQLHANDLE) NULL);
    assert(rc == SQL_SUCCESS);

    if (dsn[0])
        rc = SQLDriverConnect(ConHandle, NULL, dsn,
                              SQL_NTS, NULL, 0, NULL,
                              SQL_DRIVER_NOPROMPT);
    else
        rc = SQLConnect(ConHandle, twoTask, SQL_NTS,
                        (SQLCHAR *) userName, SQL_NTS, (SQLCHAR *) pswd,
                        SQL_NTS);
    assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO);

    VERBOSE("connected to  database %s\n", twoTask);

    rc = SQLAllocStmt(ConHandle, &StmtHandle);
    assert(rc == SQL_SUCCESS);

    for (i = 0; i < sz; i++) {
        VERBOSE("executing statement: %s \n", cmds[i]);
        rc = SQLExecDirect(StmtHandle, cmds[i], SQL_NTS);
    }

    VERBOSE("calling SQLFreeStmt\n");
    if (StmtHandle != NULL)
        rc = SQLFreeHandle(SQL_HANDLE_STMT, StmtHandle);
    assert(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO);

    rc = SQLDisconnect(ConHandle);
    assert(rc == SQL_SUCCESS);
    VERBOSE("disconnected from  database\n");

    VERBOSE("calling SQLFreeHandle(ConHandle) \n");

    assert(ConHandle != (SQLHANDLE) NULL);
    rc = SQLFreeHandle(SQL_HANDLE_DBC, ConHandle);
    assert(rc == SQL_SUCCESS);

    VERBOSE("calling SQLFreeHandle(EnvHandle) \n");

    assert(EnvHandle != (SQLHANDLE) NULL);
    rc = SQLFreeHandle(SQL_HANDLE_ENV, EnvHandle);
    assert(rc == SQL_SUCCESS);

    return (rc);
}
Esempio n. 29
0
void mssql_database::on_open(const std::string &connection)
{
  // parse user[:passwd]@host/db ([Drivername])
  std::string con = connection;
  std::string::size_type pos = con.find('@');
  std::string user, passwd;
  std::string driver;
//  bool has_pwd = true;
  if (pos == std::string::npos) {
	  throw_error("mssql:open", "invalid dsn: " + connection);
  } else {
    // try to find colon (:)
    std::string credentials = con.substr(0, pos);
    std::string::size_type colpos = credentials.find(':');
    if (colpos != std::string::npos) {
      // found colon, extract user and passwd
      user = credentials.substr(0, colpos);
      passwd = credentials.substr(colpos + 1, pos);
    } else {
      // only user name given
      user = credentials.substr(0, pos);
    }
  }
  // get connection part
  con = con.substr(pos + 1);
  pos = con.find('/');
  std::string host = con.substr(0, pos);
  std::string db = con.substr(pos + 1);

  // get driver
  pos = db.find('(');
  if (pos != std::string::npos) {
    driver = db.substr(pos+1);
    db = db.substr(0, pos);
    db = trim(db);
    pos = driver.find(')');
    driver = driver.substr(0, pos);
  } else {
    driver = "SQL Server";
  }

  SQLRETURN ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &odbc_);
  if (ret != SQL_SUCCESS) {
    SQLFreeHandle(SQL_HANDLE_ENV, odbc_);
    throw_error(ret, SQL_HANDLE_ENV, odbc_, "mssql", "couldn't get odbc handle");
  }

  ret = SQLSetEnvAttr(odbc_, SQL_ATTR_ODBC_VERSION,(SQLPOINTER)SQL_OV_ODBC3, 0);
  if (ret != SQL_SUCCESS) {
    SQLFreeHandle(SQL_HANDLE_ENV, odbc_);
    throw_error(ret, SQL_HANDLE_ENV, odbc_, "mssql", "couldn't set odbc driver version");
  }

  ret = SQLAllocHandle(SQL_HANDLE_DBC, odbc_, &connection_);
  if (ret != SQL_SUCCESS) {
    SQLFreeHandle(SQL_HANDLE_ENV, odbc_);
    throw_error(ret, SQL_HANDLE_DBC, connection_, "mssql", "couldn't get connection handle");
  }

  SQLSetConnectAttr(connection_, SQL_LOGIN_TIMEOUT, (SQLPOINTER *)5, 0);

  std::string dns("DRIVER={" + driver + "};SERVER=" + host + "\\" + db + ";DATABASE=test;UID=" + user + ";PWD=sascha;");

  SQLCHAR retconstring[1024];
  ret = SQLDriverConnect(connection_, 0, (SQLCHAR*)dns.c_str(), SQL_NTS, retconstring, 1024, NULL,SQL_DRIVER_NOPROMPT);

  throw_error(ret, SQL_HANDLE_DBC, connection_, "mssql", "error on connect");

  is_open_ = true;
}
Esempio n. 30
0
void remove_catalogs(void)
{	
	SQLRETURN	retcode;
	void        remove_update_queue_tables(void);

    sql_db_connection = (TM_CONNECTION *)malloc(sizeof(TM_CONNECTION));

	// Allocate an environment handle
	retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(sql_db_connection->henv));

	if( retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO )
	{
		/* Set the ODBC version environment attribute */
		retcode = SQLSetEnvAttr(sql_db_connection->henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);

		if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
		{
			/* Allocate a connection handle */
			retcode = SQLAllocHandle(SQL_HANDLE_DBC, sql_db_connection->henv, &(sql_db_connection->hdbc));

			if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
			{
				/* Connect to data source */
				retcode = SQLConnect(sql_db_connection->hdbc, (SQLCHAR*) odbc_dsn, SQL_NTS,
					(SQLCHAR*) username, SQL_NTS,
					(SQLCHAR*) password, SQL_NTS);

				if( retcode  == SQL_ERROR )
				{
					SQLFreeHandle(SQL_HANDLE_DBC, sql_db_connection->hdbc);
					SQLFreeHandle(SQL_HANDLE_ENV, sql_db_connection->henv);
        			printf ("Error: unable to connect to SQL Server\n");
       				puts ("Ensure that the DBMS is running and that your ODBC DSN settings are correct.");
        			exit (EXIT_FAILURE);
				}
			}
			else
			{
				SQLFreeHandle(SQL_HANDLE_DBC, sql_db_connection->hdbc);
				SQLFreeHandle(SQL_HANDLE_ENV, sql_db_connection->henv);
        		printf ("Error: unable to connect to SQL Server\n");
       			puts ("Ensure that the DBMS is running and that your ODBC DSN settings are correct.");
        		exit (EXIT_FAILURE);
			}
		}
	}
	else
	{
		SQLFreeHandle(SQL_HANDLE_ENV, sql_db_connection->henv);
        printf ("Error: unable to connect to SQL Server\n");
       	puts ("Ensure that the DBMS is running and that your ODBC DSN settings are correct.");
        exit (EXIT_FAILURE);
	}

	printf ("\n\nConnected to SQL Server.\n\n");

	puts ("Removing Vigilert's catalogs will delete your Vigilert triggers,");
	puts ("triggersets, data sources, pending mail, pending OS commands, and pending notices.");
	printf ("Are you sure you want to do this (Y/N)? ");
	fgets (yesno, sizeof (yesno), stdin);
    yesno[strlen (yesno) - 1] = '\0';  // Remove trailing \n.

	if (stricmp (yesno, "y") != 0)
	{
		exit (EXIT_SUCCESS);
	}

	puts ("");

	remove_update_queue_tables();

	exec_sql_stmt("drop table vl_DataSrc");
	puts ("vl_DataSrc");

	exec_sql_stmt("drop table vl_DataSrcAtb"),
	puts ("vl_datasrcatb");

	exec_sql_stmt("drop table vl_IDTable");
	puts ("vl_idtable");

	exec_sql_stmt("drop table vl_TriggerSet");
	puts ("vl_TriggerSet");

	exec_sql_stmt("drop table vl_Trigger");
	puts ("vl_Trigger");

	exec_sql_stmt("drop table vl_TrigDataSrcReln");
	puts ("vl_TrigDataSrcReln");

	exec_sql_stmt("drop table vl_mail");
	puts ("vl_mail");

	exec_sql_stmt("drop table vl_osexec");
	puts ("vl_osexec");

	exec_sql_stmt("drop table vl_notice");
	puts ("vl_notice");

	exec_sql_stmt("drop table vl_DataSrcMtb");
	puts ("vl_DataSrcMtb");

	exec_sql_stmt("drop table vl_null_tbl");
	puts ("vl_null_tbl");

	exec_sql_stmt("drop table vl_mon_watch");
	puts ("vl_mon_watch");

	exec_sql_stmt("drop table vl_mon_update");
	puts ("vl_mon_update");

	exec_sql_stmt("drop table vl_ext_fcn_tbl");
	puts ("vl_ext_fcn_tbl");
}