查找

文章
· 五月 6, 2024 阅读大约需 4 分钟

LinuxでJDBC接続を行う方法

前回、LinuxでODBC接続を行う方法 をご紹介しました。

今回は、LinuxでJDBC接続を行う方法 をご紹介します。作業は、root ユーザ で行います。

はじめに、Linuxのバージョンを確認します。

$ cat /etc/os-release
NAME="Red Hat Enterprise Linux"
VERSION="9.4 (Plow)"
:


1. yumパッケージのアップデートを行います

$ su -
Password:
Last login: Tue May  7 01:04:35 UTC 2024 on pts/0
# yum update


2. Java をインストールします

今回は、Adoptium OpenJDK の Version 8 - LTS を使用してテストします。
※ *.tar.gz は、/usr/java 以下にダウンロードします。

# cd /usr/java
# ls
OpenJDK8U-jdk_x64_linux_hotspot_8u412b08.tar.gz
# tar zxvf OpenJDK8U-jdk_x64_linux_hotspot_8u412b08.tar.gz
:
# ls
jdk8u412-b08  OpenJDK8U-jdk_x64_linux_hotspot_8u412b08.tar.gz


3. IRISクライアントをインストールします

Linuxのバージョンにあったインストーラを使用してください。

# cd IRIS-2024.1.0.262.0-lnxrh9x64

# ./irisinstall_client
Your system type is 'Red Hat Enterprise Linux 9 (x64)'.
Enter a destination directory for client components.
Directory: /intersystems/iris
Directory '/intersystems/iris' does not exist.
Do you want to create it <Yes>?
Installation completed successfully

※JDBC ドライバのみダウンロードしたい場合は、こちら から行えます(JDBC のリンクをクリック)。


4. 環境変数の設定を行います
 (JAVA_HOME、PATH、LD_LIBRARY_PATH、CLASSPATH)

 JAVA_HOME       --- JDKがインストールされているディレクトリ
 PATH            --- $JAVA_HOME/bin + <IRISクライアントインストールディレクトリ>/bin
 LD_LIBRARY_PATH --- $JAVA_HOME/lib 
 CLASSPATH       --- <IRISクライアントインストールディレクトリ>/dev/java/lib/1.8/intersystems-jdbc-*.*.*.jar

 

# export JAVA_HOME=/usr/java/jdk8u412-b08
# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$JAVA_HOME/lib
# export PATH=$PATH:$JAVA_HOME/bin

# export PATH=$PATH:/intersystems/iris/bin
# ls /intersystems/iris/dev/java/lib/1.8
intersystems-binding-3.2.2.jar         intersystems-messaging-1.3.0.jar
intersystems-cloudclient-1.2.2.jar     intersystems-persister-1.0.0.jar
intersystems-cloud-manager-1.6.15.jar  intersystems-rgateway-3.2.0.jar
intersystems-enslib-jms-3.2.0.jar      intersystems-uima-1.0.0.jar
intersystems-jdbc-3.8.4.jar            intersystems-utils-4.1.5.jar
intersystems-loader-1.2.3.jar          intersystems-xep-3.2.1.jar
# export CLASSPATH=$CLASSPATH:/intersystems/iris/dev/java/lib/1.8/intersystems-jdbc-3.8.4.jar

※すべてのユーザで使用できるよう、環境変数を永続化させる場合は、/etc/profile に追加します。

確認します。

$ which java
/usr/java/jdk8u412-b08/bin/java
$ which javac
/usr/java/jdk8u412-b08/bin/javac
$ java -version
openjdk version "1.8.0_412"
OpenJDK Runtime Environment (Temurin)(build 1.8.0_412-b08)
OpenJDK 64-Bit Server VM (Temurin)(build 25.412-b08, mixed mode)


5. IRISへのJDBC接続確認をします

こちらのサンプルでは、DriverManager クラスを使用した接続テスト を行います。
※現在のネームスペース内の全てのテーブル (およびビュー) に関する INFORMATION.SCHEMA.TABLES の情報をSelectするサンプルです。

/// JDBCSample.java
import java.sql.*;

