Как создать Синоним Sql или “Псевдоним” для Имени базы данных?

У меня была такая же проблема в проекте, я искал PHP Class to Read Excel as PHP Array. Мне повезло, что я нашел 'SimpleXLSX' Class. Он отлично справляется с данными Excel, но ... но ... ох! но .... :( Я понял, что есть некоторая проблема с полем Date Reading From Excel. В значениях excel смотрелось отлично, но когда мы пытались их импортировать, значения даты менялись. Некоторое время мы получали правильные значения раз в несколько раз и несколько раз поплавковым значениям. Мы искали решение

ПОЧЕМУ ЭТО ПРОИСХОДИТ, ПОЧЕМУ PHP НЕ ПОЛУЧИТ ПРАВИЛЬНУЮ ДАТА ИЗ EXCEL

blockquote>

'Затем после многократного поиска мы обнаружили причину:

@Source: чтение xls date в php

В соответствии с форматом excel 41397 is 2013-05-03 Excel хранит даты и время как число, представляющее количество дней с 1900 года по январь-0, а также дробную часть 24-часового дня: ddddd.tttttt. Это называется последовательной датой или последовательной датой

blockquote>

@Source: Преобразование даты Excel с использованием PHP Excel

Преобразование даты Excel в дату Unix и последующее преобразование Unix Дата в PHP Дата

blockquote>

Итак, я м ade немного вспомогательного класса для чтения Excel Date для использования в PHP. Я надеюсь, что это поможет кому-то и уменьшит внимание и усилия.

Вот мой код для Read Excel as PHP Array() и Parse Excel Date as PHP Date

Для начинающих:

  1. Загрузить SimpleXLSX.php из приведенного примера кода
  2. Преобразование данных excel (поле / значение) в PHP array ()
  3. Преобразование даты excel в PHP
  4. Теперь .. Да! Данные Excel готовы в качестве массива PHP для перехода в таблицу MySQL ...

Вот код PHP:

blockquote>
 Array
          (
              [ID] => 536
              [Consumer_Date] => -No-Data-
              [Delivery_Date] => 42317
              [Date_of_Dispatch] => 42315
              [Gift_Date_Created] => -No-Data-
              [Active_Date] => 10/31/2015 12:00:00 AM
              [Approved_Date] => 42105.431574074
          )
      [1] => Array
          (
              [ID] => 537
              [Consumer_Date] => -No-Data-
              [Delivery_Date] => -No-Data-
              [Date_of_Dispatch] => 42315
              [Gift_Date_Created] => -No-Data-
              [Active_Date] => 10/23/2015 12:00:00 AM
              [Approved_Date] => 42074.683958333
          )
  )

*/

/* ----------------- */
/* Excel_Date_Parser.php */
/* ----------------- */


// Numbers of days between January 1, 1900 and 1970 (including 19 leap years)
define("MIN_DATES_DIFF", 25569);

// Numbers of second in a day:
define("SEC_IN_DAY", 86400);

/** Set default timezone (will throw a notice otherwise) */
date_default_timezone_set('Asia/Kolkata');

/**
 * Class Excel_Date_Parser
 *
 * SetDateString($excel_date_value) : send excel date column value
 * GetDateString(): get your php date in Y-m-d format (MySQL)
 */
class Excel_Date_Parser
{

  /**
   * Send Excel Date String Value Here
   * @param [type] $date_from_excel [description]
   * @return instance Excel_Date_Parser
   */
  public function SetDateString($date_from_excel) {
    $this->date_from_excel = $date_from_excel;
    return $this;
  }

  /**
   * Set Date Format Here, default is "Y-m-d"
   * @param string $set_format_date [description]
   */
  public function SetDateFormat($set_format_date = "Y-m-d") {
    $this->set_format_date = $set_format_date;
  }

  /**
   * Get what format is set
   */
  public function GetDateFormat() {
    return $this->set_format_date;
  }

  /**
   * Return PHP date according to Set Format from Excel Date
   * @return string php date
   */
  public function GetDateString() {

    // if value is valid date string
    if (strtotime($this->date_from_excel)) {

      /**
       * Excel stores dates and times as a number representing the number of days since 1900-Jan-0,
       * plus a fractional portion of a 24 hour day: ddddd.tttttt.
       * This is called a serial date, or serial date-time.
       *
       * @source: https://stackoverflow.com/questions/17808750/reading-xls-date-in-php
       */
      if (is_float($this->date_from_excel)) {

        // date format 2015-25-12
        $this->SetDateFormat("Y-d-m");
        $this->date_from_excel = date($this->GetDateFormat() , (mktime(0, 0, -1, 1, $this->date_from_excel, 1900)));
      } 
      else {

        // date format 2015-12-25
        $this->SetDateFormat();

        // return converted date string in php format date format 2015-12-25
        $this->date_from_excel = date($this->GetDateFormat() , strtotime($this->date_from_excel));
      }
    }

    /**
     * Excel stores dates and times as a number representing the number of days since 1900-Jan-0,
     * plus a fractional portion of a 24 hour day: ddddd.tttttt .
     * This is called a serial date, or serial date-time.
     *
     * According to excel format 41397 is 2013-05-03
     * @source: https://stackoverflow.com/questions/17808750/reading-xls-date-in-php
     */
    else if (is_integer($this->date_from_excel)) {
      $this->SetDateFormat();
      $this->date_from_excel = gmdate($this->GetDateFormat() , (($this->date_from_excel - MIN_DATES_DIFF) * SEC_IN_DAY));
    }

    // return real value
    else {
      $this->date_from_excel = $this->date_from_excel;
    }

    // return date
    return $this->date_from_excel;
  }
}


