2010-02-13 19 views
5

我試圖這樣做:在SQL中使用Java插入Java變量

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

錯誤缺少逗號

請幫助

+2

這是在Java中使用SQL語句的最糟糕的方法。請參閱BalusC的正確答案。 – 2010-02-13 05:03:02

回答

26

這是不是真的你應該構建方式使用變量執行SQL INSERT查詢。這不僅容易出現SQL injection attacks,但它也很漂亮..)笨重;)可能是一個值包含單引號並導致您的查詢在語法上無效。

只是不要將變量串連到SQL字符串中。請改用PreparedStatementtutorial here)和?作爲SQL字符串中變量的佔位符。通過這種方式,您可以很好地將全部Java對象(包括DateInputStream!)放在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正確的方法,你可能會發現this article有用。

希望這會有所幫助。

3

你應該看看使用PrepairedStatements而不是構建字符串。他們更快,並處理與引用和轉義價值相關的許多缺陷。

0

像所有其他人說的,你真的應該將它轉換爲使用PreparedStatements的原因有很多。你最有可能得到錯誤(你沒有發佈確切的ORA錯誤),因爲你傳遞的是字符串類型值,但是你沒有用硬編碼查詢中的單引號包裝它們。

如果textual_description和for_description其中唯一的字符串類型的列在您的查詢,然後將查詢需要看起來像這樣:

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

儘管不像開放自己的SQL注入那樣糟糕,但以這種方式構建字符串並不是首選方式;-)例如,使用StringBuilder更有效。 – Marged 2015-06-28 18:27:59