上面问题中,如何查询表格并输出,并在页面输出一行文字
时间: 2024-02-12 20:07:46 浏览: 24
好的,您可以在 `try` 块中加入查询表格的代码,并在控制台输出查询结果。示例代码如下:
```java
import java.sql.*;
public class ConnectToDatabase {
public static void main(String[] args) {
Connection conn = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库(这里假设数据库名为myDB,用户名为root,密码为123456)
String url = "jdbc:mysql://localhost/myDB?useSSL=false";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 查询表格并输出
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM 表名";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("name");
String gender = rs.getString("gender");
int age = rs.getInt("age");
System.out.println(name + " " + gender + " " + age);
}
// 输出连接成功信息
System.out.println("连接数据库成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
// 输出连接失败信息
System.out.println("连接数据库失败");
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 输出一行文字
System.out.println("查询结果已输出");
}
}
```
需要注意的是,上述代码中的 `表名` 需要替换为您自己的表格名。另外,如果您要查询的是SQL Server数据库中的表格,则需要修改SQL语句中的语法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.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://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)