Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / Databases / November 2006

Tip: Looking for answers? Try searching our database.

executeUpdate problem [newbie]

Thread view: 
Tomislav - 09 Nov 2006 02:44 GMT
Hi everyone,
i have a problem with the executeUpdate method that is converting a
value of my sql query to null.
When i create an entry in my table it's setting the id field to null. I
debugged it and saw that the "conversion" took place when i come in the
executeUpdate method and i don't really know why and how to manage it.

Here is a sample of the code :
-----------------------------------------------------------------
private static final String TABLE = "T_CATEGORY";
private static final String COLUMNS = "ID, NAME, DESCRIPTION";
...
   public void insert(final PersistentObject object) throws
DuplicateKeyException {
        Connection connection = null;
        Statement statement = null;
        final Category category = (Category) object;

        try {
            // Gets a database connection
            connection = getConnection();
            statement = connection.createStatement();

            // Inserts a Row
            final String sql = "INSERT INTO " + TABLE + "(" + COLUMNS +
") VALUES ('" + category.getId() + "', '" + category.getName() + "','" +
category.getDescription()+"' )";
            statement.executeUpdate(sql);

        } catch (SQLException e) {
            // The data already exists in the database
            if (e.getErrorCode() == DATA_ALREADY_EXIST) {
                throw new DuplicateKeyException();
            } else {
                // A Severe SQL Exception is caught
                displaySqlException(e);
                throw new DataAccessException("Cannot insert data into
the database", e);
            }
        } finally {
            // Close
            try {
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                displaySqlException("Cannot close connection", e);
                throw new DataAccessException("Cannot close the
database connection", e);
            }
        }
    }

------------------------------------------------------------------------------
Thanks for your help.
Tomislav
David Harper - 09 Nov 2006 09:24 GMT
> Hi everyone,
> i have a problem with the executeUpdate method that is converting a
[quoted text clipped - 5 lines]
> Here is a sample of the code :
> -----------------------------------------------------------------
[SNIP]
>         try {
>             // Gets a database connection
[quoted text clipped - 6 lines]
> category.getDescription()+"' )";
>             statement.executeUpdate(sql);
[SNIP]

Putting quotes around values is sometimes a tricky business.  Most
textbooks on JDBC programming recommend the use of prepared statements
for this kind of operation.  Your code would look something like this:

  // Instance variable declaration
  private PreparedStatement pstmtInsert;
  ...
  // In your class's constructor, or the method in which the connection
  // to the database is established
  String sql = "INSERT INTO " + TABLE + "(" + COLUMNS +
    ") VALUES (?,?,?)";
  pstmtInsert = connection.prepareStatement(sql);
  ...
  // Your "insert" method now looks like this ...
  public void insert(final PersistentObject object)
    throws DuplicateKeyException {
        final Category category = (Category) object;

        try {
            // Gets a database connection
            connection = getConnection();
            pstmtInsert.setInt(1, category.getId());
            pstmtInsert.setString(2, category.getName());
            pstmtInsert.setString(3, category.getDescription());

            // Inserts a Row
            int rowcount = pstmtInsert.executeUpdate();

            // "rowcount" is the number of rows inserted.  It should
            // be 1.
        } catch (SQLException e) {
            // Your exception-handling code goes here
        }
    }

By using a prepared statement, you let the JDBC driver deal with the
question of whether the values should be enclosed in quotes.

With some database systems, you gain the additional benefit that the
prepared statement is cached in the server, which avoids the need for
the server to parse every insert statement and which also reduces the
amount of data that needs to be sent across the network.

David Harper
Cambridge, England
Lew - 13 Nov 2006 04:51 GMT
>> Hi everyone,
>> i have a problem with the executeUpdate method that is converting a
[quoted text clipped - 18 lines]
>>             statement.executeUpdate(sql);
> [SNIP]

> Putting quotes around values is sometimes a tricky business.  Most
> textbooks on JDBC programming recommend the use of prepared statements
> for this kind of operation.  Your code would look something like this:
...

> By using a prepared statement, you let the JDBC driver deal with the
> question of whether the values should be enclosed in quotes.
[quoted text clipped - 3 lines]
> the server to parse every insert statement and which also reduces the
> amount of data that needs to be sent across the network.

Could any of the get...() methods return null? An empty String? An empty
object? What are the types of the category object attributes? If any of these
attributes are not of type String, what will its toString() method return for
the String concatenation?

What is the exact string passed in to the executeUpdate() method?

What are the types of the database columns?

Is ID a key column? Primary key? If it were a PK, you would not have a NULL id
in the table, you'd have a rejected INSERT.

If one of the values from a get...() is null, or if one of the corresponding
column types isn't expecting a string value, you'll get unusual results or
exceptions. A PreparedStatement will alert you to these difficulties well
before the execute(), during the setInt(), setString(), etc., calls that set
"?" parameters.

In the real world PreparedStatements add to the security of your db interface
and help catch a few more bugs at compile time rather than run time. For
simple, controlled cases like your example, it's not too wrong to use
Statements as long as you carefully control the pieces that you assemble. JDBC
magic will not guard against data that violate assumed algorithm invariants.

Don't blame the executeUpdate() method first; that's probably not the culprit
and only looking there likely will lead you away from a successful resolution.
Contrary to popular belief, the order is opposite to "blame, in order, the
hardware, the OS, the VM, the library, the driver, your manager, yourself".

- Lew


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.