Home >Java >javaTutorial >Database programming in Java

Database programming in Java

PHPz
PHPzOriginal
2023-06-16 08:12:091946browse

Java is a very powerful programming language that excels in data processing and management. The Java language is widely used in database programming, and many applications involve database operations. In this article, we will explore database programming in Java.

1. Overview of JDBC

JDBC (Java Database Connectivity, Java Database Connection) is a common access interface for various relational databases in the Java language. It is part of the Java EE architecture and is also a part of Java An important component in programming, it is often used to realize the connection between Java and database.

Using JDBC, you can easily establish a connection with any database that supports the SQL protocol and directly execute SQL statements. The JDBC API defines many classes and interfaces for implementing Java-based database connections, including driver managers, connectors, statements, result sets, etc.

2. JDBC driver

When using JDBC programming, you need to establish a connection with the database through the driver. A JDBC driver is a software module used to communicate with a database. JDBC drivers are usually provided by database vendors, but you can also develop your own drivers.

JDBC drivers are generally divided into four types:

  1. JDBC-ODBC Bridge: The JDBC-ODBC Bridge is a universal driver that allows Java applications to pass ODBC Interface to access any ODBC compliant database.
  2. Native API driver: The native API driver is a driver provided directly by the database vendor for use by Java developers. This driver requires different implementations to communicate with different databases.
  3. Network protocol driver: The network protocol driver communicates with the server through the database's network protocol. The driver usually uses the TCP/IP protocol.
  4. Pure Java Drivers: Pure Java drivers are drivers written entirely in Java that communicate with the database using network protocols provided by the database vendor. This driver is often called a JDBC Type 4 driver.

3. Use of JDBC API

Connecting to the database usually requires the following steps:

  1. Load the driver: use the Class.forName() method Load the JDBC driver.
  2. Connect to the database: Use the DriverManager.getConnection() method to establish a connection to the database.
  3. Create a Statement object: Use the Connection.createStatement() method to create an executable SQL statement object.
  4. Execute SQL statements: Use the execute() method of the Statement object to execute SQL statements.
  5. Get the result set: If the SQL statement returns a relational table, you can use the executeQuery() method of the Statement object to get the result set.
  6. Close the database connection: When communication with the database is no longer needed, use the Connection.close() method to close the database connection.

The following is an example of a Java program connecting to a MySQL database:

import java.sql.*;

public class JDBCExample {
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   
   try{
      Class.forName("com.mysql.jdbc.Driver");

      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      while(rs.next()){
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }

      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      se.printStackTrace();
   }catch(Exception e){
      e.printStackTrace();
   }finally{
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
   System.out.println("Goodbye!");
}
}

In the above example program, first load the com.mysql.jdbc.Driver driver and then connect to specified database. Then use the created Statement object stmt to execute the SQL query in the MySQL database. Finally, close the ResultSet, Statement and database connection Connection objects.

Summary

In applications, data is usually stored in relational databases. The Java language provides many practical APIs to connect and interact with databases. JDBC is one of the commonly used database connection APIs in Java, which allows Java applications to easily establish communication with any relational database. When doing database programming in Java, you need to first load the corresponding driver to establish a connection with the database. Then, you can use the classes and methods of the JDBC API to perform operations such as SQL queries, adding, deleting, and modifying data.

The above is the detailed content of Database programming in Java. 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