Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
Thread: writing a SQL statement in Java
07-15-2008, 10:48 PM #1
- Join Date
- Jul 2008
- Falls Chuch, VA
- Thanked 1 Time in 1 Post
writing a SQL statement in Java
I have written the following Sql statement in my java code.
String str = "SELECT ZipCode,State FROM zipcodes WHERE City = '+city+' AND State = '+state+'"; rsZipCodes = oStatement.executeQuery(str);
SELECT ZipCode,State FROM zipcodes WHERE City ='+city+' AND State = '+state+';
But i need the below Sql statement to get the correct output.
SELECT ZipCode,State FROM zipcodes WHERE City = 'TAMPA' AND State ='FL';
Anybody know how to deal with this.
Thanks in Advance.
07-16-2008, 04:35 AM #2
07-16-2008, 01:44 PM #3
Also look into using prepared statements, they are considered more secure and I find them easier to use.
07-16-2008, 03:31 PM #4
- Join Date
- Oct 2007
- Springfield, IL
- Thanked 87 Times in 87 Posts
You have to put strings in quotes. Where you have ('+city+') to concatenate the variable "city" to the string you are building, you need to tell the system that the value of "city" is a literal. Just add a quote before and after it inside of the rest of the string parts.
String str = "SELECT ZipCode,State FROM zipcodes WHERE City = '" + city + "' AND State = '" + state + "'";
making the first part:
"SELECT ZipCode, State FROM zipcodes WHERE City = '"
and the next part:
+ city + "' ...
ending the quotes around the variable. Same thing with the last variable:
"' AND State = '" + state + "'";
BTW, you might use prepared statements which eliminates the confusion of quotes on strings and dates, but if you understand them you don't need it. If you do use it, it would look like this:
Where the sql statement would look like this:Code:PreparedStatement pstmt = this.conn.prepareStatement(SQLStrings.getInsertUserQuery()); pstmt.setString(1, this.loginForm.getJdbcUserName()); pstmt.setString(2, this.loginForm.getUserPassword()); pstmt.setString(3, this.loginForm.getUserID()); pstmt.executeUpdate();
The "?" in the query are substituted to the numbered parameters in the prepared statement.Code:String insertUserQuery = "insert into \"DHSDB2\".\"JV_PERSON\" " + "(\"USERID\", \"PASSWORD\", \"NAME\") " + "values(?, ?, ?)";
...and gladly would he learn and gladly teach
Visit www.LiberalsWin.com for humor and the unique Bush/Obama Approval Polls