2009-02-20 27 views
0

根據用戶的輸入我想從數據庫中選擇記錄。這是我的代碼:如何在網頁中使用where子句時輸入條目?

 
<% 
String jempid=request.getParameter("empid"); 
out.println(jempid); 
int intempid=1223; 
Connection conn=null; 
String url="jdbc:mysql://localhost/employees"; 
Class.forName("com.mysql.jdbc.Driver").newInstance(); 
conn=DriverManager.getConnection(url,"root",""); 
Statement st=conn.createStatement(); 
ResultSet rs=st.executeQuery("select * from empdetails where empnum=jempid"); 
%> 

它引發以下錯誤

javax.servlet.ServletException:值java.sql.SQLException:未知列 'jempid' 在「where子句

+0

他他..沒有代碼是完美的代碼。 – Learning 2009-02-20 05:59:28

+0

在那裏,修正了這個問題。 – paxdiablo 2009-02-20 06:00:39

+0

不能得到你的朋友.. – user67722 2009-02-20 06:02:36

回答

1

,看起來在JSP頁面中像太多的代碼.... 謂曰:

... empnum='"+jempid+"');" ...... 

而且還當你完成一定要CLOS E中的DB過

+0

是的,@rbobby,但與問題無關。 – paxdiablo 2009-02-20 06:10:05

0

試試這個:

ResultSet rs=st.executeQuery(
    "select * from empdetails where empnum=" + jempid); 

你需要把jempid的到字符串,而不是文本 「jempid」。

+0

是的,@ rbobby,但並不真正與手頭的問題相關。我們都知道你不應該允許注射攻擊,但是,如果你想要涵蓋答案是「錯誤的」的每一種方式,他們最終都會成爲10,000字的散文。 – paxdiablo 2009-02-20 06:12:32

3

這是你的選擇語句:

select * from empdetails where empnum=jempid 

jempid是硬編碼,而不是被用作變量。除非您將其更改爲客戶輸入的變量值,否則這將無法使用。

改成:

"select * from empdetails where empnum=" + CleanseUserInput(jempid) 

,你是好去。

0
ResultSet 
    rs=st.executeQuery("select * from empdetails where empnum=" + jempid + ";") 
0
"select * from empdetails where empnum="+jempid 

但你真的想保護這對SQL注入!

5

使用字符串連接構造SQL是一個壞主意 - 你只是打開自己的SQL注入攻擊 - 特別是考慮到你直接從請求中獲得「empid」的值。哎呀!

更好的方法是使用參數化查詢,如下面:

PreparedStatement st=conn.prepareStatement("select * from empdetails where empnum=?"); 
st.setString(1, jempid); 
ResultSet rs=st.executeQuery(); 

您也應該檢查jempid不爲空。

0

與其他響應不同,爲什麼不使用PreparedStatement?

基本上,你必須像這樣的代碼:

PreparedStatement st=conn.prepareStatement("select * from empdetails where empnum=?"); 
st.setString(1, jempId); 
ResultSet rs=st.executeQuery(); 

你應該使用預處理語句的原因是因爲SQL Injection問題。例如,使用您在問題中發佈的代碼,黑客總是可以在您選擇jempid的文本框中輸入「1; delete * from empdetails」。

因此最終查詢形成將是

select * from empdetails where empnum=1;delete * from empdetails 

,這將導致在empdetails所有數據得到刪除。

所以總是使用PreparedStatements!

0

where應該在" "之內有輸入。就像這樣:

"select * from empdetails where empnum = "jempid"; 

因此這應該工作:

ResultSet rs = st.executeQuery("select * from empdetails where empnum=" +"'"+ jempid+"'"); 
1

是有時它拋出例如未知列的錯誤假設我們有臺自行車

因此,可以說,我們有一個像查詢select * from bikes where bikename = hayabusa;

如果你打這個查詢比它可能會引發像未知列中的錯誤,所以你應該照顧最好的辦法是引用你的價值EHICH你是給在其中子句,以便正確的方式去爲SELECT *從bikename ='hayabusa'的自行車;