search
HomeJavajavaTutorialJava 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>

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" />

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();

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();
}
  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();
}

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
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!