File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Using prepared statements Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Using prepared statements" Watch "Using prepared statements" New topic

Using prepared statements

Joseph Rudman

Joined: Mar 26, 2006
Posts: 13

I'm creating a web application which displays record stored in an mysql database. I have created a PreparedStatement method as follows:

public static void doPreparedStatements(Connection conn, ResultSet rsClients, int rowInt){

String sql = "UPDATE clients SET firstName = ? WHERE clientID=" +rowInt;
PreparedStatement ps = null;
System.out.println("sql = " +sql);

try {
// Updating the database.
ps = conn.prepareStatement(sql);
ps.setString(1, rsClients.getString("firstName"));
} catch (SQLException sqle) {
System.err.println("Error! Opening connection has failed: " + sqle);

I'm very new to jdbc and sql and I cannot see what is wrong with the sql statement above - it does not error and it does not update the mysql database.

Can anyone see anything wrong with sql.

Any help will be greatly appreciated.

Cheers Joe.
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333
First, I'd write it like this:

Second, there of course needs to be a row that matches in your database.

Third, if you've set autocommit off (somewhere else), which you generally should do, you will need to commit your changes.
[ May 01, 2006: Message edited by: stu derby ]
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333
Oh.. Now that I look at it more closely, I see that you're passing in a ResultSet.

ResultSets are always positioned BEFORE the first row, you have to call to advance the next row.

Also, while I don't think this is a problem you have, keep in mind that re-executing the same statement will close a previous ResultSet.
I agree. Here's the link:
subject: Using prepared statements
It's not a secret anymore!