Home Java javaTutorial Java development: How to use JNDI for database connection and resource management

Java development: How to use JNDI for database connection and resource management

Sep 20, 2023 am 10:10 AM
jndi (character) Database connection (characters) Resource Management (characters)

Java development: How to use JNDI for database connection and resource management

Java development: using JNDI for database connection and resource management

In Java development, JNDI (Java Naming and Directory Interface) is a standard API. For managing naming and directory services. It can be used not only to access naming services, but also to connect to databases, manage resources, etc. This article will introduce how to use JNDI for database connection and resource management, and provide detailed code examples.

  1. Configure JNDI data source
    First, add the configuration information of the JNDI data source in the configuration file of the Java web application (such as web.xml). The following is an example configuration:
<resource-ref>
  <description>Database Connection</description>
  <res-ref-name>jdbc/myDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>
Copy after login

Here, we define a JNDI data source named jdbc/myDB and specify its type as javax.sql .DataSource.

  1. Configure the data source in the server
    Next, you need to configure the actual database connection information in the configuration file of the server (such as Tomcat). The following is a sample configuration (in Tomcat's context.xml file):
<Resource name="jdbc/myDB" auth="Container"
          type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/myDB"
          username="root" password="password"
          maxTotal="100" maxIdle="30" maxWaitMillis="10000" />
Copy after login

Here, we configure a file named jdbc/myDB The data source specifies the connection URL, user name, password and other information, as well as some configurations of the connection pool.

  1. Get the database connection
    In the Java code, obtain the database connection through JNDI. The following is an example:
// 创建JNDI上下文
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");

// 获取数据源
DataSource ds = (DataSource) envCtx.lookup("jdbc/myDB");

// 获取数据库连接
Connection conn = ds.getConnection();
Copy after login

Here, we first create the initial context of JNDI initCtx, and then obtain the environment context envCtx through this context. Next, we obtained the previously configured data source jdbc/myDB from the environment context. Finally, obtain the database connection through the data source.

  1. Using database connection
    After obtaining the database connection, we can use it to perform various database operations, such as query, insert, update, etc. The following is a simple example:
try {
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM users");

    while (rs.next()) {
        int id = rs.getInt("id");
        String name = rs.getString("name");
        System.out.println("User: " + id + ", " + name);
    }

    rs.close();
    stmt.close();
} catch (SQLException e) {
    e.printStackTrace();
}
Copy after login
  1. Close the database connection
    After you have finished using the database connection, you need to manually close it to release resources. The following is a code example for closing the database connection:
try {
    if (conn != null) {
        conn.close();
    }
} catch (SQLException e) {
    e.printStackTrace();
}
Copy after login

Through the above steps, we can use JNDI for database connection and resource management. The advantage of using JNDI is that database connection information can be centrally managed in the configuration file without hard-coding connection parameters in the code, making the code more concise and maintainable.

Summary:
This article introduces how to use JNDI for database connection and resource management. By configuring JNDI data sources, server configuration data sources, obtaining database connections, and using and closing connection sample codes, we can easily use JNDI to manage database connections and resources in Java development. I hope this article can be helpful to developers who are learning and using JNDI.

The above is the detailed content of Java development: How to use JNDI for database connection and resource management. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

When Tomcat loads Spring-Web modules, does the SPI mechanism really destroy the visibility principle of Java class loaders? When Tomcat loads Spring-Web modules, does the SPI mechanism really destroy the visibility principle of Java class loaders? Apr 19, 2025 pm 02:18 PM

Analysis of class loading behavior of SPI mechanism when Tomcat loads Spring-Web modules. Tomcat is used to discover and use the Servle provided by Spring-Web when loading Spring-Web modules...

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

See all articles