public class JDBCSample {
    public static void main(String[] str) throws Exception {
        String url = "jdbc:IRIS://***.***.***.***:1972/USER/";

        java.util.Properties prop = new java.util.Properties();
        prop.put("user", "_System");
        prop.put("password", "SYS");
        // Replace _SYSTEM and SYS with a username and password on your system
        Connection connection = DriverManager.getConnection(url,prop);

        Statement statement = connection.createStatement();
        String query = "SELECT top 5 TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES";
        ResultSet resultSet = statement.executeQuery(query);
        System.out.println("Printing out contents of SELECT query: ");

        while (resultSet.next()) {
            System.out.println(resultSet.getString(1) + ", " + resultSet.getString(2) + ", " + resultSet.getString(3));
        }

        resultSet.close();
        statement.close();
        connection.close();
    } 
}

コンパイル&実行します。

# javac JDBCSample.java
# java JDBCSample
Printing out contents of SELECT query:
%CSP_Util, CSPLogEvent, SYSTEM TABLE
%CSP_Util, Performance, SYSTEM TABLE
%Calendar, Hijri, SYSTEM TABLE
%Compiler_Informix, ConversionRule, SYSTEM TABLE
%Compiler_Informix, ImportedObject, SYSTEM TABLE


IRISDataSource を使用する場合は以下のようになります。

import com.intersystems.jdbc.IRISDataSource;
import java.sql.*;

