java - 从字符串数组更新 mysql 数据库

标签 java mysql database

我是 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/

相关文章:

database - MongoDB 按年份查找查询

java - 尝试从多个 Maven 模块构建 uberjar

java - 如何在java中每行替换220行代码?

java - 如何使用线程更新textview?

mysql - 如何计算每个地址的商店数量?

php - 如何从 'table' 中选择 WHERE 列 = *通配符*

mysql - 由于某种原因,加入更新需要 9 到 30 个小时?

java - (Java) 在控制台中逐个字母地打印文本 - ft. Lag

php - 将两个 Laravel 集合与交替的行组合起来

database - Redis中的限制列表长度