2013-03-18 72 views
0

我已經能夠鏈接postgresql和Java。我希望用戶在java中的文本框中輸入名稱,並執行搜索並檢查名稱是否存在於數據庫中。在PostgreSQL中搜索

我迄今爲止代碼:

String hostname=this.hostNameText.getText(); 
try 
{ 
s = connection.createStatement(); 
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = "+hostname; 

rs = s.executeQuery(q); 
}catch(Exception e) 
{ 
System.out.println("Problem in searching the database 1"); 
} 

我得到的問題鏈接表hostdetails。請注意hostdetails包含一個名爲HOSTNAME的字段(以大寫字母表示)。當我運行上面的代碼時,顯示「搜索數據庫1時出現問題」。請幫助我:)

+1

使用e.printstackTrace()並共享堆棧跟蹤。 – 2013-03-18 17:55:43

+0

另外,請記住,Postgresql具有標識符的[case](http://stackoverflow.com/questions/2878248/postgresql-naming-conventions/2878408#2878408)的特定處理。爲避免混淆,最好使用小寫字母來標識標識符(表和字段名稱) – leonbloy 2013-03-18 18:16:00

回答

-1

嘗試使用參數化查詢來防止SQL注入。使用方法如下:

String hostname=this.hostNameText.getText(); 
try 
{ 
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = ?"; //notice change here 

//and use params like this 
PreparedStatement pStmnt = connection.prepareStatement(q); 
pStmnt.setString(1, hostname); 

rs = pStmnt.executeQuery(q); 
}catch(Exception e) 
{ 
//error handling here 
} 
+0

如果在PostgreSQL的列名中包含大寫字母,則需要雙引號。如果您因此而低估了我,請刪除downvote並閱讀PostgreSQL命名約定。事實上,這裏有一篇文章將開始你的方式:http://stackoverflow.com/questions/6331504/omitting-the-double-quote-to-do-query-on-postgresql – 2013-03-18 18:18:36