public class JDBCSample {
    public static void main(String[] str) throws Exception {
        IRISDataSource ds = new IRISDataSource();
        ds.setURL("jdbc:IRIS://***.***.***.***:1972/User");
        ds.setUser("_system");
        ds.setPassword("SYS");
        Connection connection = ds.getConnection();
        // 以下、DriverManager のサンプルと同じ


詳細は以下のドキュメントをご覧ください。
JDBC ドライバの使用法
InterSystems SQL の基礎 : JDBC とインターシステムズのデータベース

讨论 (0)0
登录或注册以继续
讨论 (4)2
登录或注册以继续
公告
· 五月 6, 2024

Tercer concurso de artículos técnicos en español

¡Hola Comunidad!

Llega un nuevo reto para vosotros ¡El tercer concurso de redacción de artículos técnicos de InterSystems en español ya está aquí!

🏆 3º Concurso de Artículos Técnicos en español 🏆
Descripción del concurso: Escribe un artículo en español en la Comunidad de Desarrolladores, sobre cualquier tema relacionado con la tecnología de InterSystems.

Duración: del 6 de mayo al 2 de junio de 2024.

Premios para todos los participantes: Todas las personas que publiquen un artículo en español durante la vigencia del concurso recibirán un premio.

Premio principal: LEGO Ferrari Daytona SP3 / Banco Mágico Gringotts™ - Edición para coleccionistas. 

 

¡Participa en el concurso y alcanza a cientos de usuarios! Es una de las mejores oportunidades para publicar esos consejos que has descubierto.

Premios

1. Todos los participantes ganan en el concurso de artículos técnicos de InterSystems -> Cualquier miembro de la Comunidad que participe en el concurso, recibirá un detalle de InterSystems por participar.

2. Premios de los Expertos – los artículos ganadores de esta categoría serán elegidos por expertos de InterSystems y podrán elegir en cada caso:

🥇 1er puesto: LEGO Ferrari Daytona SP3 o Banco Mágico Gringotts™ - Edición para coleccionistas. 

🥈 2do puesto: LEGO Sistema de Lanzamiento Espacial Artemis de la NASA o Chaqueta hombre Patagonia Nano Puff® Hoody.

🥉 3er puesto: Altavoz JBL Flip 6, Amazon Kindle 8G Paperwhite (Onceava generación) o Mochila Samsonite SPECTROLITE 3.0 15.6"

O como alternativa, cualquier ganador puede elegir un premio de una categoría inferior a la suya

Nota: Los premios están sujetos a cambiar si la disponibilidad en el país no permite su entrega.

3. Premio de la Comunidad de Desarrolladores – artículo con el mayor número de "Me gusta". La persona que gane, podrá elegir uno de estos premios:

🎁 Altavoz JBL Flip 6, Amazon Kindle 8G Paperwhite (Onceava generación) o Mochila Samsonite SPECTROLITE 3.0 15.6" 

Nota: cada autor solo puede ganar un premio de cada categoría (en total, un autor puede ganar dos premios: uno en la categoría Expertos y otro en la categoría de la Comunidad).

¿Quién puede participar?

Cualquier persona registrada en la Comunidad de Desarrolladores, excepto los empleados de InterSystems. Regístrate aquí en la Comunidad si aún no tienes una cuenta.

Duración del concurso

📝  Del 6 de mayo al 2 de junio: Publicación de artículos.

📝  Del 3 de junio al 9 de junio: Fase de votación. 

Publica tu(s) artículos(s) durante ese período. Los miembros de la Comunidad de Desarrolladores pueden ir votando los artículos que les gustan haciendo clic en "Me gusta" debajo de cada artículo.

Truco: Cuanto antes publiques tu(s) artículo(s), más tiempo tendrás para conseguir más votos de los Expertos y de la Comunidad.

🎉 10 de junio: Anuncio de los ganadores.

    Requisitos

    ❗️ Cualquier artículo escrito durante el período de duración del concurso y que cumpla los siguientes requisitos entrará automáticamente en la competición ❗️:

    • El artículo debe estar relacionado directa o indirectamente con la tecnología de InterSystems (características propias de los productos de InterSystems o, también, herramientas complementarias, soluciones arquitecturales, mejores prácticas de desarrollo,…).
    • El artículo debe estar escrito en español.
    • El artículo debe ser 100% nuevo (puede ser la continuación de un artículo ya publicado).
    • El artículo no puede ser una copia o traducción de otro publicado en la Comunidad de Desarrolladores en español o en otra Comunidad.
    • Tamaño del artículo: >1 000 caracteres (los enlaces no cuentan en el cálculo de caracteres).
    • Modo de participación: individual (se permite que un participante publique varios artículos).

    ¿Sobre qué se puede escribir?

    Se puede escoger cualquier tema técnico relacionado directa o indirectamente con la tecnología de InterSystems.

    🎯 BONUS:

    Los Expertos conceden 3 votos al artículo que consideran el mejor, 2 votos al 2º que consideran mejor y 1 voto al 3º que consideran mejor. Además, los artículos pueden recibir más puntos en función de los siguientes bonus:

    Nota: la decisión de los jueces es inapelable.

    1. Bonus por autor nuevo: Si es la primera vez que participas en el Concurso de Artículos Técnicos en Español, tu artículo recibirá un 1 voto extra de los Expertos.

    2. Bonus por temática: Si tu artículo está dentro de las siguientes temáticas, recibirá 2 puntos extra.

    • Uso de AI/ML/GenAI
    • Cómo aprovechar las posibilidades de la búsqueda vectorial (Vector Search)
    • Aprovechamiento de la función de almacenamiento en columnas
    • ️Uso de Python integrado
    • Uso de Cloud SQL
    • Uso de VSCode
    • Explotación de las capacidades FHIR de IRIS (SMART en FHIR 2.0, modelo de objetos FHIR, FHIR SQL Builder, Bulk FHIR,...)


    3. Vídeo bonus: si además del artículo, se acompaña con un vídeo explicativo, el candidato recibirá 4 puntos.

    4. Bonus por tutorial: Recibirás 3 puntos si el artículo tiene características de tutorial, con instrucciones paso a paso que un desarrollador pueda seguir para completar una o varias tareas específicas.


    Así que... Let's go!

    ¡Esperamos ansiosos vuestros artículos! 

    ¡Comunidad! ¡Que la fuerza os acompañe! ✨🤝

    3 Comments
    讨论 (3)1
    登录或注册以继续
    文章
    · 五月 4, 2024 阅读大约需 3 分钟

    Using VECTORs in ObjectScript

    Most examples I've seen so far in OEX or DC left the impression that VECTORs
    are just something available with SQL with the 3 Functions especially around VECTOR_Search.
    * TO_VECTOR()
    * VECTOR_DOT_PRODUCT ()
    * VECTOR_COSINE ()

    There is a very useful summary hidden in iris-vector-search demo package.
    From there you find everything you need over several links and corners.

    I was missing more VECTOR methods and placed a related request in Idea Portal

    Next I remembered that every SQL Method  or procedure lives on a bunch of ObjectScript code
    So I went to search for it an this is the summary of the research.

    %Library.Vector is the core description of the new DataType
    It's a complex structure like Objects or %DynamicObjects or $Bit Expressions that require specific access methods
    We also see 2 required parameters: 
    * DATATTYPE  - once set can't be changed.
      Accepted types:  "integer" (or "int"), "double", "decimal", "string", and "timestamp".
    * LEN  >0 , may grow bur never shrink

    $vector() / $ve()  is the basic method for Vector access
    Assign Vector Data  >>>  SET $VE(. . .) = val
    Return Vector Data  >>>  WRITE $VE(. . .) ,  SET var=$VE(. . .) 
      HINT: a single position returns the value, but position from::to returns another Vector !
    Delete Vector Data  >>>  KILL $VE(. . .) 
    All 3 require at least 1 Position parameter. You may understand this as dimensions.

    $isvector() the obvious check for correct format before jumping into operations. 

    $vectorop() / $vop() covers all other functions related to vectors
    The call parameters are typically (operation, vector)
    Some operations offer an optional bitexpr. It marks positions/dimensions to be ex-/in-cluded.
    Example: 
    - Think of a 3D vector. you just want to operate on x - and y axis and not to z 

    Single Vector Operations

    Aggregate Operations
     * "count"
     * "max"
     * "min"
     * "sum"
    Filter Operations
     * "defined"
     * "undefined"
     * "<"
     * "<="
     * ">"
     * ">="
     * "="
     * "!="
     * "between"
    Numeric Operations
     * "+"
     * "-"
     * "/"
     * "*"
     * "**"
     * "#"
     * "e-"
     * "e/"
     * "ceiling"
     * "floor"
    String Operations
     * "_"
     * "e_"
     * "lower"
     * "upper"
     * "substring"
     * "trim"
     * "triml"
     * "trimr"
    Grouping Operations
     * "group"
     * "countgb"
    Miscellaneous Operations
     * "convert"
     * "length"
     * "mask"
     * "positions"
     * "set"
    Informative Operations
     * "bytesize"
     * "type"

    Multi Vector Operations  (mostly 2 vectors)

    Vector-wise Filter Operations
     * "v<"
     * "v<="
     * "v>"
     * "v>="
     * "v="
     * "v!="
    Vector-wise Arithmetic Operations
     * "v+"
     * "v-"
     * "v/"
     * "v*"
     * "v**"
     * "v#"
    Vector Concatenation
     * "v_"
    Vector Grouping
     * "countg"
     * "maxg"
     * "ming"
     * "sumg"
    Vector Merge
     * "vset"

    You see there is a rich set of tools already available.
    If you study docs in details, the purpose or advantage of the results may
    not be evident immediately. 

    Though I hope you got an overview of what is available now.

    1 Comment
    讨论 (1)1
    登录或注册以继续
    文章
    · 五月 3, 2024 阅读大约需 6 分钟

    Demo: Connecting Locally to an S3 Bucket without an AWS Account

    Introduction

    Accessing Amazon S3 (Simple Storage Service) buckets programmatically is a common requirement for many applications. However, setting up and managing AWS accounts is daunting and expensive, especially for small-scale projects or local development environments. In this article, we'll explore how to overcome this hurdle by using Localstack to simulate AWS services. Localstack mimics most AWS services, meaning one can develop and test applications without incurring any costs or relying on an internet connection, which can be incredibly useful for rapid development and debugging. We used ObjectScript with embedded Python to communicate with Intersystems IRIS and AWS simultaneously. Before beginning, ensure you have Python and Docker installed on your system. When Localstack is set up and running, the bucket can be created and used. 

    Creating an S3 Bucket from ObjectScript with Embedded Python

    Now that LocalStack is running, let's create an S3 bucket programmatically. We'll use Python and the Boto3 library - a Python SDK for AWS services. Take a look at the MakeBucket method provided in the S3UUtil class. This method utilizes Boto3 to create an S3 bucket:

    ClassMethod MakeBucket(inboundfromiris As %String) As %Status [ Language = python ]
    
    {
    
        import boto3
    
        s3 = boto3.client(
    
            service_name='s3', 
    
            region_name="us-east-1", 
    
            endpoint_url='http://host.docker.internal:4566', 
        )
    
        try:
    
            s3.create_bucket(Bucket=inboundfromiris)
    
            print("Bucket created successfully")
    
            return 1
        except Exception as e:
    
            print("Error:", e)
    
            return 0
    }

    To create a bucket, you would call this method with the desired bucket name:

    status = S3UUtil.MakeBucket("mybucket")

    Uploading Objects to the Bucket from ObjectScript with Embedded Python

    Once the bucket is created, you can upload objects to it programmatically. The PutObject method demonstrates how to achieve this:

    ClassMethod PutObject(inboundfromiris As %String, objectKey As %String) As %Status [ Language = python ]
    
    {
    
        import boto3
    
        try:
    
            content = "Hello, World!".encode('utf-8')
    
            s3 = boto3.client(
    
                service_name='s3',
    
                region_name="us-east-1",
    
                endpoint_url='http://host.docker.internal:4566'
            )
    
            s3.put_object(Bucket=inboundfromiris, Key=objectKey, Body=content)
    
            print("Object uploaded successfully!")
    
            return 1
        except Exception as e:
    
            print("Error:", e)
    
            return 0
    }

    Call this method to upload an object:

    Do ##class(S3.S3UUtil).PutObject("inboundfromiris", "hello-world-test")

     

    Listing Objects in the Bucket from ObjectScript with Embedded Python

    To list objects in the bucket, you can use the FetchBucket method:

    ClassMethod FetchBucket(inboundfromiris As %String) As %Status [ Language = python ]
    
    {
    
        import boto3
    
        s3 = boto3.client(
    
            service_name='s3', 
    
            region_name="us-east-1", 
    
            endpoint_url='http://host.docker.internal:4566', 
        )
    
        try:
    
            response = s3.list_objects(Bucket=inboundfromiris)
    
            if 'Contents' in response:
    
                print("Objects in bucket", inboundfromiris)
    
                for obj in response['Contents']:
    
                    print(obj['Key'])
    
                return 1
            else:
    
                print("Error: Bucket is empty or does not exist")
    
                return 0
        except Exception as e:
    
            print("Error:", e)
    
            return 0
    }

    Call the FetchBucket method to list objects from the bucket:

    do ##class(S3.S3UUtil).FetchBucket("inboundfromiris")


     

    Retrieving Objects from the Bucket from ObjectScript with Embedded Python

    Finally, to retrieve objects from the bucket, you can use the PullObjectFromBucket method:

    ClassMethod PullObjectFromBucket(inboundfromiris As %String, objectKey As %String) As %Status [ Language = python ]
    
    {
    
        import boto3
    
        def pull_object_from_bucket(bucket_name, object_key):
    
            try:
    
                s3 = boto3.client(
    
                    service_name='s3', 
    
                    region_name="us-east-1", 
    
                    endpoint_url='http://host.docker.internal:4566', 
                )
    
                obj_response = s3.get_object(Bucket=bucket_name, Key=object_key)
    
                content = obj_response['Body'].read().decode('utf-8')
    
                print("Content of object with key '", object_key, "':", content)
    
                return True
    
            except Exception as e:
    
                print("Error:", e)
    
                return False
    
        pull_object_from_bucket(inboundfromiris, objectKey)
    
    }

    Call this method:

    Do ##class(DQS.CloudUtils.S3.S3UUtil).PullObjectFromBucket("inboundfromiris", "hello-world-test")

     

    The discussion here is just the beginning, as it's clear there's plenty more ground to cover. I invite readers to dive deeper into this subject and share their insights. Let's keep the conversation going and continue advancing our understanding of this topic.

    I'm eager to hear thoughts and contributions.

    讨论 (0)1
    登录或注册以继续