参考: https://www.cnblogs.com/lingshang/p/10721576.html
// 题目是:计算数据库中所有图书项 价格标签的 总和
import java.sql.*;
public class MyJDBC {
public static void main(String[] args) {
Connection connection;
PreparedStatement preparedStatement;
ResultSet res;
double sum = 0d;
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "123456";
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
try {
//加载数据库驱动
Class.forName(driver);
// 通过驱动管理类获取数据库连接
connection = DriverManager.getConnection(url, userName, password);
// 定义 SQL语句, ?标识占位符
String sql = "select ? from DATA";
// 获取预处理语句
preparedStatement = connection.prepareStatement(sql);
// 填充占位符
preparedStatement.setString(1, "price");
// 执行查询, 查询出结果集
res = preparedStatement.executeQuery();
// 遍历查询结果集
while (res.next()) {
String price = res.getString("price");
sum += Double.parseDouble(price);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(sum);
}
}