2012-11-28 35 views
-2

這是我的代碼:SQL Java中:其中name =變量

public static List GetList(String myname) { 
    . 
    . 
    ResultSet result = stmt.executeQuery("SELECT * FROM authors WHERE name = ?"); 
    result.setString(myname); 
} 

我想選擇其中name = MYNAME(MYNAME是函數的輸入)。

我也試過類似:

WHERE name = @myname 

,但它不工作:/

回答

6

您沒有設置對結果但對聲明值:

PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM authors WHERE name = ?"); 
pstmt.setString(1, myname); 
ResultSet result = pstmt.executeQuery(); 
-1

試試這個:

ResultSet result = stmt.executeQuery("SELECT * FROM authors WHERE name = " + myname); 
+2

這不是很好的做法。 'PreparedStatement'是推薦的方法。 – reprogrammer

4

嘛,一個更好的方式去是使用PreparedStatement ,以避免SQL Injection: -

PreparedStatement stmt = con.prepareStatement("SELECT * FROM authors WHERE name = ?"); 
stmt.setString(1, myname); 
ResultSet res = stmt.executeQuery(); 

然而,僅僅解決您的問題,您可以使用字符串連接: -

stmt.executeQuery("SELECT * FROM authors WHERE name = '" + myname + "'"); 

1

如果我沒有弄錯,最好在這裏準備好陳述:

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM authors WHERE name = ?"); 
stmt.setString(1, myname); 
ResultSet result = stmt.executeQuery();