0

I have been able to link postgresql with java. I want the user to input a name in a text box in java and a search is performed and checks if the name exists in the database.

My code so far:

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

I am getting problem to link to the table hostdetails. Please note that hostdetails contain a field nammed HOSTNAME(in capital letters). When I run the above code, I get "Problem in searching the database 1"is displayed. Kindly please help me:)

user2128318
  • 47
  • 1
  • 5
  • 1
    Use e.printstackTrace() and share stacktrace. – Pradeep Simha Mar 18 '13 at 17:55
  • Also, bear in mind that Postgresql has a particular handling of [case](http://stackoverflow.com/questions/2878248/postgresql-naming-conventions/2878408#2878408) of identifiers. TO avoid confusions, it's best to stick with lowercase for identifiers (table and fields names) – leonbloy Mar 18 '13 at 18:16

1 Answers1

-1

Try using parameterized queries to protect against SQL injection. Use as follows:

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
}   
Robert H
  • 11,520
  • 18
  • 68
  • 110
  • Double quotes are required if you include a capital letter in the column name in PostgreSQL. If you downvoted me for that, please kindly remove the downvote and read up on PostgreSQL naming conventions. In fact, here is a post that will start you on your way: http://stackoverflow.com/questions/6331504/omitting-the-double-quote-to-do-query-on-postgresql – Robert H Mar 18 '13 at 18:18