温馨提示×

java如何获取数据库数据

小亿
111
2023-08-04 13:53:23
栏目: 编程语言

在Java中,可以使用JDBC(Java Database Connectivity)来连接和操作数据库。以下是一个简单的示例代码,演示如何使用JDBC获取数据库数据:
```java
import java.sql.*;

public class DatabaseConnection {
   public static void main(String[] args) {
       Connection connection = null;
       Statement statement = null;
       ResultSet resultSet = null;

       try {
           // 1. 加载数据库驱动
           Class.forName("com.mysql.cj.jdbc.Driver");

           // 2. 建立数据库连接
           connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");

           // 3. 创建 Statement 对象
           statement = connection.createStatement();

           // 4. 执行 SQL 查询
           String sql = "SELECT * FROM mytable";
           resultSet = statement.executeQuery(sql);

           // 5. 处理查询结果
           while (resultSet.next()) {
               int id = resultSet.getInt("id");
               String name = resultSet.getString("name");
               int age = resultSet.getInt("age");

               System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
           }
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } catch (SQLException e) {
           e.printStackTrace();
       } finally {
           // 6. 关闭数据库连接和资源
           try {
               if (resultSet != null) {
                   resultSet.close();
               }
               if (statement != null) {
                   statement.close();
               }
               if (connection != null) {
                   connection.close();
               }
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
   }
}
```
在这个示例中,首先需要加载数据库驱动,然后建立数据库连接。接下来,创建一个 Statement 对象,使用该对象执行 SQL 查询。查询结果返回的是一个 ResultSet 对象,可以使用 `next()` 方法逐行遍历结果集,并使用 `getXxx()` 方法获取具体的数据。最后,记得关闭数据库连接和释放资源。
请注意,上述代码中的数据库连接 URL、用户名和密码需要根据实际情况进行修改。

0