1. 查询所有宠物主人信息。使用JDBC查询数据表master中所有宠物主人信息并输出。
时间: 2024-03-26 11:38:39 浏览: 45
好的,以下是使用JDBC查询数据表master中所有宠物主人信息并输出的Java代码示例:
```java
import java.sql.*;
public class QueryPetOwners {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 创建 SQL 语句并执行查询
String sql = "SELECT * FROM master";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
// 输出查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String phone = rs.getString("phone");
String address = rs.getString("address");
System.out.println(id + "\t" + name + "\t" + phone + "\t" + address);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接和释放资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
其中,需要根据实际情况修改数据库连接的URL、用户名和密码。同时,代码中使用了try-catch-finally语句块来处理异常和关闭连接,保证代码的健壮性。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)