/* ----------------- */
/* Excel_Reader.php */
/* ----------------- */

/* Show errors */
error_reporting(1);

/* display error */
ini_set('display_errors', 1);

/**
* Using class SimpleXLSX 
* 
* Big Thanks!!!! to Sergey Shuchkin, Who made Excel Reader Class
* 
* This class can be used to parse and retrieve data from Excel XLS spreadsheet files.
* It can parse a given Excel XLS file by extracting its contents files and parsing the 
* contained XML spreadsheet file.
*
* The class provides functions to retrieve data for the spreadsheet worksheets, rows and cells.
*
* @link: http://www.phpclasses.org/package/6279-PHP-Parse-and-retrieve-data-from-Excel-XLS-files.html
* @author: Sergey Shuchkin
* @download: http://www.phpclasses.org/browse/download/zip/package/6279/name/simple-xlsx-2013-10-13.zip
*/
require_once 'SimpleXLSX.php';


/* Adding my class Excel_Date_Parser */
require_once 'Excel_Date_Parser.php';


/**
 * [toPhpDate description]
 * @param [type] $array [description]
 */
function toPhpDate($array) {

  // create class object
  $ed = new Excel_Date_Parser();

  // parse array and set
  $array['Consumer_Date'] = $ed->SetDateString($array['Consumer_Date'])->GetDateString();
  $array['Delivery_Date'] = $ed->SetDateString($array['Delivery_Date'])->GetDateString();
  $array['Date_of_Dispatch'] = $ed->SetDateString($array['Date_of_Dispatch'])->GetDateString();
  $array['Gift_Date_Created'] = $ed->SetDateString($array['Gift_Date_Created'])->GetDateString();
  $array['Active_Date'] = $ed->SetDateString($array['Active_Date'])->GetDateString();
  $array['Approved_Date'] = $ed->SetDateString($array['Approved_Date'])->GetDateString();

  // return php array
  return $array;
}

// make xls object
$xlsx = new SimpleXLSX('Sony_RedemptionFormat 8-Dec-15.xlsx');

// get excel data as array
$Excel_Array_Data = $xlsx->rows();

// Get Column Name
$Excel_Column = $Excel_Array_Data[0];

// Remove Column Name From Array
unset($Excel_Array_Data[0]);

// Rest Data is Excel Data without Column
$Excel_Data = $Excel_Array_Data;

// Combine array for inserting in database
foreach ($Excel_Array_Data as $key => $Excel_Data) {
  $insert_data[] = array_combine($Excel_Column, $Excel_Data);
}

// show array data
echo "
", print_r($insert_data, true);

// update array excel date
$insert_data = array_map('toPhpDate', $insert_data);

// show array data after update date
echo "
", print_r($insert_data, true);

Надежда этот код поможет кому-то. Я боролся с такой же проблемой. Поэтому я сделал этот маленький скрипт, чтобы сэкономить время.

Счастливый PHPING !!!! :)

blockquote>

27
задан Cade Roux 23 January 2009 в 20:13
поделиться

2 ответа

используйте 3 нотации части и псевдоним до таблицы, пример

select * from tempdb.dbo.sysobjects a
join master.dbo.sysobjects b on a.id = b.id
4
ответ дан SQLMenace 15 October 2019 в 06:39
поделиться

Я сделал что-то подобное этому использованию другого файла конфигурации.

новый файл конфигурации отображается, Ваше родовое название ко всей информации должно было соединиться с той базой данных (имя дб, имя пользователя, пароль, и т.д.), и затем Ваша функция соединения берет Ваше родовое название в качестве аргумента.

db.config:

DEV_DB_NAME = db20080101
DEV_DB_USER = dev_user
DEV_DB_PASS = dev_pass
TEST_DB_NAME = db20070101
TEST_DB_USER = test_user
TEST_DB_PASS = test_pass

код соединения:

db_connection get_connection(string prefix) {
    db_connection db_conn = new db_connection;
    string db_name = get_config_value(config_path, prefix + "_DB_NAME");
    string db_user = get_config_value(config_path, prefix + "_DB_USER");
    string db_pass = get_config_value(config_path, prefix + "_DB_PASS");

    db_conn.connect(db_name, db_user, db_pass);

    return db_conn;
}

Тогда Вы просто называете get_connection () с Вашим псевдонимом дб как аргумент.

1
ответ дан Ryan Ahearn 15 October 2019 в 06:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: