Programming/PHP2015. 6. 10. 17:01

프로시져 내부에 SELECT 구문이 여러개 있어서 output row을 여러개 받아야 할 경우 예시


1. 프로시져 ( MSSQL 기준 작성함...)

CREATE PROCEDURE [dbo].[spTest]
AS
BEGIN
SELECT TOP 2 log_id FROM testLog ;
SELECT TOP 2 log_id FROM testLog ;
END


2. PHP 코드

<?php
  $stmt = $conn->prepare("exec spTest");
  $stmt->execute();
  $results = array();
  do {
    $results[] = $stmt->fetchAll();
  }while ($stmt->nextRowset());
  print_r($results);
?>


3. 결과셋

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [log_id] => 1
                    [0] => 1
                )
           [1] => Array
                (
                    [log_id] => 2
                    [0] => 2
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [log_id] => 1
                    [0] => 1
                )
            [1] => Array
                (
                    [log_id] => 2
                    [0] => 2
                )
        )
)


※ 위에 예시는 거의 사용할 일이 크게 없었으며....

   아래 참고사이트에 보면 나오듯이... 게시물에 total값 별도로 output 이나 리턴 받고.. 

   요청하는 범위에 게시물의 row 수를 받을때 사용하는 일이 더 많은 듯하다....


참고사이트 

http://trentrichardson.com/2011/08/10/making-sense-of-stored-procedures-with-php-pdo-and-sqlsrv/

http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php/

Posted by 시니^^
Programming/PHP2014. 5. 22. 16:49
SQL Server Native를 설치해서 사용했지만 아래 링크처럼 한글 및 기타 몇가지 문제가 있는듯하여서
FreeTDS로 사용하기로 했다..

Linux uninxODBC SQL Server Native Client 11.0 한글문제 - http://www.opens.kr/35


※ SQL Server Native bind 처리도 문제있는 듯하다 ㅠㅠ

http://hbs.pe.kr/50113950707

http://connect.microsoft.com/SQLServer/feedback/details/521409/odbc-client-mssql-does-not-work-with-bound-parameters-in-subquery

※ FreeTDS bindValue 쓰면 되는 것 처럼 보이는 데 

    실제 SQL Server Profiler 해보면 prepare statement bind 안되어서 들어온다ㅠㅠ;;


PHP5.3/5.4/5.5 Yum 설치 - http://www.opens.kr/33  으로 PHP 설치 사용했다면

그냥 yum install php55w-mssql 만 설치하면 자동으로 설치가 다 된다.


1) 설치

$ yum install php55w-mssql ================================================================================== Package Arch Version Repository Size ================================================================================== Installing: php55w-mssql x86_64 5.5.12-1.w6 Installing for dependencies: freetds x86_64 0.91-2.el6 php55w-pdo x86_64 5.5.12-1.w6 unixODBC x86_64 2.2.14-12.el6_3 Transaction Summary ================================================================================== Install 4 Package(s)


2) 접속 테스트 아래 링크에 tsql / isql 이용해서 하면된다.

리눅스 unixODBC FreeTDS 설치 (MSSQL) - http://www.opens.kr/36


3) 글로벌 설정

$ vi /etc/freetds.conf
------------------------
[global]
tds version = 8.0
client charset = UTF-8
text size = 64512
timeout = 10
connect timeout = 10
------------------------

※ TDS protocol 버전정보와 자세한 옵션 정보는 아래 freetds 사이트 가이드 참조하면 된다.

http://www.freetds.org/userguide/choosingtdsprotocol.htm

http://www.freetds.org/userguide/


4) PHP PDO에서 접속예시 

$dsn = 'dblib:host=192.168.0.0;dbname=DBNAME';
$user = "user_id";
$password = "user_password";

try {
    $dbh = new PDO($dsn, $user, $password); 
} catch (PDOException $e) {
    echo $e->getMessage();
}
$sQuery = "select * from sysobjects where xtype = 'U'";
$sth =  $dbh->prepare($sQuery);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($result);



Posted by 시니^^
DB/NoSQL/Mssql2014. 5. 22. 16:16

리눅스에서 MSSQL 서버 접근할려고 MS에서 제공해주는 라이브러리 설치했지만 이래저래

문제가 많아서 FreeTDS를 사용하기로 결정했다.


리눅스 SQL Server(MSSQL) ODBC 설치 - http://www.opens.kr/34

Linux uninxODBC SQL Server Native Client 11.0 한글문제 - http://www.opens.kr/35


FreeTDS Yum 간단 설치 방법


1) 저장소 등록 ( 다른곳을 이용해도 무관함 )

$ rpm -Uvh http://mirror.webtatic.com/yum/el6/latest.rpm


2) Yum 설치

$ yum install freetds unixODBC

=================================================================================================================

 Package                               Arch                            Version                                  Repository                         Size

=================================================================================================================

Installing:

 freetds                               x86_64                          0.91-2.el6                               webtatic                          567 k

 unixODBC                              x86_64                          2.2.14-12.el6_3                          base                              378 k

Installing for dependencies:

 libtool-ltdl                          x86_64                          2.2.6-15.5.el6                           base                               44 k


Transaction Summary

=================================================================================================================

Install       3 Package(s)


3) tsql을 이용한 접속테스트

$ tsql -H 192.168.0.0 -p 1433 -U username -P userpassword

참조 가이드 : http://www.freetds.org/userguide/confirminstall.htm


4) ODBC에 FreeTDS등록

vi /etc/odbcinst.ini 

----------------------------------

[FreeTDS]

Description = FreeTDS Driver

Driver = /usr/lib64/libtdsodbc.so.0

Setup = /usr/lib64/libtdsS.so.2

FileUsage = 1

CPTimeout = 5

CRReuse = 5

----------------------------------


5) isql을 이용한 접속 테스트

vi /etc/odbc.ini

----------------------------------

[MSSQLTEST]

driver=FreeTDS

server=192.168.0.0

port=1433

database=DBNAME

client_charset = UTF-8

tds_version = 8.0

----------------------------------


$ isql -v MSSQLTEST username userpassword

+---------------------------------------+

| Connected!                

|                              

| sql-statement            

| help [tablename]           

| quit                          

|                                     

+---------------------------------------+



※ ODBC 정보확인은 아래와 같이

$ odbcinst -j

unixODBC 2.2.14

DRIVERS............: /etc/odbcinst.ini

SYSTEM DATA SOURCES: /etc/odbc.ini

FILE DATA SOURCES..: /etc/ODBCDataSources

USER DATA SOURCES..: /root/.odbc.ini

SQLULEN Size.......: 8

SQLLEN Size........: 8

SQLSETPOSIROW Size.: 8


※ PHP PDO나 타 개발언어에서 사용시

    $ vi /etc/freetds.conf의 [global]에 기본 tds_version 버젼과 client_charset  지정해주는 게 좋을 듯하다.

-------------------------------

[global]

tds version = 8.0

client charset = UTF-8

text size = 64512

-------------------------------

※ 리눅스 PHP PDO dblib FreeTDS 사용 (MSSQL) - http://www.opens.kr/37




Posted by 시니^^
Programming/PHP2014. 5. 22. 12:48

MSSQL에서 UTF-8 텍스트를 데이터를 넣을때 NVARCHAR타입으로 해서


INSERT INTO table ( text ) value ( N'한글테스트' ) 이런식으러 넣는 다


그런데 리눅스에서 PDO에서 uninxODBC SQL Server Native Client 11.0 넣으면 제대로 들어가지 않고 깨진다


그래서 아래 처럼  UTF-16LE로 변환해서 hexcode로 넣으니까 잘된다.. 

$sName = iconv('utf-8','UTF-16LE',$sName);
$sName = bin2hex($sName);
$sQuery = "INSERT INTO table (name) VALUES (  0x{$sName} )";

그리고 값을 가져올때 가끔식 일부데이터는 문제가 또 발생한다 ㅠㅠ


그래서 CAST 로 한번 변환해주니까 잘된다..

참가로 NVARCHAR(MAX)로 하니까 글이 전혀 나오지 않아서 그냥 NTEXT로 꽁수를 부렸다..

$sQuery = "SELECT CAST(name AS NTEXT) AS name FROM table ";

그리고 참고로 PHP5.3.3 버전에서 PDO ODBC nvarchar(max)데이터 어느 정도 이상되면 깨지는 현상이 나오는듯하다.


그래서 PHP5.5.12 / PHP5.4.28 / PHP5.3.28에서는 CAST해서 하면 큰 문제가 없다.


아무튼 Linux uninxODBC SQL Server Native Client 11.0 이래저래 문제가 좀 있는듯하다.


그래서 개인적으로는 Linux에서 MSSQL 연결하는 경우 SQL Server Native Client 보다는 FreeTDS를 사용을 권하고 싶다.


Posted by 시니^^
DB/NoSQL/Mssql2014. 5. 21. 18:53

 

MS사이트 : http://www.microsoft.com/en-us/download/details.aspx?id=28160


1) 파일다운로드 ( centos6 64bit의 경우 Linux6을 선택 다운로드 안될때 MS사이트 URL확인 )

$ wget http://download.microsoft.com/download/6/A/B/6AB27E13-46AE-4CE9-AFFD-406367CADC1D/Linux6/sqlncli-11.0.1790.0.tar.gz

 

2) 압축풀고 build_dm실행

$ tar xvfz sqlncli-11.0.1790.0.tar.gz
$ cd sqlncli-11.0.1790.0

$ ./build_dm.sh //실행후 나오는 디렉토리 기준으로 make 실행
Enter 'YES' to have this script continue: YES
Verifying processor and operating system ................................... OK
Verifying wget is installed ................................................ OK
Verifying tar is installed ................................................. OK
Verifying make is installed ................................................ OK
Downloading unixODBC 2.3.0 DriverManager ................................... OK
Unpacking unixODBC 2.3.0 DriverManager ..................................... OK
Configuring unixODBC 2.3.0 DriverManager ................................... OK
Building unixODBC 2.3.0 DriverManager
...................................... OK
Build of the unixODBC 2.3.0 DriverManager complete.
Run the command 'cd /tmp/unixODBC.32631.28583.22057/unixODBC-2.3.0; make install' to install the driver manager.
PLEASE NOTE THAT THIS WILL POTENTIALLY INSTALL THE NEW DRIVER MANAGER OVER ANY
EXISTING UNIXODBC DRIVER MANAGER.  IF YOU HAVE ANOTHER COPY OF UNIXODBC INSTALLED,
THIS MAY POTENTIALLY OVERWRITE THAT COPY.

 

3) 위에 tmp 경로에서 make install 실행

$ cd /tmp/unixODBC.32631.28583.22057/unixODBC-2.3.0
$ make install

touch /etc/odbcinst.ini
touch /etc/odbc.ini
mkdir -p /etc/ODBCDataSources
/usr/bin/odbc_config --header > /usr/include/unixodbc_conf.h
make[2]: Leaving directory `/tmp/unixODBC.32631.28583.22057/unixODBC-2.3.0'
make[1]: Leaving directory `/tmp/unixODBC.32631.28583.22057/unixODBC-2.3.0'

 

4) install 실행
$ cd /root/sqlncli-11.0.1790.0
$ ./install.sh verify

Microsoft SQL Server ODBC Driver V1.0 for Linux Installation Script
Copyright Microsoft Corp.
Starting install for Microsoft SQL Server ODBC Driver V1.0 for Linux
Checking for 64 bit Linux compatible OS ..................................... OK
Checking required libs are installed ........................................ OK
unixODBC utilities (odbc_config and odbcinst) installed ..................... OK
unixODBC Driver Manager version 2.3.0 installed ............................. OK
unixODBC Driver Manager configuration correct .............................. OK*
Microsoft SQL Server ODBC Driver V1.0 for Linux already installed .... NOT FOUND
Install log created at /tmp/sqlncli.18759.30552.14202/install.log.
One or more steps may have an *. See README for more information regarding
these steps.

$ ./install.sh install
Enter YES to accept the license or anything else to terminate the installation: YES
Checking for 64 bit Linux compatible OS ..................................... OK
Checking required libs are installed ........................................ OK
unixODBC utilities (odbc_config and odbcinst) installed ..................... OK
unixODBC Driver Manager version 2.3.0 installed ............................. OK
unixODBC Driver Manager configuration correct .............................. OK*
Microsoft SQL Server ODBC Driver V1.0 for Linux already installed .... NOT FOUND
Microsoft SQL Server ODBC Driver V1.0 for Linux files copied ................ OK
Symbolic links for bcp and sqlcmd created ................................... OK
Microsoft SQL Server ODBC Driver V1.0 for Linux registered ........... INSTALLED
Install log created at /tmp/sqlncli.27629.13209.11572/install.log.
One or more steps may have an *. See README for more information regarding
these steps.

$ vi /etc/odbcinst.ini //odbc추가확인
[SQL Server Native Client 11.0]
Description=Microsoft SQL Server ODBC Driver V1.0 for Linux
Driver=/opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0
Threading=1
UsageCount=1

 

5) 최종 설치 결과확인

$ ./install.sh verify

Microsoft SQL Server ODBC Driver V1.0 for Linux Installation Script
Copyright Microsoft Corp.

Starting install for Microsoft SQL Server ODBC Driver V1.0 for Linux

