我是 mysql 的新手,在从我的 java 程序更新我的 sql 数据库时遇到问题。我的 java 程序执行所有计算并将要更新的值存储在大小为 2000 的字符串数组中。我的 sql 数据库包含以下内容列 名字 价格 高 低 我的字符串数组存储以逗号分隔的价格、高价、低价。(我实际上查询了雅虎金融并将 csv 文件存储在一个字符串中)。 现在我需要使用字符串中的数据更新价格、最高价、最低价。我该怎么做。或者是否可以直接将yahoo finance返回的数据上传到我的数据库中。
代码
URL yahoofin = new URL("http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=nl1sjkm3m4r");
URLConnection yc = yahoofin.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
}
我用来更新单个股票的代码
Statement stmt = conn.createStatement() ;
// Execute the Update
int rows = stmt.executeUpdate( "UPDATE tablename SET id = 9842 WHERE name='name'" )
最佳答案
构建准备好的语句:
String sql = "update stock set price = ?, high = ?, low = ? where name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
然后遍历 CSV 文件的行,并将每一行解析为包含 4 个字段的数据结构(或简单数组):
while ((inputLine = in.readLine()) != null) {
StockLine line = parseStockLine(inputLine);
}
并且对于每一行,绑定(bind)参数并执行语句:
while ((inputLine = in.readLine()) != null) {
StockLine line = parseStockLine(inputLine);
stmt.setBigDecimal(1, line.getPrice());
stmt.setBigDecimal(2, line.getHigh());
stmt.setBigDecimal(3, line.getLow());
stmt.setString(4, line.getName());
stmt.executeUpdate();
}
为了加快速度,您可以使用批处理:
while ((inputLine = in.readLine()) != null) {
StockLine line = parseStockLine(inputLine);
stmt.setBigDecimal(1, line.getPrice());
stmt.setBigDecimal(2, line.getHigh());
stmt.setBigDecimal(3, line.getLow());
stmt.setString(4, line.getName());
stmt.addBatch();
}
stmt.executeBatch();
关于java - 从字符串数组更新 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9698524/