Java database connection requires the use of classes and methods in the java.sql package, including: DriverManager: manages the database driver and establishes a connection with the database. Connection: Represents the connection to the database. Statement: The object that executes the SQL statement. ResultSet: Object that stores query results.
Common classes and methods for Java database connection
To connect to the database in Java, you need to use the java.sql
package classes and methods in . The following introduces several common classes and methods:
Class:
Method:
Practical case:
Connect to MySQL database and query a table:
import java.sql.*; public class JdbcExample { public static void main(String[] args) { // 数据库连接信息 String url = "jdbc:mysql://localhost:3306/database_name"; String user = "username"; String password = "password"; try { // 获取连接 Connection connection = DriverManager.getConnection(url, user, password); // 创建 Statement 对象 Statement statement = connection.createStatement(); // 执行查询 ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name"); // 遍历结果 while (resultSet.next()) { String name = resultSet.getString("column_name"); int age = resultSet.getInt("column_name"); System.out.println(name + " - " + age); } // 释放资源 resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
In the above code, we generated a database with MySQL The database connection executes a query statement and traverses the query results.
The above is the detailed content of What common classes and methods are used for Java database connections?. For more information, please follow other related articles on the PHP Chinese website!