Checking for 64 bit Linux compatible OS ..................................... OK
Checking required libs are installed ........................................ OK
unixODBC utilities (odbc_config and odbcinst) installed ..................... OK
unixODBC Driver Manager version 2.3.0 installed ............................. OK
unixODBC Driver Manager configuration correct .............................. OK*
Microsoft SQL Server ODBC Driver V1.0 for Linux already installed .... INSTALLED

 

6) isql 이용한 접속테스트

$ vi /etc/odbc.ini

-------------------------

[MSSQLTEST]
driver=SQL Server Native Client 11.0
server=192.168.0.0
port=1433
database=DBNAME

-------------------------

$ isql -v MSSQLTEST userid userpassword

+---------------------------------------+
| Connected!                           
|                                       
| sql-statement                         
| help [tablename]                      
| quit                                  
|                                       
+---------------------------------------+

 

※ PHP에는 PDO ODBC에는 odbcinst.ini에 등록된 이름으로 odbc.ini처럼 지정해주면됨
 => odbc:DRIVER=SQL Server Native Client 11.0;Server=192.168.0.0;
port=1433;database=dbname;

 

※ C컴파일에러시 gcc설치할것!!
view /tmp/unixODBC.19411.11370.8462/build_dm.log
yum install gcc


※ ODBC 정보확인은 아래와 같이

$ odbcinst -j

unixODBC 2.2.14

DRIVERS............: /etc/odbcinst.ini

SYSTEM DATA SOURCES: /etc/odbc.ini

FILE DATA SOURCES..: /etc/ODBCDataSources

USER DATA SOURCES..: /root/.odbc.ini

SQLULEN Size.......: 8

SQLLEN Size........: 8

SQLSETPOSIROW Size.: 8

 

Posted by 시니^^
Programming/JAVA2014. 4. 9. 22:16

1. Microsoft에서Microsoft SQL Server JDBC 다운로드

1) SQL Server JDBC 드라이버 4.0 (SQL Server 2000 버전 지원 안한다고함) 

URL : http://www.microsoft.com/ko-kr/download/details.aspx?id=11774


2) SQL Server JDBC 드라이버 3.0

URL : http://www.microsoft.com/ko-kr/download/details.aspx?id=21599



2. sqljdbc.jar와 sqljdbc4.jar 차이점

http://msdn.microsoft.com/ko-kr/library/ms378422.aspx

 sqljdbc.jar

 라이브러리는 JDBC 3.0을 지원합니다. 

 라이브러리에는 JRE(Java Runtime Environment) 버전 5.0이 필요합니다.

 JRE 6.0에서 sqljdbc.jar을 사용하면 데이터베이스에 연결할 때 예외가 발생합니다.

 JDBC 드라이버는 JRE 1.4를 지원하지 않습니다.

 JDBC 드라이버를 사용하려면 JRE 1.4를 JRE 5.0 또는 JRE 6.0으로 업그레이드해야 합니다. 

 응용 프로그램이 JDK 5.0 이상과 호환되지 않아 다시 컴파일해야 하는 경우도 있습니다. 

 자세한 내용은 Sun Microsystems 웹 사이트의 설명서를 참조하십시오.

 sqljdbc4.jar

 라이브러리는 JDBC 4.0을 지원합니다. 

 이 라이브러리에는 sqljdbc.jar의 모든 기능과 함께 새로운 JDBC 4.0 메서드가 포함되어 있습니다.

 클래스 라이브러리를 사용하려면 JRE(Java Runtime Environment) 버전 6.0이 필요합니다.

 JRE 1.4 또는 5.0에서 sqljdbc4.jar을 사용하면 예외가 발생합니다.

 응용 프로그램을 JRE 6.0에서 실행해야 하는 경우에는 JDBC 4.0 기능을 사용하지 않더라도  sqljdbc4.jar을 사용하십시오.

JDBC 드라이버는 모든 주요 Sun 호환 Java 가상 컴퓨터에서 작동하고 지원되도록 설계되어 있지만 테스트는 Sun JRE 5.0 이상에서 수행됩니다


3. cmd에서 mvn install

C:\>mvn install:install-file -Dfile=sqljdbc.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar

C:\>mvn install:install-file -Dfile=sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar


4. pom.xml에 등록

        <!-- MSSQL -->

        <dependency>

            <groupId>com.microsoft.sqlserver</groupId>

            <artifactId>sqljdbc4</artifactId>

            <version>4.0</version>

        </dependency>

Posted by 시니^^