It's not a secret anymore!*
The moose likes JDBC and the fly likes query writing problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "query writing problem" Watch "query writing problem" New topic
Author

query writing problem

mohammad shadab
Ranch Hand

Joined: Jul 09, 2013
Posts: 33

i am writing an insert query for posgressql but it is not accepting that...it will be very helpfull for me if you suggest the right way........





where stmt is an object of Statement.and my table named(mytable) has the following fields
patient_id integer
patient_name character
patient_type character
when i m running this code there is an exception that""" patient_id does not exist""""
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30123
    
150


This code doesn't pass Java variables to your code. You have two choices:

Option 1 - build the query inserting the variables directly
String qry="insert into mytable(patient_id,patient_name,patient_type)"+"values("+patient_id+",'"+patient_name +"','" +patient_type + "');";

Option 2 - use a PreparedStatement instead of a Statement:
String qry="insert into mytable(patient_id,patient_name,patient_type)"+"values(?,?,?);";

In real application code, you'll want to use option 2 so you don't have to worry about SQL injection where people can mess up your database or hack your application.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
mohammad shadab
Ranch Hand

Joined: Jul 09, 2013
Posts: 33

Jeanne Boyarsky wrote:
This code doesn't pass Java variables to your code. You have two choices:

Option 1 - build the query inserting the variables directly
String qry="insert into mytable(patient_id,patient_name,patient_type)"+"values("+patient_id+",'"+patient_name +"','" +patient_type + "');";

Option 2 - use a PreparedStatement instead of a Statement:
String qry="insert into mytable(patient_id,patient_name,patient_type)"+"values(?,?,?);";

In real application code, you'll want to use option 2 so you don't have to worry about SQL injection where people can mess up your database or hack your application.




thank you jeanne for nice suggestion ...actualy i want to do this without using place holders(prepared statement) approach...i was confuse in appending the variables..thank you again for nice explaination
 
Don't get me started about those stupid light bulbs.
 
subject: query writing problem
 
Similar Threads
PreparedStatement (displaying records)
PreparedStatement and sysdate
Search Query Problem
Verifying Queries
Need to parse StringBuffer