0

我有一个下面的方法,用于preparedStatements将数据插入到我的 SQL 数据库中。目前它是被插入到的天气数据mydb.weather_data。出于某种原因,我连接到我的数据库没有问题(没有出现任何连接错误),但实际上没有数据插入到我的数据库中。

我想知道这个问题会是什么?下面的数字都是用于测试插入的虚拟数据。

我的type五列分别是varChar(10)Int其余四列。

private static void batchInsertRecordsIntoTable() throws SQLException{
        Connection dbConnection = null;
        PreparedStatement preparedStatement = null;

        String insertTableSQL = "INSERT INTO `mydb`.`weather_data`" 
                + "(`dateTime`,`hourlyTemp`,`dewPoint`,`windSpeed`,`relHum`) VALUES" 
                + "(?,?,?,?,?)";
        try{
            dbConnection = getDBConnection();
            preparedStatement = dbConnection.prepareStatement(insertTableSQL);

            dbConnection.setAutoCommit(false);

            preparedStatement.setString(1, "1111111111"); // dateTime
            preparedStatement.setInt(2, 12); // hourlyTemp
            preparedStatement.setInt(3, 12); // dewPoint
            preparedStatement.setInt(4, 12); //windSpped
            preparedStatement.setInt(5, 12); //relHum
            preparedStatement.addBatch();

            preparedStatement.executeBatch();

            dbConnection.commit();

            System.out.println("Record was inserted into mydb weather_data");

        }catch(SQLException e){
            System.out.println(e.getMessage());
            dbConnection.rollback();
        }finally{
            if(preparedStatement!=null){
                preparedStatement.close();
            }
            if(dbConnection!=null){
                dbConnection.close();
            }
        }
    }
4

1 回答 1

0

尝试这个:

private static void batchInsertRecordsIntoTable() throws SQLException{
        Connection dbConnection = null;
        PreparedStatement preparedStatement = null;

        String insertTableSQL = "INSERT INTO mydb.weather_data" 
                + "(dateTime,hourlyTemp,dewPoint,windSpeed,relHum) VALUES" 
                + "(?,?,?,?,?)";
        try{
            dbConnection = getDBConnection();
            preparedStatement = dbConnection.prepareStatement(insertTableSQL);

            dbConnection.setAutoCommit(false);

            preparedStatement.setString(1, "1111111111"); // dateTime
            preparedStatement.setInt(2, 12); // hourlyTemp
            preparedStatement.setInt(3, 12); // dewPoint
            preparedStatement.setInt(4, 12); //windSpped
            preparedStatement.setInt(5, 12); //relHum

            preparedStatement.executeUpdate();

            dbConnection.commit();

            System.out.println("Record was inserted into mydb weather_data");

        }catch(SQLException e){
            System.out.println(e.getMessage());
            dbConnection.rollback();
        }finally{
            if(preparedStatement!=null){
                preparedStatement.close();
            }
            if(dbConnection!=null){
                dbConnection.close();
            }
        }
    }
于 2014-01-31T10:59:06.283 回答