java读取数据库
时间: 2023-07-08 07:20:21 浏览: 68
要在Java中读取数据库,需要使用JDBC API。以下是一个简单的Java程序,它使用JDBC连接到MySQL数据库并读取数据:
```java
import java.sql.*;
public class ReadDatabase {
public static void main(String[] args) {
try {
//连接到MySQL数据库
String url = "jdbc:mysql://localhost/mydatabase";
String username = "root";
String password = "mypassword";
Connection conn = DriverManager.getConnection(url, username, password);
//执行SQL查询
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
//遍历查询结果并输出
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
//关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们首先使用`DriverManager.getConnection()`方法连接到MySQL数据库。然后,我们使用`conn.createStatement()`方法创建一个`Statement`对象,该对象用于执行SQL查询。接下来,我们使用`stmt.executeQuery()`方法执行查询,并使用`ResultSet`对象遍历查询结果。最后,我们关闭连接,以释放资源。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)