使用Java在MySQL中将值从一个表写入另一个表

时间:2016-12-20 05:03:18

标签: java mysql jdbc

File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
    for(File file: path.listFiles()) {
        if (file.isFile()) {
            String fileName = file.getName();
            String ticker = fileName.split("\\_")[0];
            String writeCompanyValues = "INSERT INTO BALANCESHEET (companies_id, Companies, ticker) "
                                        + "SELECT companies_id, Companies, ticker FROM companies WHERE ticker = " + ticker;
            statement.executeUpdate(writeCompanyValues);

        }
    }

我有公司代码(例如AAPL)存储在股票代码字符串中,并在我的公司表中有一个名为ticker的列。我想找到一个带有该股票行的行,并将该行数据复制到资产负债表表格中。

我在线程“main”

中收到错误Exception
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'AAPL' in 'where clause'

有关如何以这种方式复制数据的任何想法?

1 个答案:

答案 0 :(得分:2)

您应该使用prepared statements而不是字符串连接来避免此类问题。并防止SQL注入(这是由Scary Wombat添加的建议)。这里的错误是由于缺少引用

"SELECT companies_id, Companies, ticker FROM companies WHERE ticker = '" + ticker +"'";

可选地

String writeCompanyValues = "INSERT INTO BALANCESHEET (companies_id, Companies, ticker) "
                                        + "SELECT companies_id, Companies, ticker FROM companies WHERE ticker = ?";

stmt = con.prepareStatement(writeCompanyValues);
stmt.setString(1, ticker);
stmt.executeUpdate();