2014-04-07 35 views
2

我正在編寫一個網頁,它從表單接收輸入,通過cgi將其發送到java文件,通過sql將輸入插入到數據庫中,然後打印出數據庫。我在使用變量插入數據庫時​​遇到了困難,而且我想知道是否有人能夠幫助我。用Java在SQL中插入變量

String a1Insert = (String)form.get("a1"); 
String a2Insert = (String)form.get("a2"); 

這是我得到我的變量構成的形式(只相信它的作品,還有一羣更後端,但我以前使用過這一點,我知道這是正確獲取變量)。

String dbURL = "jdbc:derby://blah.blahblah.ca:CSE2014;user=blah;password=blarg"; 
    Connection conn = DriverManager.getConnection(dbURL); 
    Statement stmt = conn.createStatement(); 
    stmt.executeUpdate("set schema course"); 
stmt.executeUpdate("INSERT INTO MEMBER VALUES (a1Insert, a2Insert)"); 
stmt.close(); 

這是我試圖插入數據庫的地方。它給我的錯誤:

Column 'A1INSERT' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'A1INSERT' is not a column in the target table. 

如果任何人有這將是可愛的任何想法^^感謝

+0

在http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html和http://www.mkyong.com/jdbc/jdbc-preparestatement-example上可以找到很好的信息。 -insert-a-record/ –

+0

如果你的語法正確 - stmt.executeUpdate(「INSERT INTO MEMBER VALUES('」+ a1Insert +「','」+ a2Insert +「')」); - 那麼它將在技術上起作用,但是如果有人可以操縱a1Insert/s2Insert並將它們設置爲惡意值,則會讓您打開SQL注入攻擊。相反,你應該遵循Nathan提到的PreparedStatement的方法。 –

+0

@NeilCoffey,只是正確的SQL指定了插入語句中的列名。因此,需要將...加入成員(colname1,colname2)值(value1,value2) – jwenting

回答

5

java.sql.Statement不支持的參數,切換到java.sql.PreparedStatement將允許您設置參數。將SQL中的參數名稱替換爲?,然後調用準備語句中的setter方法爲每個參數分配一個值。這看起來像

String sql = "INSERT INTO MEMBER VALUES (?, ?)"; 
PreparedStatement stmt = con.prepareStatement(sql); 
stmt.setString(1, "a1"); 
stmt.setString(2, "a2"); 
stmt.executeUpdate(); 

將執行SQL

INSERT INTO MEMBER VALUES ('a1', 'a2') 

注意參數指標從1開始,而不是0。另請注意,我沒有把雙引號的字符串時, PreparedStatement爲我做了。

或者,您可以繼續使用Statement並在Java代碼中創建您的SQL字符串,但這會引入SQL注入攻擊的可能性。使用PreparedStatement設置參數可以避免這個問題,爲您處理引號;如果它在參數值中找到引號,它將會將其轉義,以便它不會影響它所包含的SQL語句。

Oracle在此處有一個tutorial

+0

提及SQL注入保護+1。 –