Insert Java variable using Java in SQL

I have tried:

 String sql = "INSERT INTO CURRENT_WEATHER_US VALUES("+city_code+",   
"+object.city+","+object.region+","+object.country+","+object.wind_chill+",  
"+object.wind_direction+", "+object.wind_speed+","+object.humidity+","+object.visibility+", 
"+object.pressure+","+object.rising+",  
"+object.sunrise+","+object.sunset+","+object.textual_description+",  
"+object.condition_code+","+object.temp+","+object.for_temp_high+",  
"+object.for_temp_low+","+object.for_description+","+object.forecast_code+")";   

  stmt.execute(sql);  

Error missing comma

Please, help

+5
source share
3 answers

This is not how you should create and execute a SQL INSERT query with variables. This is not only subject to SQL injection attacks , but also quite .. cumbersome;) Perhaps the value contained one value and caused your query to be syntactically invalid.

SQL. PreparedStatement ( ) ? SQL. , Java ( Date InputStream!)) SQL , , SQL- (, , SQL-).

, SQL:

private static final String SQL_INSERT = "INSERT INTO CURRENT_WEATHER_US"
    + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

public void create(String cityCode, Weather weather) throws SQLException {
    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
    ) {
        statement.setString(1, cityCode);
        statement.setString(2, weather.getCity());
        statement.setString(3, weather.getRegion());
        // ...
        statement.setString(20, weather.getForecastCode());
        statement.executeUpdate();
    }
}

JDBC , .

, .

+27

PrepairedStatements . , .

+3

, PreparedStatements . , ( ORA), String, .

textual_description for_description, String, :

String sql = "INSERT INTO CURRENT_WEATHER_US VALUES( " +
    city_code + ", " +
    object.city + ", " +
    object.region + ", " +
    object.country + ", " +
    object.wind_chill  + ", " +
    object.wind_direction + ", " +
    object.wind_speed + ", " +
    object.humidity + ", " +
    object.visibility + ", " +
    object.pressure + ", " +
    object.rising + ", " +
    object.sunrise + ", " +
    object.sunset + ", " +
    "'" + object.textual_description + "', " +
    object.condition_code + ", " +
    object.temp + ", " +
    object.for_temp_high + ", " +
    object.for_temp_low + ", " +
    "'" + object.for_description + "', " +
    object.forecast_code + 
    " )";   

stmt.execute(sql);  

, .

0

All Articles