已经在mysql类中用jdbc连接了mysql数据库,怎么在测试类中输入用户信息到数据库里,并导出数据库的航班信息
时间: 2024-02-13 13:05:32 浏览: 31
你可以在测试类中编写一个方法,首先从用户输入获取用户信息,然后将数据插入到数据库中。可以使用 JDBC 的 PreparedStatement 对象来执行插入操作。
以下是一个示例方法:
```java
public void addUserInfoToDatabase(String name, String email, String password) {
// 假设已经创建了一个名为 connection 的 Connection 对象
try {
PreparedStatement statement = connection.prepareStatement("INSERT INTO user (name, email, password) VALUES (?, ?, ?)");
statement.setString(1, name);
statement.setString(2, email);
statement.setString(3, password);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
这个方法将用户提供的姓名、电子邮件和密码插入到名为 "user" 的表中。你需要根据你自己的情况修改表名和列名。
要导出数据库的航班信息,你可以编写一个查询语句,然后执行它并将结果导出到一个文件中。以下是一个示例方法:
```java
public void exportFlightInfoToCsv() {
// 假设已经创建了一个名为 connection 的 Connection 对象
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM flight");
FileWriter writer = new FileWriter("flight.csv");
while (resultSet.next()) {
String flightNumber = resultSet.getString("flight_number");
String departure = resultSet.getString("departure");
String destination = resultSet.getString("destination");
String departureTime = resultSet.getString("departure_time");
String arrivalTime = resultSet.getString("arrival_time");
writer.write(flightNumber + "," + departure + "," + destination + "," + departureTime + "," + arrivalTime + "\n");
}
writer.close();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
```
这个方法将名为 "flight" 的表中的所有行导出到名为 "flight.csv" 的 CSV 文件中。你需要根据你自己的情况修改表名和列名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)