java与mysql数据库连接完成多条查询
时间: 2023-09-13 19:04:30 浏览: 47
好的,您可以参考以下 Java 代码实现多条查询:
```java
import java.sql.*;
public class MySQLTest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 注册数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 获取数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 3. 创建Statement对象
stmt = conn.createStatement();
// 4. 执行查询语句1
String sql1 = "SELECT * FROM student";
rs = stmt.executeQuery(sql1);
// 处理查询结果1
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id: " + id + ", name: " + name + ", age: " + age);
}
// 5. 执行查询语句2
String sql2 = "SELECT * FROM course";
rs = stmt.executeQuery(sql2);
// 处理查询结果2
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
int credit = rs.getInt("credit");
System.out.println("id: " + id + ", name: " + name + ", credit: " + credit);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6. 关闭资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在以上代码中,我们首先注册了 MySQL 数据库驱动,然后获取了数据库连接,在创建 Statement 对象后,分别执行了两条查询语句并处理了查询结果。最后,我们关闭了资源。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](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)