java输入序号从数据库提取数据并进行计算
时间: 2023-09-11 21:06:56 浏览: 170
好的,这里是一个Java示例,演示如何从MySQL数据库中获取数据并进行计算,用户可以通过输入序号选择要计算的数据:
```java
import java.sql.*;
public class DatabaseCalculation {
public static void main(String[] args) {
try {
// Connect to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// Query the data
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// Display the data and ask for input
int i = 1;
while (rs.next()) {
System.out.println(i + ". " + rs.getString("column_name"));
i++;
}
int choice = Integer.parseInt(System.console().readLine("Enter the number to calculate: "));
// Extract the chosen data
rs.absolute(choice);
double data = rs.getDouble("column_name");
// Perform the calculation
double result = data / rs.getRow();
// Display the result
System.out.println("The average value is: " + result);
// Close the resources
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
这个示例使用了Java的JDBC API连接到一个MySQL数据库,并查询了一个名为mytable的表中的所有数据。然后,它显示了所有数据,并要求用户输入序号来选择要计算的数据。接下来,它从查询结果中提取了所选行的数据,并对这些数据进行了求和和平均值的计算。最后,它将平均值显示在控制台上。
阅读全文
相关推荐

















