【问题标题】:Updating mysqldatabase from a string array从字符串数组更新 mysqldatabase
【发布时间】:2012-03-30 17:01:20
【问题描述】:

我是 mysql 新手,从我的 java 程序更新我的 sql 数据库时遇到问题。我的 java 程序执行所有计算并将要更新的值存储在大小为 2000 的字符串数组中。我的 sql 数据库包含以下内容列 名称 价格 高 低 我的字符串数组存储价格,高,低,用逗号分隔。(我实际上查询了 yahoo Finance 并将 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'" ) 

【问题讨论】:

    标签: java mysql database


    【解决方案1】:

    构造一个准备好的语句:

    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);
    }
    

    并且对于每一行,绑定参数并执行语句:

    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();
    

    【讨论】:

    • 我遇到了问题。当我尝试更新具有负号的双精度时,它会引发以下错误您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 'change = -0.1 where SYMBOL = ' 附近使用正确的语法
    • 这与您的原始问题无关,并且您没有显示您的代码。请尝试自己理解,如果不理解,请使用您的代码提出另一个问题。
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2015-07-29
      相关资源
      最近更新 更多