In Java, you can use JDBC to access different databases, including: loading the JDBC driver, obtaining the connection, creating a Statement/PreparedStatement, executing the query/updating the traversal results, releasing resources
Java Database Connection: Connecting to different types of databases
In Java, you can connect to various types of databases through the JDBC (Java Database Connectivity) API. JDBC provides a common set of Java classes and interfaces that allow applications to interact with different database systems such as MySQL, Oracle, SQL Server, etc.
Connection steps
Connecting to a database usually involves the following steps:
Loading the JDBC driver:
Class.forName("com.mysql.cj.jdbc.Driver");
Get connection:
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb", "user", "password");
Create Statement/PreparedStatement:
Statement stmt = conn.createStatement();
Execute query/update:
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
Traversal results:
while (rs.next()) { // 获取结果集中的值 }
Release resources:
rs.close(); stmt.close(); conn.close();
Practical case: Connecting to MySQL database
The following code example demonstrates how to connect to a MySQL database and execute a query:
import java.sql.*; public class MySQLConnection { public static void main(String[] args) { Connection conn; try { // 加载 MySQL 驱动 Class.forName("com.mysql.cj.jdbc.Driver"); // 获取连接 conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb", "user", "password"); // 创建 Statement Statement stmt = conn.createStatement(); // 执行查询 ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // 遍历结果 while (rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("name")); } // 释放资源 rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
Notes on connecting to different types of databases
By following these steps and taking these considerations into account, you can easily connect to various types of databases and perform various operations using Java JDBC.
The above is the detailed content of How does Java database connection connect to different types of databases?. For more information, please follow other related articles on the PHP Chinese website!