Home  >  Article  >  How to connect jndi to database

How to connect jndi to database

小老鼠
小老鼠Original
2024-04-19 10:37:451060browse

You can connect to the database through JNDI (Java Naming and Directory Interface). Specific steps include: Obtain JNDI context Search data source Obtain database connection Execute SQL query Processing result set Close connection

How to connect jndi to database

JNDI connection database

JNDI (Java Naming and Directory Interface) is a Java API used to access naming services and directory services. It provides a unified interface that enables applications to access a variety of naming and directory services, including LDAP, RMI registries, and database connection pools.

To use JNDI to connect to the database, you need to perform the following steps:

1. Get the JNDI context

First, you need to get the JNDI context, which represents the The connection to the named service. You can use the InitialContext class to create a context:

<code class="java">import javax.naming.*;
InitialContext ctx = new InitialContext();</code>

2. Find the data source

Next, you need to find the data source. The data source is the configuration of the connection pool, which contains the configuration information required to connect to the database. The name of the data source is usually stored in the JNDI context. You can find the data source according to the name:

<code class="java">DataSource ds = (DataSource) ctx.lookup("jdbc/myDataSource");</code>

3. Get the database connection

You can get the database connection from the data source. You can use the getConnection() method:

<code class="java">Connection conn = ds.getConnection();</code>

4. Execute SQL query

After obtaining the connection, you can execute the SQL query:

<code class="java">Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM myTable");</code>

5. Process the result set

Finally, process the query results:

<code class="java">while (rs.next()) {
    // 处理结果集中的每一行
}</code>

6. Close the connection

Once completed, close the connection to release the resources:

<code class="java">rs.close();
stmt.close();
conn.close();</code>

It is important to note that the specific implementation of JNDI connection to the database may vary depending on the application server or container.

The above is the detailed content of How to connect jndi to database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn