Top Banner
JDBC FAQ From jGuru Generated Sep 13, 2005 1:37:19 PM Location: http://www.jguru.com/faq/JDBC Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership . What is a database URL? Location: http://www.jguru.com/faq/view.jsp?EID=690 Created: Nov 8, 1999 Modified: 1999-11-24 01:42:34.137 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15) A database URL (or JDBC URL) is a platform independent way of adressing a database. A database/JDBC URL is of the form jdbc:[subprotocol]:[node]/[databaseName] If you are accessing a database called wham on the server yoghurt.jguru.com using the xyz subprotocol, your database URL could be: jdbc:xyz:yoghurt.jguru.com/wham Notice that the ordinary URL is of the form [protocol]://[node]/[path], such as http://www.jguru.com/index.html. The jdbc database URL mimics the ordinary URL, just adding a subprotocol, and - depending on the driver implementation - omitting the double slashes. If the database resides on the same computer node as the java program, the hostname part and the corresponding double slashes of the jdbc can be skipped: jdbc:odbc:wham All standard database URLs should commence with the string jdbc. Comments and alternative answers The IP Port Author: Guillermo Alvarez (http://www.jguru.com/guru/viewbio.jsp?EID=819342), Apr 1, 2002 What happens with the IP port? is JDBC always "listening" by the same port, or we have to define it in the URL? Thanks Re: The IP Port
274
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Jdbc Faq From Jguru

JDBC FAQ From jGuru Generated Sep 13, 2005 1:37:19 PM

Location: http://www.jguru.com/faq/JDBCOwnership: http://www.jguru.com/misc/user-agree.jsp#ownership.

What is a database URL?Location: http://www.jguru.com/faq/view.jsp?EID=690 Created: Nov 8, 1999 Modified: 1999-11-24 01:42:34.137Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

A database URL (or JDBC URL) is a platform independent way of adressing a database. A database/JDBC URL is of the form

jdbc:[subprotocol]:[node]/[databaseName]

If you are accessing a database called wham on the server yoghurt.jguru.com using the xyz subprotocol, your database URL could be:

jdbc:xyz:yoghurt.jguru.com/wham

Notice that the ordinary URL is of the form [protocol]://[node]/[path], such as http://www.jguru.com/index.html. The jdbc database URL mimics the ordinary URL, just adding a subprotocol, and - depending on the driver implementation - omitting the double slashes.

If the database resides on the same computer node as the java program, the hostname part and the corresponding double slashes of the jdbc can be skipped:

jdbc:odbc:wham

All standard database URLs should commence with the string jdbc.

Comments and alternative answers

The IP Port Author: Guillermo Alvarez (http://www.jguru.com/guru/viewbio.jsp?EID=819342), Apr 1, 2002What happens with the IP port? is JDBC always "listening" by the same port, or we have to define it in the URL? Thanks

Re: The IP Port Author: Christian Lugo (http://www.jguru.com/guru/viewbio.jsp?EID=910315), Jun 11, 2002First of all what you call the IP port is the port for the JDBC service on the machine where the database. With IBM DB2 you can set this port to any port (of course any port that is not currently in use) with the command db2jstrt [port_number]. If you are using other DBMS you probably will have a command like that.

Page 2: Jdbc Faq From Jguru

I dont undertand the JDBC URL Author: Efren Lugo (http://www.jguru.com/guru/viewbio.jsp?EID=726052), Jun 12, 2002if my JDBC String looks like: jdbc:oracle:thin:@localhost:1521:sintec

how it would be un URL format??? jdbc:odbc:localhost/sintec

why :odbc?? my RAD need the URL for success. thanks...

View on browser Author: Rati Naren (http://www.jguru.com/guru/viewbio.jsp?EID=990238), Aug 28, 2002Can we use this URL to view some database details over the browser ?

want to know detailed procedure of connecting an MS Access Database to java

Author: Samik Mukherjee (http://www.jguru.com/guru/viewbio.jsp?EID=1063485), Mar 5, 2003I'm using WebSphere 4.0 and trying to connect a MS Access database (called trial.mdb) residing in my machine. Now I want to know how will I write the Database URL in the Websphere Test Environment Control Center's DataSource Configuration Section and how will I mention it in my java code? I have kept the mdb file in the root of my localhost folder. Please tell me what will be the exact URL for it? ( I'm using a Win2000 machine)

Re: want to know detailed procedure of connecting an MS Access Database to java Author: Andrew Vitale (http://www.jguru.com/guru/viewbio.jsp?EID=1178492), Jun 14, 2004Did you get your question answered? I have the same question and would like to find out what answer you found. Thanks,

What types of JDBC drivers exist?Location: http://www.jguru.com/faq/view.jsp?EID=691 Created: Nov 8, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

There are four types of JDBC database driver:

Driver type

Explanation Comment

Page 3: Jdbc Faq From Jguru

code

1The JDBC/ODBC bridge driver

A piece of native C-code that translates a JDBC call to an ODBC call. Use this driver for development, not for industrial-strength application environments. Note that you have to have an ODBC database driver manager + an ODBC database driver installed on the server in addition to the JDBC/ODBC bridge.

2Native API partly java driver

A piece of native C-code that translates a java JDBC call to a native database call level API. Use this driver for development and deployment. Due to its native code, this driver can only be used by Java Applications with full computer access (i.e. not Applets).

3JDBC-Net pure Java driver

A piece of pure java code that translates an incoming JDBC call to an outgoing database Net protocol call (such as SQL*Net). Use this driverfor development and deployment. Flexible and powerful, this driver can be used by any Java component and requires only connect access to work.

4Native protocol pure Java driver

A piece of pure java code that translates an incoming JDBC call to an outgoing database native protocol call (such as Oracle CLI). Use this driver for development and deployment. This driver type is the recommended one for server-side java development unless a type 2 driver has considerable performance advantages.

Comments and alternative answers

Cool stuff really helpful for beginners Author: prasad iyer (http://www.jguru.com/guru/viewbio.jsp?EID=959085), Jul 22, 2002Cool article Its really worth reading. Keep up the good work.

How do I create a database connection?Location: http://www.jguru.com/faq/view.jsp?EID=692 Created: Nov 8, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

The database connection is created in 3 steps: 1. Find a proper database URL (see FAQ on JDBC URL) 2. Load the database driver 3. Ask the Java DriverManager class to open a connection to your

database

In java code, the steps are realized in code as follows:

Page 4: Jdbc Faq From Jguru

1. Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the form jdbc:someSubProtocol://myDatabaseServer/theDatabaseName

2. try {3. Class.forName("my.database.driver");4. }5. catch(Exception ex)6. {7. System.err.println("Could not load database driver:

" + ex);8. }9. 10. Connection conn =

DriverManager.getConnection("a.JDBC.URL", "databaseLogin", "databasePassword");

11.

What is the difference between a Statement and a PreparedStatement?Location: http://www.jguru.com/faq/view.jsp?EID=693 Created: Nov 8, 1999 Modified: 2000-07-24 21:59:08.519Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Short answer:

1. The PreparedStatement is a slightly more powerful version of a Statement, and should always be at least as quick and easy to handle as a Statement.

2. The PreparedStatement may be parametrized.

Longer answer: Most relational databases handles a JDBC / SQL query in four steps:

1. Parse the incoming SQL query 2. Compile the SQL query 3. Plan/optimize the data acquisition path

4. Execute the optimized query / acquire and return data

A Statement will always proceed through the four steps above for each SQL query sent to the database. A PreparedStatement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a PreparedStatement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time.

Code samples

Page 5: Jdbc Faq From Jguru

Statement example

// Assume a database connection, conn.Statement stmnt = null;ResultSet rs = null;try{ // Create the Statement stmnt = conn.createStatement();

// Execute the query to obtain the ResultSet rs = stmnt.executeQuery("select * from aTable");}catch(Exception ex){

System.err.println("Database exception: " + ex);}

PreparedStatement example

// Assume a database connection, conn.PreparedStatement stmnt = null;ResultSet rs = null;try{ // Create the PreparedStatement stmnt = conn.prepareStatement("select * from aTable");

// Execute the query to obtain the ResultSet rs = stmnt.executeQuery();}catch(Exception ex){ System.err.println("Database exception: " + ex);}

Another advantage of the PreparedStatement class is the ability to create an incomplete query and supply parameter values at execution time. This type of query is well suited for filtering queries which may differ in parameter value only:

SELECT firstName FROM employees WHERE salary > 50SELECT firstName FROM employees WHERE salary > 200

To create a parametrized prepared statement, use the following syntax:

// Assume a database connection, conn.PreparedStatement stmnt = null;ResultSet rs = null;try

Page 6: Jdbc Faq From Jguru

{ // Create the PreparedStatement, leaving a '?' // to indicate placement of a parameter. stmnt = conn.prepareStatement( "SELECT firstName FROM employees WHERE salary > ?");

// Complete the statement stmnt.setInt(1, 200);

// Execute the query to obtain the ResultSet rs = stmnt.executeQuery();} catch(Exception ex){ System.err.println("Database exception: " + ex);}

Comments and alternative answers

what should the scope of my PreparedStatement be? Author: Marc Provencher (http://www.jguru.com/guru/viewbio.jsp?EID=1056240), Feb 12, 2003If my logic re-creates the PreparedStatement everytime, do I lose the advantage of the PreparedStatement over the Statement class ? Should I instead try to make the scope of my PreparedStatement reference such that it does not get destroyed? Or is the JDBC driver smart enough to recognize a statement that it has already precompiled, and not recompile it again ?

How prepare statement increasing performance Author: RajaRajan SivaSubramanian (http://www.jguru.com/guru/viewbio.jsp?EID=1206467), Oct 20, 2004Using prepare statement is less expensive 'coz, it pre executes the follwoing steps. Step 1 :Parse the incoming SQL query Step 2 :Compile the SQL query Step 3 :Plan/optimize the data acquisition path Where will be the pre executed steps stored, i.e) in Application server or in DataBaseServer

Prepared Statement execution Author: Adi Grandhi (http://www.jguru.com/guru/viewbio.jsp?EID=1262205), Sep 13, 2005

Hi Lennart , I have couple of doughts regarding the execution of prepared statement. Where do these 4 sequence of steps takes place ? whether at JDBC end or at the Database end ? If the these steps takes place at JDBC level , how does database executes the statements that are parsed/complied by JDBC. Where this data is stored ? Thanks & regards,

Page 7: Jdbc Faq From Jguru

Adi

What is Metadata and why should I use it?Location: http://www.jguru.com/faq/view.jsp?EID=694 Created: Nov 8, 1999 Modified: 1999-11-10 06:22:48.233Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Metadata ('data about data') is information about one of two things: 1. Database information (java.sql.DatabaseMetaData), or 2. Information about a specific ResultSet

(java.sql.ResultSetMetaData).

Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns.

See "Database Metadata Example" and "ResultSet Metadata Example"

What is the advantage of using a PreparedStatement?Location: http://www.jguru.com/faq/view.jsp?EID=720 Created: Nov 8, 1999 Modified: 2000-01-12 17:24:10.873Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

For SQL statements that are executed repeatedly, using a PreparedStatement object would almost always be faster than using a Statement object. This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement.

Typically, PreparedStatement objects are used for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters.

Comments and alternative answers

An interesting article showing at which point PreparedStatements are faster than Statements using OCI and Thin drivers Author: Paul Feaviour (http://www.jguru.com/guru/viewbio.jsp?EID=765383), Feb 20, 2002http://www.onjava.com/pub/a/onjava/excerpt/oraclejdbc_19/index.html?page=2#94197

PreparedStatment is faster than Statement?

Page 8: Jdbc Faq From Jguru

Author: Ming-tzung Dung (http://www.jguru.com/guru/viewbio.jsp?EID=1045313), Jan 10, 2003

At the begging, I had the same idea that using PreparedStatement to execute queries should run faster than the Statement in most cases until I wrote a program to test.

I used the MS-SQL as my DBMS and the JDBC from Microsoft. I randomly fetched 10 records through a huge table. I found that using Statement in fact is faster than the PreparedStatement. In the test program, I also carefully not to close Stament and PreparedStatment objects to make sure that the driver potentially can take advantage of it.

So far, I cannot found any good explation yet. But in the book, "Java Programming with Oracle JDBC", the author has the same test result as me. He did raise the good point of different application scenarios needs different choices.

I will be interested in knowing any explantion or the performance tests.

What is a "dirty read"?Location: http://www.jguru.com/faq/view.jsp?EID=721 Created: Nov 8, 1999 Modified: 2000-01-12 17:24:43.146Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value.

While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.

Comments and alternative answers

But how to deal with the invalid value? Author: Stan Yao (http://www.jguru.com/guru/viewbio.jsp?EID=958738), Jul 21, 2002If after the dirty read, the former transaction rolls back, how to deal with the invalid value from the dirty read? Thanks.

Re: But how to deal with the invalid value? Author: Jon Thorarinsson (http://www.jguru.com/guru/viewbio.jsp?EID=776345), Oct 7, 2002Nothing. By setting the isolation level to READ_UNCOMMITTED you are

Page 9: Jdbc Faq From Jguru

saying that you won't have a problem with reading data that might get rolled back. If this is unacceptable, use a more restrictive isolation level.

Re: But how to deal with the invalid value? Author: Robert White (http://www.jguru.com/guru/viewbio.jsp?EID=1041462), Aug 13, 2003You do what's called an optimistic transaction, defined as follows: write to the database while checking that new data is not be overwritten by using WHERE clauses containing the old data. However note that optimistic transactions can lead to worse performance if many transactions fail.

A good example of this is to timestamp each row in a result set and compare the timestamps from one read to another.

See Java Developer's Journal article here.

Can I make a change to the transaction isolation level in the midst of executing the transaction?Location: http://www.jguru.com/faq/view.jsp?EID=722 Created: Nov 8, 1999 Modified: 2000-06-16 08:12:08.777Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

Although you may want to avoid it, you can change the transaction isolation level in the midst of executing a transaction. However, this will immediately freeze all the changes made upto that point, as a commit() is automatically invoked.

At a glance, how does the Java Database Connectivity (JDBC) work?Location: http://www.jguru.com/faq/view.jsp?EID=1180 Created: Nov 21, 1999 Modified: 2000-06-02 06:34:20.199Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

A: The JDBC is used whenever a Java application should communicate with a relational database for which a JDBC driver exists. JDBC is part of the Java platform standard; all visible classes used in the Java/database communication are placed in package java.sql.

JDBC as a mediator between the Java Application and the database

Main JDBC classes:

DriverManager. Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that

Page 10: Jdbc Faq From Jguru

recognizes a certain subprotocol under jdbc (such as odbc or dbAnywhere/dbaw) will be used to establish a database Connection.

Driver. The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.

Connection. Interface with all methods for contacting a database Statement. Encapsulates an SQL statement which is passed to the

database to be parsed, compiled, planned and executed. ResultSet. The answer/result from a statement. A ResultSet is a fancy 2D

list which encapsulates all outgoing results from a given SQL query.

JDBC classes normally seen and used by the developer.Comments and alternative answers

suppose there are 1000 employee in my company.If i... Author: Arti Arti (http://www.jguru.com/guru/viewbio.jsp?EID=107329), Mar 16, 2001suppose there are 1000 employee in my company.If i use prepared statement in the Loop (from i=0 to 1000) to update their salary field where deptcode=XXX ,then for every iteration this statement goes to the database to check the record matching to the query.This will be really an overhead of prepared statement. CAN u suggent some way to do that so that for every iteration we don't have to go to the database?

Re: suppose there are 1000 employee in my company.If i... Author: scott carlson (http://www.jguru.com/guru/viewbio.jsp?EID=428708), May 31, 2001Are you saying you are creating the PreparedStatement inside the loop... Yes that will be tremendous overhead; it is also the exact opposite of what you want. Instead create it once, and use it over and over... // pSeudo codePreparedStatment ps = new PS();foreach employee{ps.setField(1, "Amount");conn.execute(ps);}

Page 11: Jdbc Faq From Jguru

Re: Re: suppose there are 1000 employee in my company.If i... Author: Arti Arti (http://www.jguru.com/guru/viewbio.jsp?EID=107329), Jun 4, 2001In such cases we can use batch updates which has come up in JDBC API 2.0.We can append sqls to be executed in a loop in a statement and then execute after the loop.In this case the transaction will be completed in one go.By using this we can also reduce network traffic also. Look for the JDBC API 2.0 in java doc 1.2 or later for examples.

How do I check what table-like database objects (table, view, temporary table, alias) are present in a particular database?Location: http://www.jguru.com/faq/view.jsp?EID=1181 Created: Nov 21, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Use java.sql.DatabaseMetaData to probe the database for metadata. Use the getTables method to retrieve information about all database objects (i.e. tables, views, system tables, temporary global or local tables or aliases). The exact usage is described in the code below.

NOTE! Certain JDBC drivers throw IllegalCursorStateExceptions when you try to access fields in the ResultSet in the wrong order (i.e. not consecutively). Thus, you should not change the order in which you retrieve the metadata from the ResultSet.

public static void main(String[] args) throws Exception{ // Load the database driver - in this case, we // use the Jdbc/Odbc bridge driver. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

// Get DatabaseMetaData DatabaseMetaData dbmd = conn.getMetaData();

// Get all dbObjects. Replace the last argument in the getTables // method with objectCategories below to obtain only database // tables. (Sending in null retrievs all dbObjects). String[] objectCategories = {"TABLE"}; ResultSet rs = dbmd.getTables(null, null, "%", null);

// Printout table data while(rs.next()) { // Get dbObject metadata String dbObjectCatalog = rs.getString(1); String dbObjectSchema = rs.getString(2); String dbObjectName = rs.getString(3); String dbObjectType = rs.getString(4);

Page 12: Jdbc Faq From Jguru

// Printout System.out.println("" + dbObjectType + ": " + dbObjectName); System.out.println(" Catalog: " + dbObjectCatalog); System.out.println(" Schema: " + dbObjectSchema); }

// Close database resources rs.close(); conn.close();}

How do I check what table types exist in a database?Location: http://www.jguru.com/faq/view.jsp?EID=1182 Created: Nov 21, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Use the getTableTypes method of interface java.sql.DatabaseMetaData to probe the database for table types. The exact usage is described in the code below.

public static void main(String[] args) throws Exception{ // Load the database driver - in this case, we // use the Jdbc/Odbc bridge driver. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

// Get DatabaseMetaData DatabaseMetaData dbmd = conn.getMetaData();

// Get all table types. ResultSet rs = dbmd.getTableTypes();

// Printout table data while(rs.next()) { // Printout System.out.println("Type: " + rs.getString(1)); }

// Close database resources rs.close(); conn.close();}

How can I investigate the physical structure of a database? Location: http://www.jguru.com/faq/view.jsp?EID=1183 Created: Nov 21, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

The JDBC view of a database internal structure can be seen in the image below.

Page 13: Jdbc Faq From Jguru

Several database objects (tables, views, procedures etc.) are contained within a Schema.

Several schema (user namespaces) are contained within a catalog. Several catalogs (database partitions; databases) are contained within a

DB server (such as Oracle, MS SQL

The JDBC view of a database internal structure.

The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:

public static void main(String[] args) throws Exception{ // Load the database driver - in this case, we // use the Jdbc/Odbc bridge driver. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

// Get DatabaseMetaData DatabaseMetaData dbmd = conn.getMetaData();

// Get all Catalogs System.out.println("\nCatalogs are called '" + dbmd.getCatalogTerm() + "' in this RDBMS."); processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());

Page 14: Jdbc Faq From Jguru

// Get all Schemas System.out.println("\nSchemas are called '" + dbmd.getSchemaTerm() + "' in this RDBMS."); processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());

// Get all Table-like types System.out.println("\nAll table types supported in this RDBMS:"); processResultSet("Table type", dbmd.getTableTypes());

// Close the Connection conn.close(); }

public static void processResultSet(String preamble, ResultSet rs) throws SQLException { // Printout table data while(rs.next()) { // Printout System.out.println(preamble + ": " + rs.getString(1)); }

// Close database resources rs.close();}

How do I extract SQL table column type information? Location: http://www.jguru.com/faq/view.jsp?EID=1184 Created: Nov 21, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Use the getColumns method of the java.sql.DatabaseMetaData interface to investigate the column type information of a particular table. Note that most arguments to the getColumns method (pinpointing the column in question) may be null, to broaden the search criteria. A code sample can be seen below:

public static void main(String[] args) throws Exception{ // Load the database driver - in this case, we // use the Jdbc/Odbc bridge driver. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

// Get DatabaseMetaData DatabaseMetaData dbmd = conn.getMetaData();

// Get all column types for the table "sysforeignkeys", in schema // "dbo" and catalog "test". ResultSet rs = dbmd.getColumns("test", "dbo", "sysforeignkeys", "%");

Page 15: Jdbc Faq From Jguru

// Printout table data while(rs.next()) { // Get dbObject metadata String dbObjectCatalog = rs.getString(1); String dbObjectSchema = rs.getString(2); String dbObjectName = rs.getString(3); String dbColumnName = rs.getString(4); String dbColumnTypeName = rs.getString(6); int dbColumnSize = rs.getInt(7); int dbDecimalDigits = rs.getInt(9); String dbColumnDefault = rs.getString(13); int dbOrdinalPosition = rs.getInt(17); String dbColumnIsNullable = rs.getString(18);

// Printout System.out.println("Col(" + dbOrdinalPosition + "): " + dbColumnName + " (" + dbColumnTypeName +")"); System.out.println(" Nullable: " + dbColumnIsNullable + ", Size: " + dbColumnSize); System.out.println(" Position in table: " + dbOrdinalPosition + ", Decimal digits: " + dbDecimalDigits); }

// Free database resources rs.close(); conn.close(); }

How do I extract the SQL statements required to move all tables and views from an existing database to another database? Location: http://www.jguru.com/faq/view.jsp?EID=1185 Created: Nov 21, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Boy, this is a big one. :) The operation is performed in 9 steps:

1. Open a connection to the source database. Use the DriverManager class.

2. Find the entire physical layout of the current database. Use the DatabaseMetaData interface.

3. Create DDL SQL statements for re-creating the current database structure. Use the DatabaseMetaData interface.

4. Build a dependency tree, to determine the order in which tables must be setup. Use the DatabaseMetaData interface.

5. Open a connection to the target database. Use the DriverManager class.

6. Execute all DDL SQL statements from (3) in the order given by (4) in the target database to setup the table and view structure. Use the PreparedStatement interface.

7. If (6) threw exceptions, abort the entire process.

Page 16: Jdbc Faq From Jguru

8. Loop over all tables in the physical structure to generate DML SQL statements for re-creating the data inside the table. Use the ResultSetMetaData interface.

9. Execute all DML SQL statements from (8) in the target database.

How do I find all database stored procedures in a database?Location: http://www.jguru.com/faq/view.jsp?EID=1186 Created: Nov 21, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.

public static void main(String[] args) throws Exception{ // Load the database driver - in this case, we // use the Jdbc/Odbc bridge driver. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

// Get DatabaseMetaData DatabaseMetaData dbmd = conn.getMetaData();

// Get all procedures. System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS."); ResultSet rs = dbmd.getProcedures(null, null, "%");

// Printout table data while(rs.next()) { // Get procedure metadata String dbProcedureCatalog = rs.getString(1); String dbProcedureSchema = rs.getString(2); String dbProcedureName = rs.getString(3); String dbProcedureRemarks = rs.getString(7); short dbProcedureType = rs.getShort(8);

// Make result readable for humans String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult ? "No Result" : "Result");

// Printout System.out.println("Procedure: " + dbProcedureName + ", returns: " + procReturn); System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog + " | " + dbProcedureSchema + "]"); System.out.println(" Comments: " + dbProcedureRemarks); }

Page 17: Jdbc Faq From Jguru

// Close database resources rs.close(); conn.close();}

How can I investigate the parameters to send into and receive from a database stored procedure?Location: http://www.jguru.com/faq/view.jsp?EID=1187 Created: Nov 21, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Use the method getProcedureColumns in interface DatabaseMetaData to probe a stored procedure for metadata. The exact usage is described in the code below.

NOTE! This method can only discover parameter values. For databases where a returning ResultSet is created simply by executing a SELECT statement within a stored procedure (thus not sending the return ResultSet to the java application via a declared parameter), the real return value of the stored procedure cannot be detected. This is a weakness for the JDBC metadata mining which is especially present when handling Transact-SQL databases such as those produced by SyBase and Microsoft.

public static void main(String[] args) throws Exception{ // Load the database driver - in this case, we // use the Jdbc/Odbc bridge driver. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

// Get DatabaseMetaData DatabaseMetaData dbmd = conn.getMetaData();

// Get all column definitions for procedure "getFoodsEaten" in // schema "testlogin" and catalog "dbo". System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS."); ResultSet rs = dbmd.getProcedureColumns("test", "dbo", "getFoodsEaten", "%");

// Printout table data while(rs.next()) { // Get procedure metadata String dbProcedureCatalog = rs.getString(1); String dbProcedureSchema = rs.getString(2); String dbProcedureName = rs.getString(3); String dbColumnName = rs.getString(4); short dbColumnReturn = rs.getShort(5); String dbColumnReturnTypeName = rs.getString(7); int dbColumnPrecision = rs.getInt(8); int dbColumnByteLength = rs.getInt(9);

Page 18: Jdbc Faq From Jguru

short dbColumnScale = rs.getShort(10); short dbColumnRadix = rs.getShort(11); String dbColumnRemarks = rs.getString(13);

// Interpret the return type (readable for humans) String procReturn = null;

switch(dbColumnReturn) { case DatabaseMetaData.procedureColumnIn: procReturn = "In"; break; case DatabaseMetaData.procedureColumnOut: procReturn = "Out"; break; case DatabaseMetaData.procedureColumnInOut: procReturn = "In/Out"; break; case DatabaseMetaData.procedureColumnReturn: procReturn = "return value"; break; case DatabaseMetaData.procedureColumnResult: procReturn = "return ResultSet"; default: procReturn = "Unknown"; }

// Printout System.out.println("Procedure: " + dbProcedureCatalog + "." + dbProcedureSchema + "." + dbProcedureName); System.out.println(" ColumnName [ColumnType(ColumnPrecision)]: " + dbColumnName + " [" + dbColumnReturnTypeName + "(" + dbColumnPrecision + ")]"); System.out.println(" ColumnReturns: " + procReturn + "(" + dbColumnReturnTypeName + ")"); System.out.println(" Radix: " + dbColumnRadix + ", Scale: " + dbColumnScale); System.out.println(" Remarks: " + dbColumnRemarks); }

// Close database resources rs.close(); conn.close();}

What properties should I supply to a database driver in order to connect to a database?Location: http://www.jguru.com/faq/view.jsp?EID=1323 Created: Nov 29, 1999 Modified: 2000-05-30 08:38:01.335Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Most JDBC drivers should accept 3 properties:

Page 19: Jdbc Faq From Jguru

user password hostname

However, a JDBC driver may accept an arbitrary number of properties thrown at it. Drivers can be interrogated for their supported properties using the DriverPropertyInfo metadata class. Most drivers will also contain documentation which should specify all properties and their meaning for creating the jdbc database connection.

NOTE! The JDBC/ODBC bridge driver does not properly return an array of DriverPropertyInfo objects, but instead throws a NullPointerException. Other database drivers work better in this respect.

public static void printPropertyInfo(Driver aDriver, String jdbcURL, Properties daProps) throws Exception { // Get the DriverPropertyInfo of the given driver DriverPropertyInfo[] props = aDriver.getPropertyInfo(jdbcURL, daProps);

// If the driver is poorly implemented, // a null object may be returned. if(props == null) return;

System.out.println("Resolving properties for: " + aDriver.getClass().getName());

// List all properties. for(int i = 0; i props.length; i++) { // Get the property metadata String propName = props[i].name; String[] propChoices = props[i].choices; boolean req = props[i].required; String propDesc = props[i].description;

// Printout System.out.println("" + propName + " (Req: " + req + ")"); if(propChoices == null) { System.out.println(" No choices."); } else { System.out.print(" Choices: "); for(int j = 0; j propChoices.length; j++) { System.out.print(" " + propChoices[j]); } }

Page 20: Jdbc Faq From Jguru

System.out.println(" Desc: " + propDesc); } } }

I have the choice of manipulating database data using a byte[] or a java.sql.Blob. Which has best performance?Location: http://www.jguru.com/faq/view.jsp?EID=1324 Created: Nov 29, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

java.sql.Blob, since it does not extract any data from the database until you explicitly ask it to. The Java platform 2 type Blob wraps a database locator (which is essentially a pointer to byte). That pointer is a rather large number (between 32 and 256 bits in size) - but the effort to extract it from the database is insignificant next to extracting the full blob content. For insertion into the database, you should use a byte[] since data has not been uploaded to the database yet. Thus, use the Blob class only for extraction.

Conclusion: use the java.sql.Blob class for extraction whenever you can.

Comments and alternative answers

EJB CMP and Blob Author: Kris Bo (http://www.jguru.com/guru/viewbio.jsp?EID=1013463), Oct 17, 2002

In EJB CMP i can't map one parameter to more than one type (i can choose java.sql.Blob or byte[] - I would like use Blob

How do I extract a BLOB from a database?Location: http://www.jguru.com/faq/view.jsp?EID=1325 Created: Nov 29, 1999 Modified: 2002-03-23 20:02:48.66Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in the database. You extract the data in two steps:

1. Call the getBlob method of the Statement class to retrieve a java.sql.Blob object

2. Call either getBinaryStream or getBytes in the extracted Blob object to retrieve the java byte[] which is the Blob object.

Note that a Blob is essentially a pointer to a byte array (called LOCATOR in database-talk), so the java.sql.Blob object essentially wraps a byte pointer. Thus, you must extract all data from the database blob before calling commit or

<div align="center">

Page 21: Jdbc Faq From Jguru

private void runGetBLOB() { try { // Prepare a Statement: PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");

// Execute ResultSet rs = stmnt.executeQuery();

while(rs.next()) { try { // Get as a BLOB Blob aBlob = rs.getBlob(1); byte[] allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length()); } catch(Exception ex) { // The driver could not handle this as a BLOB... // Fallback to default (and slower) byte[] handling byte[] bytes = rs.getBytes(1); } }

// Close resources rs.close(); stmnt.close();

} catch(Exception ex) { this.log("Error when trying to read BLOB: " + ex); }}

</div> Comments and alternative answers

getBytes() position starts with 1. Author: Joseph Shelby (http://www.jguru.com/guru/viewbio.jsp?EID=26292), Apr 30, 2001The specification (javadocs) of java.sql.Blob.getBytes() states: Parameters: pos - the ordinal position of the first byte in the BLOB value to be extracted; the first byte is at position 1

Seems much of jdbc is designed for database guys who think the world starts with 1, rather than java/c/c++ programmers who know better... ;-) --Joe

Re: getBytes() position starts with 1.

Page 22: Jdbc Faq From Jguru

Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Mar 23, 2002Thanks, Joe. I have corrected the code to start at 1. And, yes, most JDBC origins are at 1 rather than zero as you point out.

not working properly.. Author: Erin Walter (http://www.jguru.com/guru/viewbio.jsp?EID=523020), Oct 17, 2001the blob is being inserted as follows: insert into The_Table values( utl_raw.concat('11111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111')); however, when I perform blob.length() and blob.getBytes() on the blob it does not turn out correct. It gives the incorrect length and incorrect amount of Bytes... I thought it would take each group of 8 bits and put it into a byte, but, it is not doing that. How exactly does it split it into bytes and get the length? Am I inserting it incorrectly for the java.sql.blob functions to handle it?

Re: not working properly.. Author: Enrico Leder (http://www.jguru.com/guru/viewbio.jsp?EID=876241), May 13, 2002I have the same problem. Have you solved it???? Thank you very much in advance.

Re[2]: not working properly.. Author: Bigapple Hoe (http://www.jguru.com/guru/viewbio.jsp?EID=912158), Jun 12, 2002Retrieving BLOB Data

I have a example given below shows a method that retrieves an array of bytes from the database.

Maybe, it will be useful for u. : )

------------------------------------------------------------

import java.io.*;import java.sql.*;

...

public byte[] selectBlob( int rowid ) {

Page 23: Jdbc Faq From Jguru

// In this example I'm assuming there's an open, active// Connection instance called 'con'.

// This examples uses an imaginary SQL table of the // following form://// CREATE TABLE blobs (// ROWID INT NOT NULL,// ROWDATA BLOB,//// PRIMARY KEY (rowid)// );

try {

Statement sment = con.createStatement();

String sql = "SELECT rowid, rowdata FROM blobs WHERE rowid = " + rowid;

ResultSet rs = sment.executeQuery(sql);

byte[] returndata = null;

if ( rs.next() ) {

try {

// The ByteArrayOutputStream buffers all bytes written to it// until we call getBytes() which returns to us an // array of bytes:ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);

// Create an input stream from the BLOB column. // By default, rs.getBinaryStream()// returns a vanilla InputStream instance. // We override this for efficiency// but you don't have to:BufferedInputStream bis = new BufferedInputStream( rs.getBinaryStream("fieldblob") );

// A temporary buffer for the byte data:byte bindata[1024];

// Used to return how many bytes are read with each read() of the input stream:int bytesread = 0;

// Make sure its not a NULL value in the column:if ( !rs.wasNull() ) {

if ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 ) {

// Write out 'bytesread' bytes to the writer instance:baos.write(bindata,0,bytesread);

Page 24: Jdbc Faq From Jguru

} else {

// When the read() method returns -1 we've hit the end of // the stream,// so now we can get our bytes out of the writer object:returndata = baos.getBytes();

}}

// Close the binary input stream:bis.close();

} catch ( IOException ioe ) {System.err.println("Problem retrieving binary data: " + ioe);} catch ( ClassNotFoundException cnfe ) {System.err.println("Problem retrieving binary data: " + cnfe);}}

rs.close();sment.close();

} catch ( SQLException se ) {System.err.println("Couldn't retrieve binary data: " + se);} finally {con.close();}

return returndata;}

Getting java.io.IOException: not in streaming mode Author: Sudhir Byna (http://www.jguru.com/guru/viewbio.jsp?EID=938092), Jul 4, 2002Hi I m getting the exception when I m trying to read a blob using the above method. Pls find the stack trace below. java.io.IOException: not in streaming mode at oracle.jdbc.dbaccess.DBError.SQLToIOException(DBError.java:477) at oracle.jdbc.driver.OracleInputStream.needBytes(OracleInputStream.java:86) at oracle.jdbc.driver.OracleBufferedStream.read(OracleBufferedStream.java:108) at oracle.jdbc.driver.OracleBufferedStream.read(OracleBufferedStream.java:91) Is this due to multithreading??

Re[3]: not working properly.. Author: akshay Bhatt (http://www.jguru.com/guru/viewbio.jsp?EID=1157941), Mar 27, 2004hey chck out aksh3.com

Page 25: Jdbc Faq From Jguru

Re[3]: not working properly.. Author: B Satish (http://www.jguru.com/guru/viewbio.jsp?EID=1159593), Apr 2, 2004Hey if i compile your code i got 3 error. can you please ans me 1) ']' expected byte bindata[1024]; 2)location: class java.io.ByteArrayOutputStream returndata = bao s.getBytes(); ^ 3)cannot resolve symbol return returndata;

I have the choice of manipulating database data using a String or a java.sql.Clob. Which has best performance?Location: http://www.jguru.com/faq/view.jsp?EID=1326 Created: Nov 29, 1999 Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

java.sql.Clob, since it does not extract any data from the database until you explicitly ask it to. The Java platform 2 type Clob wraps a database locator (which is essentially a pointer to char). That pointer is a rather large number (between 32 and 256 bits in size) - but the effort to extract it from the database is insignificant next to extracting the full Clob content. For insertion into the database, you should use a String since data need not been downloaded from the database. Thus, use the Clob class only for extraction.

Conclusion: Unless you always intend to extract the full textual data stored in the particular table cell, use the java.sql.Clob class for extraction whenever you can.

Which is the preferred collection class to use for storing database result sets?Location: http://www.jguru.com/faq/view.jsp?EID=2286 Created: Dec 9, 1999 Modified: 2000-07-30 09:48:38.772Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

When retrieving database results, the best collection implementation to use is the LinkedList. The benefits include:

Retains the original retrieval order Has quick insertion at the head/tail Doesn't have an internal size limitation like a Vector where when the

size is exceeded a new internal structure is created (or you have to find out size beforehand to size properly)

Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized

Basically:

ResultSet result = stmt.executeQuery("...");List list = new LinkedList();while(result.next()) { list.add(result.getString("col")); } If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size,

Page 26: Jdbc Faq From Jguru

though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

Where can I find a comprehensive list of JDBC drivers, including the databases they support?Location: http://www.jguru.com/faq/view.jsp?EID=4541 Created: Jan 11, 2000 Modified: 2000-05-09 11:17:26.28Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

Sun maintains a fairly current list of JDBC drivers that support the JDBC 2.x and JDBC 1.x APIs, at:

http://industry.java.sun.com/products/jdbc/drivers

Comments and alternative answers

You can also find another list at http://ourworld.... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 14, 2000You can also find another list at http://ourworld.compuserve.com/homepages/Ken_North/jdbcvend.htm.

Do I need to commit after an INSERT call in JDBC or does JDBC do it automatically in the DB?Location: http://www.jguru.com/faq/view.jsp?EID=4756 Created: Jan 12, 2000 Modified: 2000-01-12 19:01:36.755Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

If your autoCommit flag (managed by the Connection.setAutoCommit method) is false, you are required to call the commit() method - and vice versa.Comments and alternative answers

When you open a connection to a database, the default... Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10), May 29, 2000

When you open a connection to a database, the default JDBC behavior is to automatically commit each SQL statement after execution.

To change this behavior, and to execute multiple SQL statements as part of a transaction, you have to invoke the setAutoCommit(false) method on your Connection object. If auto commit is false, then SQL statements won't be committed until you invoke the commit() method on the connection. You also have the option of invoking the rollback() method, to rollback the database changes since the previous commit (or since the opening of the connection, if there was no previous commit).

If the underlying database doesn't support transactions, then all SQL statements

Page 27: Jdbc Faq From Jguru

will be committed after execution, regardless of whether you have set auto commit or not. See your database vendor's documentation and your JDBC driver's documentation for detailed information about what features are supported in your specific case.

How can I retrieve only the first n rows, second n rows of a database using a particular WHERE clause ? For example, if a SELECT typically returns a 1000 rows, how do first retrieve the 100 rows, then go back and retrieve the next 100 rows and so on ? Location: http://www.jguru.com/faq/view.jsp?EID=4757 Created: Jan 12, 2000 Modified: 2000-01-12 19:01:57.831Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Use the Statement.setFetchSize method to indicate the size of each database fetch. Note that this method is only available in the Java 2 platform. For Jdk 1.1.X and Jdk 1.0.X, no standardized way of setting the fetch size exists. Please consult the Db driver manual.Comments and alternative answers

How can I design my servlet so that query results get... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Sep 8, 2000How can I design my servlet so that query results get displayed on several pages, like the results of a search engine? shows another way to spread your results over multiple pages.

I have a question about setFetchSize Author: Jeason Zhao (http://www.jguru.com/guru/viewbio.jsp?EID=1037417), Dec 13, 2002If i want to fetch 100 rows first and then begin retrieve data normally.is the statement listed below correcttly?   myResultSet.setFetchSize(100);   if(!myResultSet.fecth())     return false;   myResultSet.setFetchSize(1);   while(myResultSet.fetch())   {     //do something.  }BTW :If u want to retrieve the first n rows only,u can use the sql clause defined by special provider.such as "limit " to mysql . "fetch frist n rows only " to db2 and "rownum <= n" to oracle.

I have a weak english.and i am so weak.

Page 28: Jdbc Faq From Jguru

Need more explanation Author: Tasneem Abbasi (http://www.jguru.com/guru/viewbio.jsp?EID=1100937), Jul 12, 2003Can you explain this in detail. using setFetchSize if i get the first 100 rows then how do i get next 100 rows ?

Re: Need more explanation Author: Amol Umate (http://www.jguru.com/guru/viewbio.jsp?EID=317564), Aug 22, 2003The setFetchSize only provides the HINT to the jdbc driver to fetch the data in batches. It completely depends on the vendor implemetation. Assume if you have 1000 rows to be fetched and you set the fetchsize as 100. The jdbc driver will bring all the 1000 records but in batch of 100 and you don't have to change your implementation. when you reach 100th row and say resultset.next(), the jdbc driver will pull the next batch and you will get the 101st row like you do in the normal jdbc call. I hope this will clear your doubt (not sure will clear the problem or not).

What does ResultSet actually contain? Is it the actual data of the result or some links to databases? If it is the actual data then why can't we access it after connection is closed?Location: http://www.jguru.com/faq/view.jsp?EID=5053 Created: Jan 15, 2000 Modified: 2000-01-16 10:09:17.436Author: Sameer Tyagi (http://www.jguru.com/guru/viewbio.jsp?EID=4381)

A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns.

For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an oracle database it actually returns a cursor in the databse. The oracle cursor can however be processed like a ResultSet would be from the client.

Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process. Comments and alternative answers

What does ResultSet actually contain? Is it the actual data of the result or some links to databases? If it is the actual data Author: Parag Bharambe (http://www.jguru.com/guru/viewbio.jsp?EID=453237), Jul 12, 2001I agree with that. But autually cursor is just a view of underlying Data. It need a connection to view the data from DBMS. Once a connection is closed cursor is not able to view the data. This is reason why you caanot view the Data once a connection is closed. Am I right? If not please feel free to give ur sueeestion. Parag

Page 29: Jdbc Faq From Jguru

How can I make batch updates using JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=5079 Created: Jan 15, 2000 Modified: 2000-01-15 21:06:08.419Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

One of the more advanced features of JDBC 2.0 is the ability to submit multiple update statements to the database for processing as a single unit. This batch updating can be significantly more efficient compared to JDBC 1.0, where each update statement has to be executed separately.

Consider the following code segment demonstrating a batch update:

try {dbCon.setAutoCommit(false);

Statement stmt= dbCon.createStatement();stmt.addBatch("INSERT INTO bugs "+ "VALUES (1007, 'Server stack overflow', 1,2,{d '1999-01-01'})");stmt.addBatch("INSERT INTO bugs "+ "VALUES (1008,'Cannot load DLL', 3,1,{d '1999-01-01'})");stmt.addBatch("INSERT INTO bugs "+ "VALUES (1009,'Applet locks up',2,2,{d '1999-01-01'})");

int[] updCnt = stmt.executeBatch();dbCon.commit();

} catch (BatchUpdateException be) {

//handle batch update exceptionint[] counts = be.getUpdateCounts();for (int i=0; I counts.length; i++) {

System.out.println("Statement["+i+"] :"+counts[i]);}dbCon.rollback();

}catch (SQLException e) {

//handle SQL exceptiondbCon.rollback();

}

Before carrying out a batch update, it is important to disable the auto-commit mode by calling setAutoCommit(false). This way, you will be able to rollback the batch transaction in case one of the updates fail for any reason. When the Statement object is created, it is automatically associated a "command list", which is initially empty. We then add our SQL update statements to this command list, by making successive calls to the addBatch() method. On calling executeBatch(), the entire command list is sent over to the database, and are then executed in the order they were added to the list. If all the commands in the list are executed successfully, their corresponding update counts are returned as an array of integers. Please note that you always have to clear the existing batch by calling clearBatch() before creating a new one.

If any of the updates fail to execute within the database, a BatchUpdateException is thrown in response to it. In case there is a problem in returning the update counts of each SQL statement, a SQLException will be thrown to indicate the error.

Page 30: Jdbc Faq From Jguru

Comments and alternative answers

Hi, This is an interesting article. I would appr... Author: Srinivas Gamini (http://www.jguru.com/guru/viewbio.jsp?EID=3704), Jan 17, 2000Hi, This is an interesting article. I would appreciate, if you could tell me which jdbc driver will support this feature. I tried this feature with Oracle database and 8.1.6 sdk driver but unfortunately it is giving errors like feature is not implemented... Thanks in advance. Gamini [email protected]

HI please let me know which verstion of Oracle supports Bach updates This is an interesting article. I would appr... Author: Gopi ch (http://www.jguru.com/guru/viewbio.jsp?EID=463010), Aug 27, 2001Please let me know.which version of Oracle Jdbc Thni driver supports bach updates.appreciated your earliest Response. Regards Gopi

DB2 JDBC2 Batch Update problems Author: Fazl Rahman (http://www.jguru.com/guru/viewbio.jsp?EID=421751), Jul 11, 2001Thanks for that. I'd like to see some feedback from people who had problems making the batch update work. The sun tutorial describes some reasons why the batch update api may throw either the SQLException or it's derivative BatchUpdateException (see http://java.sun.com/docs/books/tutorial/jdbc/jdbc2dot0/batchupdates.html) but I'm getting a DB2Exception complaining about the server not talking on a socket.. which makes me wonder if the DB2 JDBC2 driver knows about the executeBatch() business. Any comments cc:-d direct to me appreciated folks thanks. (mailto:[email protected])

Query if Batch Update is supported Author: Fazl Rahman (http://www.jguru.com/guru/viewbio.jsp?EID=421751), Jul 11, 2001Here is a link that shows how you can query the driver to see if batch updates are supported *before* you try to use them :-) http://developer.java.sun.com/developer/onlineTraining/Database/JDBC20Intro/exercises.html#M11 From this page you can also reach what looks like a very good short course on using JDBC. HTH etc.

DB2 ExecuteBatch problems Author: Raghu Bala (http://www.jguru.com/guru/viewbio.jsp?EID=503647), Sep 25, 2001Anyone knowhow to get executeBatch to work with Db2 7 on Windows ? Always fails on the addBatch en route to executeBatch. RB

Re: DB2 ExecuteBatch problems Author: David McMillan (http://www.jguru.com/guru/viewbio.jsp?

Page 31: Jdbc Faq From Jguru

EID=1049840), Jan 23, 2003Make sure that you have run the script "usejdbc2" under the SQLLIB/java12 folder on the machine that is running the java code. jdbc1 version of db2java.zip doesn't support the batch updates. This script will copy the jdbc1.2 version into the sqllib/java folder.

preparedStatement using placeholder Author: manoj kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1124261), Oct 27, 2003String sql3 = "UPDATE dept_audit SET cnt_emp = nvl (cnt_emp,0) + 1 WHERE deptno = ?"; PreparedStatement pstmt3 = conn.prepareStatement(sql3); String a = txtfiled_deptno(); pstmt1.setInt(1, a); pstmt1.executeQuery(); giving errors ,I tried a lot. reply at earliest.

Re: preparedStatement using placeholder Author: Muthukumaran Mohan (http://www.jguru.com/guru/viewbio.jsp?EID=1124512), Oct 28, 2003Hi Manoj, PreparedStatement you declared is pstmt3. But you are using pstmt1 for setting parameter and executing query. change pstmt1 to pstmt3. It will solve the problem. - MK

batch updates Author: venkata kumar merupula (http://www.jguru.com/guru/viewbio.jsp?EID=1179305), Jun 16, 2004this is very interesting concept and very useful when we update multiple rows at a time.but this is not support all the drivers .I think this is support oracle 4th driver. i want some more information about batch updates in jdbc.

Batching Stored Procedures. Author: ramki k (http://www.jguru.com/guru/viewbio.jsp?EID=1204869), Oct 12, 2004I understand with JDBC2.0 batch processing of SQL is supported. Can i use batching of Stored Procedures using CallableStatment.I saw an example in Sun site

CallableStatement cstmt = con.prepareCall( "{call updatePrices(?, ?)}");

cstmt.setString(1, "Colombian");

cstmt.setFloat(2, 8.49f);

cstmt.addBatch();

cstmt.setString(1, "Colombian_Decaf");

cstmt.setFloat(2, 9.49f);

Page 32: Jdbc Faq From Jguru

cstmt.addBatch();

int [] updateCounts = cstmt.executeBatch();

But I am not getting the above example working. The first update added to the batch gets executed and the second one doesn't. I used DB2 Version 8 and the JDBC driver shipped with that. So I want to know if i can run the same procedure in a batch with different IN params as demonstrated in this example and does DB2 support that. Please reply for this query.

Thankx

ramki

What are SQL3 data types?Location: http://www.jguru.com/faq/view.jsp?EID=5080 Created: Jan 15, 2000 Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

The next version of the ANSI/ISO SQL standard defines some new datatypes, commonly referred to as the SQL3 types. The primary SQL3 types are:

STRUCT: This is the default mapping for any SQL structured type, and is manifest by the java.sql.Struct type.

REF: Serves as a reference to SQL data within the database. Can be passed as a parameter to a SQL statement. Mapped to the java.sql.Ref type.

BLOB: Holds binary large objects. Mapped to the java.sql.Blob type.

CLOB: Contains character large objects. Mapped to the java.sql.Clob type.

ARRAY: Can store values of a specified type. Mapped to the java.sql.Array type.

You can retrieve, store and update SQL3 types using the corresponding getXXX(), setXXX(), and updateXXX() methods defined in ResultSet interface

How can I manage special characters (for example: " _ ' % ) when I execute an INSERT query? If I don't filter the quoting marks or the apostrophe, for example, the SQL string will cause an error. Location: http://www.jguru.com/faq/view.jsp?EID=8881 Created: Jan 26, 2000 Modified: 2000-10-26 17:48:58.547Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question originally posed by Stefano Cazzulani (http://www.jguru.com/guru/viewbio.jsp?EID=5622

Page 33: Jdbc Faq From Jguru

In JDBC, strings containing SQL commands are just normal strings - the SQL is not parsed or interpreted by the Java compiler. So there is no special mechanism for dealing with special characters; if you need to use a quote (") within a Java string, you must escape it.

The Java programming language supports all the standard C escapes, such as \n for newline, \t for tab, etc. In this case, you would use \" to represent a quote within a string literal:

String stringWithQuote = "\"No,\" he replied, \"I did not like that salted licorice.\"";

This only takes care of one part of the problem: letting us control the exact string that is passed on to the database. If you want tell the database to interpret characters like a single quote (') literally (and not as string delimiters, for instance), you need to use a different method. JDBC allows you to specify a separate, SQL escape character that causes the character following to be interpreted literally, rather than as a special character.

An example of this is if you want to issue the following SQL command:

SELECT * FROM BIRDS WHERE SPECIES='Williamson's Sapsucker'In this case, the apostrophe in "Williamson's" is going to cause a problem for the database because SQL will interpret it as a string delimiter. It is not good enough to use the C-style escape \', because that substitution would be made by the Java compiler before the string is sent to the database.

Different flavors of SQL provide different methods to deal with this situation. JDBC abstracts these methods and provides a solution that works for all databases. With JDBC you could write the SQL as follows:

Statement statement = // obtain reference to a Statementstatement.executeQuery( "SELECT * FROM BIRDS WHERE SPECIES='Williamson/'s Sapsucker' {escape '/'}");The clause in curly braces, namely {escape '/'}, is special syntax used to inform JDBC drivers what character the programmer has chosen as an escape character. The forward slash used as the SQL escape has no special meaning to the Java compiler; this escape sequence is interpreted by the JDBC driver and translated into database-specific SQL before the SQL command is issued to the database.

Escape characters are also important when using the SQL LIKE clause. This usage is explicitly addressed in section 11.5 of the JDBC specification:

The characters "%" and "_" have special meaning in SQL LIKE clauses (to match zero or more characters, or exactly one character, respectively). In order to interpret them literally, they can be preceded with a special escape character in strings, e.g. "\". In order to specify the escape character used to quote these characters, include the following syntax on the end of the query: {escape 'escape-character'}For example, the query SELECT NAME FROM IDENTIFIERS WHERE ID LIKE '\_%' {escape '\'}

Page 34: Jdbc Faq From Jguru

finds identifier names that begin with an underbar. Comments and alternative answers

does not work Author: chuck g. (http://www.jguru.com/guru/viewbio.jsp?EID=570586), Dec 3, 2001i'm using jdk 1.3.01 and oracle's thin driver. this does not work at, gives me a "SQL Statement not properly terminated error"...

Re: does not work Author: Steven Elliott (http://www.jguru.com/guru/viewbio.jsp?EID=123860), Dec 18, 2001You're right it won't work. The { escape 'str' } ASFAIK only works for LIKE statements. In order to *escape* quotes for INSERT or SELECT statements use either a prepared statement or double up the quotes. For instance say you want to insert the String "John's book" you would do something like: INSERT INSERT INTO yourTable VALUES ('John''s book') Try it.; )

Re[2]: does not work Author: ashish gairola (http://www.jguru.com/guru/viewbio.jsp?EID=1244660), May 18, 2005ok I agree with u but In my case the users has to fill the details and he could use any special characters. so what sql command should I use ?

Re: Special Characters need some more settings Author: K Kak (http://www.jguru.com/guru/viewbio.jsp?EID=1178435), Jun 14, 2004Try using Prepared Statement to insert these special characters. but Prepared statement does not help for inserting values like ® (Registered symbol). Does anyone know how to insert these characters.

Continuing Author: glenn bullock (http://www.jguru.com/guru/viewbio.jsp?EID=846081), May 7, 2002Another good way is to simply use PreparedStatements. Not only do you get the pre-compile benefits PS's offer, but when you call the "add" methods, the escaping is done for you.

Re: Continuing Author: Willie Wheeler (http://www.jguru.com/guru/viewbio.jsp?EID=459006), Sep 12, 2002

This works, though it comes at a price--performance suffers unless you're executing sufficiently many statements. See

www.onjava.com/pub/a/onjava/excerpt/oraclejdbc_19/

Page 35: Jdbc Faq From Jguru

Whether you do it in a given instance depends on where you want to be on the independence/performance tradeoff.

Re[2]: Continuing Author: Ashish Kapoor (http://www.jguru.com/guru/viewbio.jsp?EID=1091036), Jun 4, 2003I want to add the escape characters to all the apostophes in the SQL commands. Does anyone know an efficient function that can add an escape charachter to every apostrophe in a String. Eg String x = "Jame's garage"; should return "James''s garage"; and String x = "James's'g'a''"; should return "James''s''g''a''''"); I am looking for some efficeint program possibly in java. Regards Ashish www26.brinkster.com/akapoor/

Re[3]: Continuing Author: David Bell (http://www.jguru.com/guru/viewbio.jsp?EID=1096830), Jun 24, 2003x = x.replaceAll("'","''");

% in where clause Author: Nise Kuriakose (http://www.jguru.com/guru/viewbio.jsp?EID=1142896), Feb 2, 2004Hi Friends,

Still there is one problem. What happens if the like parthas a value with % in it. My qry goes like this:

select * from emp where emp_name like '%HA%%'.

I want to look for names with HA% in them.Even after using prepared statement I am unable to solve it.

For prep stmt, I did like this :

qry = "select * from emp where emp_name like ? ";stmt = conn.prepareStatement(qry);stmt.setString(i, "%" + emp_name + "%"); // emp_name="HA%";

Pls help.

bye,Nise

Page 36: Jdbc Faq From Jguru

The java.sql package contains mostly interfaces. When and how are these interfaces implemented while connecting to database? Location: http://www.jguru.com/faq/view.jsp?EID=11164 Created: Feb 3, 2000 Modified: 2000-05-29 11:53:43.529Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question originally posed by arul senthil (http://www.jguru.com/guru/viewbio.jsp?EID=8904

The implementation of these interfaces is all part of the driver. A JDBC driver is not just one class - it is a complete set of database-specific implementations for the interfaces defined by the JDBC.

These driver classes come into being through a bootstrap process. This is best shown by stepping through the process of using JDBC to connect to a database, using Oracle's type 4 JDBC driver as an example:

First, the main driver class must be loaded into the VM: Class.forName("oracle.jdbc.driver.OracleDriver");

The specified driver must implement the Driver interface. A class initializer (static code block) within the OracleDriver class registers the driver with the DriverManager.

Next, we need to obtain a connection to the database: String jdbcURL =

"jdbc:oracle:thin:@www.jguru.com:1521:ORCL"; Connection connection =

DriverManager.getConnection(jdbcURL);

DriverManager determines which registered driver to use by invoking the acceptsURL(String url) method of each driver, passing each the JDBC URL. The first driver to return "true" in response will be used for this connection. In this example, OracleDriver will return "true", so DriverManager then invokes the connect() method of OracleDriver to obtain an instance of OracleConnection. It is this database-specific connection instance implementing the Connection interface that is passed back from the DriverManager.getConnection() call.

The bootstrap process continues when you create a statement: Statement statement = connection.createStatement();

The connection reference points to an instance of OracleConnection. This database-specific implementation of Connection returns a database-specific implementation of Statement, namely OracleStatement

Invoking the execute() method of this statement object will execute the database-specific code necessary to issue an SQL statement and retrieve the results:

ResultSet result = statement.executeQuery("SELECT * FROM TABLE");

Again, what is actually returned is an instance of OracleResultSet, which is an Oracle-specific implementation of the ResultSet interface.

Page 37: Jdbc Faq From Jguru

So the purpose of a JDBC driver is to provide these implementations that hide all the database-specific details behind standard Java interfaces.

Can I use the JDBC-ODBC bridge driver in an applet?Location: http://www.jguru.com/faq/view.jsp?EID=12983 Created: Feb 10, 2000 Modified: 2000-09-14 06:19:06.058Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

A: Short answer: No.

Longer answer: You may create a digitally signed applet using a Certicate to circumvent the security sandbox of the browser. See the Certificate jFAQ.

Comments and alternative answers

If you use the JDBC-ODBC bridge driver in an applet,... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Feb 21, 2000If you use the JDBC-ODBC bridge driver in an applet, Internet Explorer uses a different class for the driver than Netscape and the Java Plugin (Sun reference implementation).

The Sun JDBC-ODBC bridge is sun.jdbc.odbc.JdbcOdbc... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Sep 14, 2000The Sun JDBC-ODBC bridge is sun.jdbc.odbc.JdbcOdbcDriver. The Microsoft one is com.ms.jdbc.odbc.JdbcOdbcDriver

What is SQLJ and why would I want to use it instead of JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=12988 Created: Feb 10, 2000 Modified: 2002-03-24 00:04:18.12Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

SQL/J is a technology, originally developed by Oracle Corporation, that enables you to embed SQL statements in Java. The purpose of the SQLJ API is to simplify the development requirements of the JDBC API while doing the same thing. Some major databases (Oracle, Sybase) support SQLJ, but others do not. Currently, SQLJ has not been accepted as a standard, so if you have to learn one of the two technologies, I recommend JDBC.

How can I connect from an applet to a database on the server?Location: http://www.jguru.com/faq/view.jsp?EID=12992 Created: Feb 10, 2000 Modified: 2000-09-14 06:19:58.171Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15) Question originally posed by tarek adel (http://www.jguru.com/guru/viewbio.jsp?EID=10046

Page 38: Jdbc Faq From Jguru

There are two ways of connecting to a database on the server side.

1. The hard way. Untrusted applets cannot touch the hard disk of a computer. Thus, your applet cannot use native or other local files (such as JDBC database drivers) on your hard drive. The first alternative solution is to create a digitally signed applet which may use locally installed JDBC drivers, able to connect directly to the database on the server side.

2. The easy way. Untrusted applets may only open a network connection to the server from which they were downloaded. Thus, you must place a database listener (either the database itself, or a middleware server) on the server node from which the applet was downloaded. The applet would open a socket connection to the middleware server, located on the same computer node as the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database. This is illustrated below:

Comments and alternative answers

And the easiest way connecting to a database on the server side Author: Bags P (http://www.jguru.com/guru/viewbio.jsp?EID=551914), Nov 20, 2001If you have installed jdk properly you should be able to do this. There is an utily called policytool. Run this and add the web site you are downloading the applet from to the CODEBASE parameter and grand all permission. It is intuitive. Beware of the consequences though. Its like you are opening the doors of the houses for a particular person. Other rules in the applet code are the same.

How do I insert an image file (or other raw data) into a database?Location: http://www.jguru.com/faq/view.jsp?EID=13000 Created: Feb 10, 2000 Modified: 2000-04-24 19:46:09.718Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15) Question originally posed by abhishek dubey (http://www.jguru.com/guru/viewbio.jsp?EID=2207

All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,

1. Read all data from the file using a FileInputStream. 2. Create a byte array from the read data. 3. Use method setBytes(int index, byte[] data); of

java.sql.PreparedStatement to upload the data.

Page 39: Jdbc Faq From Jguru

Comments and alternative answers

still have problem Author: qinglee li (http://www.jguru.com/guru/viewbio.jsp?EID=883257), May 17, 2002I try this way by MS ACCESS. I can upload the whole image data file into the database. and then read it back to my servlet with exact number of bytes as the original image file, but the data can't be displayed by browser or other image program. Is any body know why? some people think that it's caused by the Database. if it's true, is any other database can avoid this problem? thank you!

HOW USE FROM FILEINPUTSTREAM Author: maryam ghafoori (http://www.jguru.com/guru/viewbio.jsp?EID=1207406), Oct 26, 2004

I HAVE PROBLEM TO USE OF FILE INPUTSTREAM AND I HAVE PROBLEM TO USE OF GETBINARYSTREAM.PLEASE DISCRIBE IT WITH EXAMPLE

Re: HOW USE FROM FILEINPUTSTREAM Author: robin bajaj (http://www.jguru.com/guru/viewbio.jsp?EID=1207628), Dec 15, 2004just Read this 5 page article , you will find out everything about image uploads/downloads using java servlets/EJB http://www.ftponline.com/javapro/2004_01/magazine/features/jodonahue/ regards robin

When using JDBC-ODBC or Oracle thin JDBC drivers, some methods of ResultSet can't be used. (For example. ResultSet.first(), ResultSet.previous();) What is wrong?Location: http://www.jguru.com/faq/view.jsp?EID=13327 Created: Feb 11, 2000 Modified: 2000-03-23 12:04:22.564Author: Benoit Xhenseval (http://www.jguru.com/guru/viewbio.jsp?EID=3363) Question originally posed by roy shao (http://www.jguru.com/guru/viewbio.jsp?EID=10140

Some of the JDBC 2.0 features are not implemented in the Oracle JDBC drivers; even if it compiles ok, if you try them you will get an exception! ouch!

Having said that, the latest driver is 8.1.6 available on http://technet.oracle.com and it should sort out the problems you are having.

I'm using a type 4 (pure Java) JDBC driver in an applet. It works fine in Netscape, but doesn't work properly in Internet Explorer. Why not?Location: http://www.jguru.com/faq/view.jsp?EID=15147 Created: Feb 17, 2000 Modified: 2000-09-14 06:26:53.349Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Rafal Kurianowicz (http://www.jguru.com/guru/viewbio.jsp?EID=13323

Page 40: Jdbc Faq From Jguru

Microsoft's VM loads classes/drivers differently than the Java VM in Netscape browsers (and Sun's reference implementation). Just having a Class.forName(driverClassName) line is insufficient, as it doesn't consider it an active use. You'll also need to create a new instance of the driver Class.forName(driverClassName).newInstance() which registers the driver with the driver manager (java.sql.DriverManager.registerDriver(new DriverClass())).

How can resultset records be restricted to certain rows?Location: http://www.jguru.com/faq/view.jsp?EID=15644 Created: Feb 18, 2000 Modified: 2000-02-19 04:19:02.43Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

The easy answer is "Use a JDBC 2.0 compliant driver".

With a 2.0 driver, you can use the setFetchSize() method within a Statement or a ResultSet object.

For example,

Statement stmt = con.createStatement(); stmt.setFetchSize(400); ResultSet rs = stmt.executeQuery("select * from customers");

will change the default fetch size to 400.

You can also control the direction in which the rows are processed. For instance:

stmt.setFetchDirection(ResultSet.FETCH_REVERSE)will process the rows from bottom up.

The driver manager usually defaults to the most efficient fetch size...so you may try experimenting with different value for optimal performance.

How can I pool my database connections so I don't have to keep reconnecting to the database?Location: http://www.jguru.com/faq/view.jsp?EID=17020 Created: Feb 22, 2000 Modified: 2002-03-23 20:28:33.101Author: Sylvain GIBIER (http://www.jguru.com/guru/viewbio.jsp?EID=11408) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

There are plenty of connection pool implementations described in books or availalble on the net. Most of them implement the same model. The process is always the same :

you gets a reference to the pool you gets a free connection from the pool you performs your different tasks you frees the connection to the pool

Page 41: Jdbc Faq From Jguru

Since your application retrieves a pooled connection, you don't consume your time to connect / disconnect from your data source.You can find some implementation of pooled connection over the net, for example:

Db Connection Broker (http://www.javaexchange.com/), a package quite stable ( I used it in the past to pool an ORACLE database on VMS system)

You can look at the JDBC 2.0 standard extension API specification from SUN which defines a number of additional concepts. Comments and alternative answers

I highly recommend PoolMan. It comes with complete... Author: Christopher Longo (http://www.jguru.com/guru/viewbio.jsp?EID=2166), Jun 18, 2000I highly recommend PoolMan. It comes with complete source and is distributed under the Lesser Gnu Public License.

Re: I highly recommend PoolMan. It comes with complete... Author: Gopalakrishnan G (http://www.jguru.com/guru/viewbio.jsp?EID=415914), May 5, 2001Yes, PoolMan seems to do a lot at first. However, there is no documentation on how to use the product and there is no support. There are no examples available on how to use this product. It's frustating to say the least. If you know how to use it, then, please email me the details [email protected]. Thanks

I am so sad,The poolman is no longer available!The text listed below was digisted from the site of poolMan Author: Jeason Zhao (http://www.jguru.com/guru/viewbio.jsp?EID=1037417), Dec 13, 2002PoolMan is no longer available or supported through this site. It did exceedingly well during its lifetime, and I appreciate the important role it played in so many distributed applications over the past three years. If you are looking for connection and object pooling mechanisms, they can now be found in application servers such as JRun, Tomcat and the Jakarta Project, and other J2EE products and servers.

Additional connection pool resources: Enhydra Build... Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Jul 25, 2000Additional connection pool resources:

EnhydraBuild your own ObjectPool in Java to boost app speedTHE JDBC 2.0 OPTIONAL PACKAGEImproved Performance with a Connection Pool

Page 42: Jdbc Faq From Jguru

Writing Advanced Applications: Chapter 8 Continued: Connection Pooling

Connection Pools Author: glenn bullock (http://www.jguru.com/guru/viewbio.jsp?EID=846081), May 7, 2002Connection pools are nice, but most connections support concurrent statements, which is much simpler to deal with (unless you're dealing with transactions, of course).

Also, another nice idea is to have a Prepared Statement pool that will remove the statement from the map when needed (don't want to execute it simultaneously), then add it back in when you're done.

DBConnectionBroker Tips Author: Nate McMorris (http://www.jguru.com/guru/viewbio.jsp?EID=929030), Jun 26, 2002DbConnectionBroker from javexchange(http://www.javaexchange.com) is working well. However...There's almost no documentation. So here's what I found.1) Start really simple, just create the broker object and NOTHING ELSE first.2) When catching exceptions, use the method catching syntax ( public void method() throws Exception {...} ) rather than using a "try {} catch(){}" clause. 3) You must create your log file first. The Broker won't create it if it doesn't exist.4) If you're running this inside a JSP/Servlet container, you can't rely on the container's class loader to find the database driver or any other classes you need from the DbConnectionBroker class; you need to make sure the DB Driver etc. is somewhere in your $CLASSPATH.5) I needed to get this to work inside TOMCAT, and without using Servlets, so I create the broker between the <jsp:useBean...> and </jsp:useBean> tags, then I load that instance into a bean with an "application" cope. Then I can call that bean from any page where I need a connection.6) I couldn't get some of the methods (like idOfConnection() ) to work, so try the methods out one by one to see if they work.7) Lastly, the syntax for a MySQL connection is slightly different than the Oracle Driver in the examples. I use DbConnectionBroker myBroker = new DbConnectionBroker("org.gjt.mm.mysql.Driver","jdbc:mysql://yourdatabase server/yourDb?user=user","","",4,5,"/path/to/brokerLog.log",1.0,true,0,3); -

In distributed architecture (typical three tier consisting of thin client, middleware & database) which type of JDBC driver should be used and why?Location: http://www.jguru.com/faq/view.jsp?EID=21804 Created: Mar 8, 2000 Modified: 2000-03-23 12:17:42.054

Page 43: Jdbc Faq From Jguru

Author: Zahid Shaikh (http://www.jguru.com/guru/viewbio.jsp?EID=21793) Question originally posed by sat d (http://www.jguru.com/guru/viewbio.jsp?EID=14705

Normally in 3-tier architectures, you would preferably connect to database via middleware. Pure java drivers are slower than native driver but they do not require any client-side installation. So for middleware, as perfomance is important, native JDBC drivers like Oracle's OCI driver should be preferred. Also native installation(like ODBC or Oracle's Sqlnet ) would be required at middleware level but it would not affect the clients. In the exceptional case, if the database is needed to be accessed by thin client than pure Java driver like Oracle's thin driver is recommended as they do not require any client-side installation.Comments and alternative answers

Sybase claims that their JConnect Type 4 drivers are... Author: Patrick Shomo (http://www.jguru.com/guru/viewbio.jsp?EID=105029), Feb 20, 2001Sybase claims that their JConnect Type 4 drivers are faster than their native components because the overhead of "going native" is more than the "micropayment" of using Java. Check out the JConnect documentation in PDF for more. My experience? While I haven't run timed tests I am pleased with performance. Seems quick enough. As always, YMMV.

How do I pass a Timestamp from JDBC to a database? Give me some database specific examples (MS Access etc.).Location: http://www.jguru.com/faq/view.jsp?EID=25919 Created: Mar 19, 2000 Modified: 2000-03-19 09:39:58.533Author: Richard Katz (http://www.jguru.com/guru/viewbio.jsp?EID=25710) Question originally posed by Sean Tillman (http://www.jguru.com/guru/viewbio.jsp?EID=6837

Use the setTimestamp() method to load your timestamp into a PreparedStatement. First create a connection to the database and then:

String upsql="UPDATE MYTABLE SET MYDATETIME = ? WHERE MYTABLEID=100"; PreparedStatement pstmt = con.prepareStatement(upsql); pstmt.setTimestamp(1,mytimestampvar); pstmt.execute();

This method can be used with any database that supports timestamps and any driver that supports PreparedStatement.

For Windows desktop databases, the JDataConnect driver (and a number of other Windows specific type 3 drivers) support PreparedStatement. If the JDBC-ODBC bridge isn't doing what you need, try a more industrial strength driver. You can obtain a copy of JDataConnect from http://www.softsyn.com/.

Comments and alternative answers

Can't update timestamp on MS SQL Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Feb 3, 2002

Page 44: Jdbc Faq From Jguru

In MS SQL (at least, MS SQL 7) you can not write to or update a timestamp field: it's set by the database automatically.

How about this url for JNetDirect Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Feb 3, 2002http://www.j-netdirect.com/JDataFeatures.htm

Will a call to PreparedStatement.executeQuery() always close the ResultSet from the previous executeQuery()?Location: http://www.jguru.com/faq/view.jsp?EID=26155 Created: Mar 20, 2000 Modified: 2000-03-23 13:22:45.632Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708) Question originally posed by Andy Schneider (http://www.jguru.com/guru/viewbio.jsp?EID=10819

A quote from the Java API docs, java.sql.ResultSet:

A ResultSet is automatically closed by the Statement that generated it when that Statement is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.

I think that this should answer your question. It is recommended to retrieve the results into an abitrary datastructure, but be aware that even if in Java parameters are always passed per value; an object variable is a reference (i.e. can be seen as a pointer to an object) and only that reference will be passed per value, but not the object itself. That's a hint for the case that you suddenly get an exception accessing an object you retrieved with myResultSet.getObject(). Comments and alternative answers

And calling query with diferents ResultSet? Author: Julio Garrido (http://www.jguru.com/guru/viewbio.jsp?EID=1048231), Jan 20, 2003Ok, when I call a query again the Resultset will be closed and cleared, but, if I call with other resultset, I will lost the result too? Example:

Resultset rs1 = con.executeQuery("SELECT * FROM TABLE1 WHERE ..."); ...; ...; rs1 = con.executeQuery("SELECT * FROM TABLE1 WHERE ..."); ...; Resultset rs2 = con.executeQuery("SELECT * FROM TABLE2");

rs1 will lost its data?

How do you find the number of records returned using the JDBC API? Is there a direct function call(like in other languages)? Right now we have to

Page 45: Jdbc Faq From Jguru

loop over the resultset to get the number(I guess the only way) Location: http://www.jguru.com/faq/view.jsp?EID=26160 Created: Mar 20, 2000 Modified: 2000-03-23 14:22:55.823Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708) Question originally posed by neal ravindran PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=17737

Well java.sql.ResultSet does not offer any method to retrieve the amount of rows that have been selected.Now I have following ideas that I hope might help:

1. It is recommended to retrieve the results into an abitray datastructure, especially in case of pooled connections. Now ensure using a datastructure that has an accessor method for its size.

2. Another possibility would be to use a seperate prepared statement that returns nothing but a count of the rows that will be selected. i.e. select count(*) from myTableInstead of * you can also use any column existing in myTable.

3. A third way I could think of is to add the count(<column>) to the request, thus retrieving the count of all rows as the first column of each row. i.e. select count(&lt;existing column&gt;),* from myTableI am not sure if it really makes sense, but it's at least a possibility.

Comments and alternative answers

A JDBC 2.0 compliant driver supports getRow(), which... Author: Vivek Shukla (http://www.jguru.com/guru/viewbio.jsp?EID=49607), May 17, 2000A JDBC 2.0 compliant driver supports getRow(), which returns the current row number ( the first row is one, second is two, and so on. ) Using the JDBC 2.0 ResultSet method last() and then invoking getRow() effectively gives the ResultSet row count in an easy and much more efficient way than previous methods.

Re: A JDBC 2.0 compliant driver supports getRow(), which... Author: Johann Tomas (http://www.jguru.com/guru/viewbio.jsp?EID=305921), Sep 12, 2001The JDBC driver for SAP DB, which claims JDBC 2.0 compatibility (but not compatibility with the JDBC standard extensions) seems to behave as follows: rs.last();int numRows = rs.getRow();// at this point, numRows == -1

Is this incorrect behavior or are drivers allowed to behave this way? I'm assuming that the -1 means "1 from the end of the resultset", similar to the semantics of ResultSet's absolute(int row) method.

Anyone have any ideas apart from those already mentioned in this thread for how to retrieve the number of rows in a RecordSet where the driver behaves this way?

Page 46: Jdbc Faq From Jguru

When using JDBC 2.0 as mentioned, be sure to use the... Author: Christopher Bowland (http://www.jguru.com/guru/viewbio.jsp?EID=217833), Sep 28, 2000When using JDBC 2.0 as mentioned, be sure to use the method createStatement(int resultSetType, int resultSetConcurrency) instead of the createStatement() method so that you obtain a scrollable ResultSet and will then be able to use the first() method to return to the beginning of the ResultSet so processing can continue.

If you do not use the suggested method or the correct parameters in that method, an exception will be thrown if you attempt to access the first row again or you will have to re-run the query and get a new Result Set.

Getting the size out of ResultSet. Author: Mimpin Halim (http://www.jguru.com/guru/viewbio.jsp?EID=515634), Apr 26, 2002The #3 idea doesn't work, at least not in oracle 8i. I was using the #2 idea and looking for cheaper way to do it than to make the call to the db twice (one for count and one for data).

Re: Getting the size out of ResultSet. Author: jose vazquez (http://www.jguru.com/guru/viewbio.jsp?EID=921762), Jun 20, 2002Oracle JDBC drivers sucks! You can get the size of a resultset by doing: last() getCursorPosition() or whatever is called. The problem is that in oracle's JDBC implementation (up to classes12.zip) rset.last() takes exactly the same time as while(rset.next()); because they DO NOT SKIP ANY ENTRIES, YESS! EVEN ON ('supposed to be') SCROLLABLE RESULTSETS!!! So basically IT IS USELESS. If you are getting 10000 entries it can take oracle 2s to get the query done and then it will consume 4.5s just to do the last() call. Another way is to get the size by doing select count(*) from query; Which will take more or less the same time (2s, you save 2.5s or 4.5 if the queries are done in separate threads) but you will be in trouble if the user wants to go directly to the last rows, because ORACLE JDBC DOES NOT SKIP ROWS. If someone can prove I am wrong or have a solution to this, I willing to learn. (We are forced to move to MSSQL Server + Sprinta which provides a REAL Scrollable ResultSet, and I hate to depend on Windows machines as servers)

I have stored image files in a database. Is there any way to display that image in a web browser by querying the database?Location: http://www.jguru.com/faq/view.jsp?EID=26164 Created: Mar 20, 2000 Modified: 2000-06-21 13:58:08.889Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708) Question originally posed by chandra sekar (http://www.jguru.com/guru/viewbio.jsp?EID=20353

I would recommend you to retrieve the image via JDBC from a simple HTTP servlet.

Page 47: Jdbc Faq From Jguru

Things you have to take care about:

Ensure to set the correct Mime type. This has to be done calling HttpServletResponse.setContentType(String type);e.g. myHttpServletResponse.setContentType("image/jpeg");

Ensure that your RDBMS does not limit result sizes (i.e. check the manuals if you get half images, and always the same block sizes).

Attach ?<param>=<value> to your src URL to specify the picture to be retrieved. This param can be retrieved within your service method very simple, using:HttpServletRequest.getParameter(String name);The HTML tag for the image would then be something like follows:&lt;img src="http://www.mydomain.com/PictureServlet?id=35"&gt;(Sure you can use more params if you need to do so.)

Use some simple or sophisticated caching algorithm to limit your systems load.

Be sure to check the Servlet FAQ for questions on Servlets.Comments and alternative answers

About your last point of "Use some simple or ... Author: Billy Collins (http://www.jguru.com/guru/viewbio.jsp?EID=301635), Jan 13, 2001About your last point of "Use some simple or sophisticated caching algorithm to limit your system's load." Do you have any suggestions/advice/sample_code?

Thanks!

It is a Good Idea to wrap your stored media with the... Author: Brian Ewins (http://www.jguru.com/guru/viewbio.jsp?EID=301660), Jan 13, 2001It is a Good Idea to wrap your stored media with the javax.activation.DataSource API - this will allow you to use the media as described above in servlets and in JAF-aware UI frameworks (eg to browse your DB). You should store the MIME type along with the image in the DB, otherwise you will have to figure it out. The JAF currently recognizes MIME types by file extension, but you can easily hardcode what is in apache's mime.magic to recognize the leading bytes of files, and with a bit more effort actually use that file. (use a PushbackInputStream to pull out the first few bytes)

The simplest cache is a hashtable. Use WeakHashMap... Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jan 15, 2001The simplest cache is a hashtable. Use WeakHashMap to avoid filling up memory. More sophisticated in-memory caches are all over the place; for instance, see my http://www.purpletech.com/ for com.purpletech.util.Cache.

Page 48: Jdbc Faq From Jguru

How can I get data from multiple ResultSets?Location: http://www.jguru.com/faq/view.jsp?EID=27825 Created: Mar 23, 2000 Modified: 2000-03-23 13:58:56.488Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Anil Datt (http://www.jguru.com/guru/viewbio.jsp?EID=20887

With certain database systems, a stored procedure can return multiple result sets, multiple update counts, or some combination of both. Also, if you are providing a user with the ability to enter any SQL statement, you don't know if you are going to get a ResultSet or an update count back from each statement, without analyzing the contents. The Statement.execute() method helps in these cases.

Method Statement.execute() returns a boolean to tell you the type of response:

true indicates next result is a ResultSetUse Statement.getResultSet to get the ResultSet

false indicates next result is an update countUse Statement.getUpdateCount to get the update count

false also indicates no more resultsUpdate count is -1 when no more results (usually 0 or positive)

After processing each response, you use Statement.getMoreResults to check for more results, again returning a boolean. The following demonstrates the processing of multiple result sets:

boolean result = stmt.execute(" ... ");int updateCount = stmt.getUpdateCount();

while (result || (updateCount != -1)) { if(result) { ResultSet r = stmt.getResultSet(); // process result set } else if(updateCount != -1) { // process update count } result = stmt.getMoreResults(); updateCount = stmt.getUpdateCount(); }Comments and alternative answers

How do I deal with multiple ResultSets that might have some empty result sets? Author: tim chen (http://www.jguru.com/guru/viewbio.jsp?EID=387588), Apr 4, 2001How do I deal with multiple ResultSets that might have some empty result sets? For example, what happens when I run something like this: BEGIN SELECT name FROM employees WHERE id <= 1 AND id >=10; SELECT name FROM ex_employees WHERE id <=11 AND id >=20; SELECT name FROM bosses WHERE id <=21 AND id >=30; END; I'm expecting 3 result sets back but what happens if the second select statement returned no rows, but the other 2 select statements return some rows. Will getMoreResults() return false or will it return

Page 49: Jdbc Faq From Jguru

true and have getResultSet() return a null ResultSet? thanks, timbo

How do I execute stored procedures?Location: http://www.jguru.com/faq/view.jsp?EID=30731 Created: Mar 31, 2000 Modified: 2000-04-28 17:48:40.961Author: Andreas Schaefer (http://www.jguru.com/guru/viewbio.jsp?EID=25162) Question originally posed by Jairo Lagos (http://www.jguru.com/guru/viewbio.jsp?EID=22155

Here is an example on how to execute a stored procedure with JDBC (to use this in a servlet is the same the only thing is that you create the connection and callable statement in the init() of the servlet):package DBTest;

import java.sql.*;

public class JdbcTest {

private String msDbUrl = "jdbc:odbc:ms"; private String msJdbcClass = "sun.jdbc.odbc.JdbcOdbcDriver"; private Connection mcDbAccess; private CallableStatement msProcedure;

public JdbcTest() { try { Class.forName( msDbUrl ).newInstance(); mcDbAccess = DriverManager.getConnection( msJdbcClass, "milestone", "milestone" ); msProcedure = mcDbAccess.prepareCall( "{? = call sp_sav_Bom_Header( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) }" ); msProcedure.registerOutParameter( 1, java.sql.Types.VARCHAR ); msProcedure.setInt( 2, -1 ); msProcedure.setInt( 3, 39 ); msProcedure.setString( 4, "format" ); long ltTest = new java.util.Date().getTime(); System.out.println( "Today: " + ltTest ); msProcedure.setTimestamp( 5, new Timestamp( ltTest ) ); msProcedure.setString( 6, "type" ); msProcedure.setString( 7, "submitter" ); msProcedure.setString( 8, "email" ); msProcedure.setString( 9, "phone" ); msProcedure.setString( 10, "comments" ); msProcedure.setString( 11, "label" ); msProcedure.setInt( 12, 52 ); msProcedure.setBoolean( 13, true ); msProcedure.setBoolean( 14, false ); msProcedure.setInt( 15, 53 ); msProcedure.setString( 16, "runtime" ); msProcedure.setString( 17, "configuration" ); msProcedure.setBoolean( 18, true ); msProcedure.setBoolean( 19, false );

Page 50: Jdbc Faq From Jguru

msProcedure.setString( 20, "special instructions" ); msProcedure.setInt( 21, 54 );

ResultSet lrsReturn = null; System.out.println( "Execute: " + (lrsReturn = msProcedure.executeQuery() ) ); while( lrsReturn.next() ) { System.out.println( "Got from result set: " + lrsReturn.getInt( 1 ) ); } System.out.println( "Got from stored procedure: " + msProcedure.getString( 1 ) ); } catch( Throwable e ) { e.printStackTrace(); } }

public static void main(String[] args) { new JdbcTest(); }}I also tried it by using a native JDBC driver (i-net) and it also works fine. The only problem we encounter with JDBC-ODBC bridge is that a stored procedure pads spaces to the full length of a VARCHAR but the native JDBC behaves right. Therefore I suggest to use JDBC native drivers.

The above example uses the MS SQL Server.

Comments and alternative answers

How does this work in Oracle? Author: P D (http://www.jguru.com/guru/viewbio.jsp?EID=493988), Sep 10, 2001The example probably works fine with MS SQL Server. However, in Oracle the one way to return a resultSet is by using a REF CURSOR. How would you map the output parameter to a REF CURSOR and still be able to return a resultSet??

Re: How does this work in Oracle? Author: Jeason Zhao (http://www.jguru.com/guru/viewbio.jsp?EID=1037417), Dec 13, 2002Add "begin" and "end;" to the sql statement

Re: How does this work in Oracle? Author: sathy guru (http://www.jguru.com/guru/viewbio.jsp?EID=1239763), Apr 20, 2005you will have to register the output parameter as OracleTypes.Cursor since the ouput of the SP is stored in a special segment called Cursor in Oracle.

What are database cursors? Location: http://www.jguru.com/faq/view.jsp?EID=31904 Created: Apr 4, 2000 Modified: 2000-04-28 19:44:51.931

Page 51: Jdbc Faq From Jguru

Author: Richard Katz (http://www.jguru.com/guru/viewbio.jsp?EID=25710) Question originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

A cursor is actually always on the database server side. When you execute an SQL SELECT and create a ResultSet in JDBC, the RDBMS creates a cursor in response. When created, the cursor usually takes up temporary memory space of some sort inside the database.

How to raise a custom SQLWarning?Location: http://www.jguru.com/faq/view.jsp?EID=32523 Created: Apr 5, 2000 Modified: 2000-06-02 07:16:57.543Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15) Question originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

The SQLWarning class extends SQLException. You may therefore treat it as any normal Exception type with respect to throwing and catching. However, the SQLException class mimics a forward traversable, linked list of Exception objects. The reason for this behavior is that a database generated SQLException rarely occurs alone - one syntactic programming error leads to a suite of SQLException objects being generated. Use the getNextException() method of the SQLException class, as seen in the class structure below:

Class structure of SQLException and SQLWarning

Page 52: Jdbc Faq From Jguru

Thus, to create and traverse a custom SQLWarning structure, use code similar to the one below:

Creating SQLWarning package se.jguru.dbTests;

// Import the SQL classes

Page 53: Jdbc Faq From Jguru

import java.sql.*;

public abstract class RasingACustomSQLWarning{ public static void main(String[] args) { try { // Simulate getting the DB data getDataFromDB();

// All OK. System.out.println("Got all data."); } catch(SQLException ex) { // Printout root SQLException System.err.println("An SQL exception occurred: " + ex);

// Get all chained SQLExceptions while((ex = ex.getNextException()) != null) { System.err.println("Contained reason: " + ex); } } }

private static void getDataFromDB() throws SQLException { // Status flag resulting from database data // should be created from normal business rules in // a live situation. boolean somethingStrangeHappened = true;

if(somethingStrangeHappened) { // Create two custom SQL Warnings SQLWarning rootWarning = new SQLWarning("Business rules not properly regarded"); SQLWarning containedWarning = new SQLWarning("Product too cheap!");

// Chain the warnings rootWarning.setNextWarning(containedWarning);

// Notify the caller of the warnings throw rootWarning; } }}

How do I upload SQL3 BLOB & CLOB data to a database?Location: http://www.jguru.com/faq/view.jsp?EID=32537

Page 54: Jdbc Faq From Jguru

Created: Apr 5, 2000 Modified: 2000-07-24 07:48:07.206Author: Lennart Jorelid (http://www.jguru.com/guru/viewbio.jsp?EID=15)

Although one may simply extract BLOB & CLOB data from the database using the methods of the java.sql.CLOB and java.sql.BLOB, one must upload the data as normal java datatypes. The example below inserts a BLOB in the form of a byte[] and a CLOB in the form of a String into the database

Inserting SQL3 type data [BLOB & CLOB] private void runInsert() { try { // Log this.log("Inserting values ... "); // Open a new Statement PreparedStatement stmnt = conn.prepareStatement( "insert Lobtest (image, name) values (?, ?)");

// Create a timestamp to measure the insert time Date before = new java.util.Date();

for(int i = 0; i < 500; i++) { // Set parameters stmnt.setBytes(1, blobData); stmnt.setString(2, "i: " + i + ";" + clobData);

// Perform insert int rowsAffected = stmnt.executeUpdate(); }

// Get another timestamp to complete the time measurement Date after = new java.util.Date(); this.log(" ... Done!"); log("Total run time: " + ( after.getTime() - before.getTime()));

// Close database resources stmnt.close(); } catch(SQLException ex) { this.log("Hmm... " + ex); }}

Comments and alternative answers

Uploading CLOB data to DataBase Author: oscar casado (http://www.jguru.com/guru/viewbio.jsp?EID=555669), Nov 21, 2001As far as I know, that solution just works if the data to be uploaded is lower than 4000 bytes, in other case you'll have to : 1.- Retrieve a locator related to the CLOB field u wonna update 2.- getCharacterOutputStream from the CLOB obtaining a java.io.Writer object 3.- Updating the Writer object implies a modification in tha

Page 55: Jdbc Faq From Jguru

DataBase Clob field

Re: Uploading CLOB data to DataBase Author: Nader Henein (http://www.jguru.com/guru/viewbio.jsp?EID=800462), May 21, 2002Given that the string I'm trying to input is about 34000 characters long, I'll have to use the locator, can you please throw some code my way because I've been struggling with this bit for hours and it's killing me:

hitString is the 34000 character string,

Clob sqlClob = null ;Writer writer = sqlClob.setCharacterStream(1) ;writer.write(hitString.toCharArray());writer.close();

it won't frigin work

Re[2]: Uploading CLOB data to DataBase Author: Peter Hitchman (http://www.jguru.com/guru/viewbio.jsp?EID=889960), May 23, 2002Hi,

Been here myself recently.

The way I made it work was to insert data into the tables row first, then select the clob columns back using a "select ... for update". Then you can use the getCharacterOutputStream() api to write through to the clob columns. You also have to have auto commit switched off to make this work.

I'm wondering if there is a better way. I'm using Oracle, but JDBC has no support for the RETURNING clause in SQL, which would allow the lob locators to be returned as part of the insert statement.

Good luck Pete

[END]

How can I connect to an Excel spreadsheet file using jdbc?Location: http://www.jguru.com/faq/view.jsp?EID=32876 Created: Apr 6, 2000 Modified: 2000-08-01 13:34:27.626Author: Peter Kua (http://www.jguru.com/guru/viewbio.jsp?EID=32290) Question originally posed by uma maheswari (http://www.jguru.com/guru/viewbio.jsp?EID=28762

Page 56: Jdbc Faq From Jguru

Let's say you have created the following Excel spreadsheet in a worksheet called Sheet1 (the default sheet name). And you've saved the file in c:\users.xls.

USERIDFIRST_NAME

LAST_NAME

pkua Peter Kua

jlsmith John Smith

gh2312 Everett Johnson

chimera Faiz Abdullah

roy6943 Roy Sudirman

Since Excel comes with an ODBC driver, we'll use the JDBC-ODBC bridge driver that comes packaged with Sun's JDK to connect to our spreadsheet.

In Excel, the name of the worksheet is the equivalent of the database table name, while the header names found on the first row of the worksheet is the equivalent of the table field names. Therefore, when accessing Excel via jdbc, it is very important to place your data with the headers starting at row 1.

1. Create a new ODBC Data Source using the Microsoft Excel Driver. Name the DSN "excel", and have it point to c:\users.xls.

2. Type in the following code:

package classes; import java.sql.*;

public class TestServer { static { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { System.err.println(e); } }

public static void main(String args[]) { Connection conn=null; Statement stmt=null; String sql=""; ResultSet rs=null; try { conn=DriverManager.getConnection("jdbc:odbc:excel","",""); stmt=conn.createStatement(); sql="select * from [Sheet1$]"; rs=stmt.executeQuery(sql);

Page 57: Jdbc Faq From Jguru

while(rs.next()){ System.out.println(rs.getString("USERID")+ " "+ rs.getString("FIRST_NAME")+" "+ rs.getString("LAST_NAME")); } } catch (Exception e){ System.err.println(e); } finally { try{ rs.close(); stmt.close(); conn.close(); rs=null; stmt=null; conn=null; } catch(Exception e){} } } }Notice that we have connected to the Excel ODBC Data Source the same way we would connect to any normal database server.

The only significant difference is in the SELECT statement. Although your data is residing in the worksheet called "Sheet1", you'll have to refer to the sheet as Sheet1$ in your SQL statements. And because the dollar sign symbol is a reserved character in SQL, you'll have to encapsulate the word Sheet1$ in brackets, as shown in the code.Comments and alternative answers

Does Excel JDBC driver support Unicode? Author: Pratap Das (http://www.jguru.com/guru/viewbio.jsp?EID=129542), May 15, 2001I was trying to get Unicode data (Japanese text) stored in an Excel sheet via the JDBC-ODBC driver. However, it seems the driver on NT4 was dropping off the hi-byte of the Unicode. (I was getting the familiar question-marks). Is this a problem with the Excel driver or am I missing something? --Das

Re: Does Excel JDBC driver support Unicode? Author: grace guo (http://www.jguru.com/guru/viewbio.jsp?EID=590616), Dec 19, 2001Have you solved this problem? I have the same question here! Thanks

Re[2]: Does Excel JDBC driver support Unicode? Author: Pratap Das (http://www.jguru.com/guru/viewbio.jsp?EID=129542), Jan 7, 2002Apparently Excel 97 on NT4 does not support Unicode.

I gave up on the idea to call it via JDBC & decided on using plain old file

Page 58: Jdbc Faq From Jguru

reading to do the trick. --Das

Accessing both numeric and alphanumeric characters in the excel spreadsheet Author: Ajay Tejwani (http://www.jguru.com/guru/viewbio.jsp?EID=418246), Aug 1, 2001Hi Peter, You have given a very good example to demonstrate this funcationality.

In my case, I have acolumn that has got both pure numeric(12345) and purely alphanumeric(testing) type of data.

How can I get both the data? If alphanumeric data is the first data, it treats all the values as alphanumerc and returns null for numeric and vice versa.

Your quick reply shall be appreciated.

Thanks, Ajay

Re: Accessing both numeric and alphanumeric characters in the excel spreadsheet Author: Deepali Sach (http://www.jguru.com/guru/viewbio.jsp?EID=1003266), Sep 24, 2002I am facing sam problem. Please let me know if you could find the solution for the same

Re[2]: Accessing both numeric and alphanumeric characters in the excel spreadsheet Author: Bhausaheb Avhad (http://www.jguru.com/guru/viewbio.jsp?EID=1128128), Nov 13, 2003I am facing the same problem. Kindly help if you have got a soulution... Thanks

Re[3]: Accessing both numeric and alphanumeric characters in the excel spreadsheet Author: Bhausaheb Avhad (http://www.jguru.com/guru/viewbio.jsp?EID=1128128), Nov 14, 2003t

Re: Accessing both numeric and alphanumeric characters in the excel spreadsheet Author: Bhausaheb Avhad (http://www.jguru.com/guru/viewbio.jsp?EID=1128128), Nov 13, 2003I am facing the same problem. Kindly help if you have got a soulution... Thanks

What if the headers don't start from ROW 1

Page 59: Jdbc Faq From Jguru

Author: Ashok Baliga (http://www.jguru.com/guru/viewbio.jsp?EID=582574), Dec 12, 2001Is there any way to get around this? I'm integrating several 100 Spreadsheets and getting them standardized is not an option.

Excel via java Author: Norman Hanson (http://www.jguru.com/guru/viewbio.jsp?EID=462048), Mar 6, 2002i found this commerical library. tested it real quick. worked on solaris. ExtenXLS but I'm having trouble with the concept of paying for java code.

Other statements like "INSERT/UPDATE/DELETE" etc Author: Rakhi Raut (http://www.jguru.com/guru/viewbio.jsp?EID=794439), Mar 13, 2002Can u give me a code example of INSERT/UPDATE/DELETE/ records in the above code? I am trying to insert a record in an excel sheet in the following way: ResultSet rs = st.executeQuery( "INSERT INTO [Sheet1$] (TestCase_ID,Owner) VALUES (1.3.1,'Rakhi')"); ..but when i execute the java file with abve code following exception is thrown : Exception: [Microsoft][ODBC Driver Manager] Invalid cursor state The field names(TestCase_ID,Owner) are at the first row of the excel sheet .. what can be the possible error? also if the record gets successfully added , what way is there to check that in the code, other than physically checking it in the excel sheet ?

Re: Other statements like "INSERT/UPDATE/DELETE" etc Author: anupam shahi (http://www.jguru.com/guru/viewbio.jsp?EID=805471), Mar 20, 2002u r using resultset for isert statement which is incorrect. insert statements never return any resultset. as well as u r giving command st.executeQuery("....."); insert command is not a query comnand. so better use st.execute("....."); command.i think this will help u.

Without JDBC Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685), Apr 15, 2002Export your data to Comma Separated Value (CSV) format and user libraries to read and write this format:http://ostermiller.org/utils/ExcelCSV.html

Use excelread by Andy Khan to get excel data into your java program:http://www.andykhan.com/excelread/

The apache project has a library which called POI that can read and write the HSSF (Horrible Spread Sheet Format) that excel uses.http://jakarta.apache.org/poi/hssf/index.html

Page 60: Jdbc Faq From Jguru

help with using multiple excel files... Author: rick hunter (http://www.jguru.com/guru/viewbio.jsp?EID=930824), Jun 27, 2002what if im going to use more than 1 excel file? what if i dont know how many? what if you dont know the filenames of the excel files? what if you don't know the location of the files?

the reason im asking this is because, the example only used 1 excel file. you already know the filename (user.xls) and its location (c:\)

for multiple excel files, you could probably configure them one by one in your ODBC, but that is assuming you already know their filenames, and locations. what if you don't know? what if you don't know how many excel files you will use?

Could you describe the architecture behind jGuru.com: JSP, Servlets, database, servers, transactions etc...?Location: http://www.jguru.com/faq/view.jsp?EID=34896 Created: Apr 11, 2000 Modified: 2002-11-20 12:23:54.439Author: Terence Parr (http://www.jguru.com/guru/viewbio.jsp?EID=1) Question originally posed by Benoit Xhenseval (http://www.jguru.com/guru/viewbio.jsp?EID=3363

[Updated Nov 20, 2002 to remove old description and point at some articles. TJP]

jGuru.com Case-Study.

Little Nybbles of Development Wisdom.

Say that a returned ResultSet has 100 rows. After looping through 60 rows, I want to return to row number 40 without querying the database again. Is it possible?Location: http://www.jguru.com/faq/view.jsp?EID=41183 Created: Apr 27, 2000 Modified: 2000-04-28 17:53:36.865Author: Nicola Ken Barozzi (http://www.jguru.com/guru/viewbio.jsp?EID=39153) Question originally posed by Monil Laddha (http://www.jguru.com/guru/viewbio.jsp?EID=33536

To access rows in a database ResultSet you must use a JDBC 2.0 capable driver. If the version number is lower you can only go forward; to go backwards or jump to a specific row you must cache the results in a data structure on the client and use that (if the table is big you might need a lot of memory, and things can get slow).If you know how many rows you will be getting you can use an array of arrays, otherwise a Vector of arrays (you know how many columns you have but not how many rows).If you need to do it because you need to show table data you can insert all the rows in a DefaultTableModel (or your implementation of the TableModel interface) with this DefaultTableModel method:public void addRow(Object[] rowData)

Page 61: Jdbc Faq From Jguru

Anyway here are some methods of Resultset you can use.

Javadoc:

/***************************************************/public boolean next() throws SQLException

Moves the cursor down one row from its current position. A ResultSet cursor is initially positioned before thefirst row; the first call to next makes the first row the current row; the second call makes the second row thecurrent row, and so on.

If an input stream is open for the current row, a call to the method next will implicitly close it. The ResultSet'swarning chain is cleared when a new row is read.

/***************************************************/public boolean previous() throws SQLException

JDBC 2.0

Moves the cursor to the previous row in the result set.

/***************************************************/public boolean relative(int&#160;rows) throws SQLException

JDBC 2.0

Moves the cursor a relative number of rows, either positive or negative. Attempting to move beyond thefirst/last row in the result set positions the cursor before/after the the first/last row. Calling relative(0) isvalid, but does not change the cursor position.

/***************************************************/public boolean first() throws SQLException

JDBC 2.0

Moves the cursor to the first row in the result set.

/***************************************************/public boolean last() throws SQLException

JDBC 2.0

Moves the cursor to the last row in the result set.

/***************************************************/

Page 62: Jdbc Faq From Jguru

public boolean absolute(int&#160;row) throws SQLException

JDBC 2.0

Moves the cursor to the given row number in the result set.

If the row number is positive, the cursor moves to the given row number with respect to the beginning of theresult set. The first row is row 1, the second is row 2, and so on.

If the given row number is negative, the cursor moves to an absolute row position with respect to the end ofthe result set. For example, calling absolute(-1) positions the cursor on the last row, absolute(-2)indicates the next-to-last row, and so on.

An attempt to position the cursor beyond the first/last row in the result set leaves the cursor before/after thefirst/last row, respectively.

Note: Calling absolute(1) is the same as calling first(). Calling absolute(-1) is the same as callinglast().

/***************************************************/

Refer to the java.sql.Resultset documentation for details and other methods.

What is the difference between client and server database cursors? Location: http://www.jguru.com/faq/view.jsp?EID=42137 Created: Apr 28, 2000 Modified: 2000-04-28 19:49:56.683Author: Richard Katz (http://www.jguru.com/guru/viewbio.jsp?EID=25710) Question originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

What you see on the client side is the current row of the cursor which called a Result (ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on the server side.

Are prepared statements faster because they are compiled? if so, where and when are they compiled? Location: http://www.jguru.com/faq/view.jsp?EID=42139 Created: Apr 28, 2000 Modified: 2000-04-28 19:52:07.157Author: Richard Katz (http://www.jguru.com/guru/viewbio.jsp?EID=25710) Question originally posed by sharma MR (http://www.jguru.com/guru/viewbio.jsp?EID=4939

Prepared Statements aren't actually compiled, but they are bound by the JDBC driver. Depending on the driver, Prepared Statements can be a lot faster - if you re-use them. Some drivers bind the columns you request in the SQL statement. When you execute Connection.prepareStatement(), all the columns bindings take place, so the binding overhead does not occur each time you run the Prepared Statement. For additional information on Prepared Statement performance and binding see JDBC Performance Tips on IBM's website.

Page 63: Jdbc Faq From Jguru

Does JDBC have support for Bulk copy utilities provided by RDBMS products.Location: http://www.jguru.com/faq/view.jsp?EID=46395 Created: May 8, 2000 Modified: 2000-05-09 11:21:02.89Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Lakshmy Ganapathy (http://www.jguru.com/guru/viewbio.jsp?EID=11922

Most of the major databases have export, import and/or bulk load utility programs. These are generally listed under administrative tools and utilities, and can be accessed via program calls and APIs. These utilities are not only outside of JDBC, but in some sense outside SQL, in the sense of meeting any standard. So the standards based answer is no.

There are some possibilities ( untried. )

From the The JDBC 1.2 Specification: "JDBC allows any query string to be passed through to an underlying DBMS driver." So, in theory, a JDBC driver could apply the passed string to a bulk load utility. I'm not aware of any that do this and it would be far from standard.

Some databases MAY allow utilities to be called from a stored procedure, so a standard call would work in this case. In the same vein, some databases allow creation of user defined functions that may be used in the same way.

An alternative available with JDBC 2.0 compliant drivers is batch updates, which "allows multiple update operations to be submitted to a database for processing at once." ( JDBC 2.0 specification. )

Where can I find a list of the possible SQLStates returned by SQLException.getSQLState()? Can I use SQLState instead of/in addition to vendor specific codes to determine what went wrong? Location: http://www.jguru.com/faq/view.jsp?EID=46397 Created: May 8, 2000 Modified: 2002-02-26 11:21:18.791Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Henrik Hermansson (http://www.jguru.com/guru/viewbio.jsp?EID=44407

Official documents that include SQLStates can obviously be purchased, at a relatively high price, from ANSI and XOpen.

But, the documentation for most databases have lists of SQLStates. Probably the most complete ( and accessible ) online listings are in the DB2 manuals. Check the DB2 Universal Messages manual, for instance. Oracle ( TechNet password required ) and Sybase, among others, also have online listings.

As to the second question, this is the intent of SQLState, however, the various databases have varying degrees of compliance. For example, some map multiple native error messages to the same SQLState. For generic use, one should probably concentrate on the major code ( the first two characters of SQLState, ) then determine if more specific info is available in the minor code ( beyond 000. )

Comments and alternative answers

Page 64: Jdbc Faq From Jguru

SQL 92 SPec Author: Euzenot Hubert (http://www.jguru.com/guru/viewbio.jsp?EID=523840), Mar 4, 2002I would strongly advise you to have a look at the SQL92 Spec. here for example http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt, you will find definition of the basic SQLstates

Which Oracle JDBC driver should I use in applets?Location: http://www.jguru.com/faq/view.jsp?EID=49521 Created: May 15, 2000 Modified: 2000-09-14 08:28:32.694Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Oracle basically has two JDBC drivers: an OCI driver which includes native code and a Thin driver which is 100% Pure Java. Since the OCI driver includes native code, it cannot be used in applets. You must use thin driver. You can get all Oracle JDBC drivers from http://technet.oracle.com/software/tech/java/sqlj_jdbc/software_index.htm.

Is it possible to connect to multiple databases simultaneously? Can one extract/update data from multiple databases with a single statement?Location: http://www.jguru.com/faq/view.jsp?EID=53814 Created: May 22, 2000 Modified: 2000-05-22 11:49:29.745Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

In general, subject, as usual, to the capabilities of the specific driver implementation, one can connect to multiple databases at the same time. At least one driver ( and probably others ) will also handle commits across multiple connections. Obviously one should check the driver documentation rather than assuming these capabilities.

As to the second part of the question, one needs special middleware to deal with multiple databases in a single statement or to effectively treat them as one database. DRDA ( Distributed Relational Database Architecture -- I, at least, make it rhyme with "Gerta" ) is probably most commonly used to accomplish this.

Oracle has a product called Oracle Transparent Gateway for IBM DRDA and IBM has a product called DataJoiner that make multiple databases appear as one to your application. No doubt there are other products available. XOpen also has papers available regarding DRDA.

Is Connection thread safe for Oracle drivers? Location: http://www.jguru.com/faq/view.jsp?EID=54794 Created: May 23, 2000 Modified: 2000-05-23 16:07:54.017Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Semen Meshcheryakov (http://www.jguru.com/guru/viewbio.jsp?EID=4894

Because of changing technology and the database and goals of the particular driver developer, it is always best to check the actual ( and current ) driver documentation; In this case check Oracle's site.

Page 65: Jdbc Faq From Jguru

However, the spec confirms that for JDBC Compliant(tm) drivers "We require that all operations on all the java.sql objects be multi-thread safe and able to cope correctly with having several threads simultaneously calling the same object." The spec goes on to give an example with a connection. The bad news is that concurrency MAY be achieved by serial behavior. For further information, see the JDBC Specification, Chapter 9 - Asynchrony, Threading, and Transactions, section 9.2.

Will SQLJ work with any JDBC driver?Location: http://www.jguru.com/faq/view.jsp?EID=55746 Created: May 24, 2000 Modified: 2000-05-26 01:26:03.928Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Yes, there are no special requirements to get SQLJ to work on top of any JDBC driver. Specifically, SQLJ does not require a JDBC 2.x compliant driver.

Where do I get SQLJ?Location: http://www.jguru.com/faq/view.jsp?EID=55754 Created: May 24, 2000 Modified: 2000-05-24 12:17:29.646Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Vendor implementations are available from http://www.sqlj.org/implement.htm.

Are there any tutorials on SQLJ available?Location: http://www.jguru.com/faq/view.jsp?EID=55760 Created: May 24, 2000 Modified: 2000-05-24 12:18:28.098Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

SQLJ.org has a tutorial available (as a set of online slides) at http://www.sqlj.org/tutorials/sqlj-sigmod/index.htm.

Are there any books out that cover SQLJ?Location: http://www.jguru.com/faq/view.jsp?EID=57309 Created: May 26, 2000 Modified: 2000-05-26 01:56:31.625Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

A quick search as of late May, 2000 turns up 4 books, 3 of which are completely devoted to SQLJ at fatbrain. A couple of these are also available at bookpool. IBM's redbooks site also has 4 freely downloadable redbooks with sections on SQLJ.

Because new books come out often and existing books become outdated quickly, I prefer to give easily searchable sites if possible ( all of these came up with a simple "SQLJ" search at each site ) rather than specific titles -- unless someone knows a classic.

Comments and alternative answers

Check out the Understanding SQL and Java Together :... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Aug 5, 2000

Page 66: Jdbc Faq From Jguru

Check out the Understanding SQL and Java Together : A Guide to SQLJ, JDBC, and Related Technologies offering. It looks very promising.

Another book out on the topic: Oracle8i SQLJ Progr... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Oct 11, 2000Another book out on the topic: Oracle8i SQLJ Programming. See DevX for a review.

What mailing lists, forums and other resources are available for information about SQLJ?Location: http://www.jguru.com/faq/view.jsp?EID=57330 Created: May 27, 2000 Modified: 2000-05-27 20:48:26.662Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

The Oracle Technet site has some articles that may be of some use - including a FAQ and technical documentation.

Where can I find online documentation for database xyz?Location: http://www.jguru.com/faq/view.jsp?EID=59007 Created: May 28, 2000 Modified: 2000-12-05 21:43:21.697Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

This list is not comprehensive ( more welcome ) but hits the documentation for the major database engines.

IBM DB2 and DB2 Universal

Informix

Microsoft SQL Server

Oracle

Sybase

What is, technically, a non-repeatable read?Location: http://www.jguru.com/faq/view.jsp?EID=59026 Created: May 29, 2000 Modified: 2000-05-29 00:11:45.433Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

One of the ISO-ANSI SQL defined "phenomena" that can occur with concurrent transactions. If one transaction reads a row, then another transaction updates or deletes the row and commits, the first transaction, on re-read, gets modified data or no data. This is an inconsistency problem within a transaction and addressed by isolation levels.

Page 67: Jdbc Faq From Jguru

What is a phantom insert? Location: http://www.jguru.com/faq/view.jsp?EID=59028 Created: May 29, 2000 Modified: 2000-05-29 00:12:34.473Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

One of the ISO-ANSI SQL defined "phenomena" that can occur with concurrent transactions. If one transaction selects a set of rows, then another transaction inserts rows that meet the same criteria, when the first transaction re-executes the query, a different set results. This is an inconsistency problem within a transaction and addressed by isolation levels.

How does one manage concurrency issues with JDBC? Location: http://www.jguru.com/faq/view.jsp?EID=59102 Created: May 29, 2000 Modified: 2000-05-29 02:57:01.45Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Richard Goh Muk Ling (http://www.jguru.com/guru/viewbio.jsp?EID=18858

JDBC is based on ISO-ANSI SQL, which provides for database concurrency using isolation levels. These are defined to deal with the "phonema" of dirty reads, non-repeatable reads and phantom inserts. "The four isolation levels guarantee that each SQL-transaction will be executed completely or not at all, and that no updates will be lost." While almost all programs will be concerned with dirty reads, in the real world we probably want to use and see the most current data, so non-repeatable reads and phantom inserts may not be an issue. Here's a table that briefly summarizes what the defined isolation levels guarantee:

Isolation Level Dirty ReadNon-Repeatable Read

Phantom Insert

Read Uncommitted Possible Possible Possible

Read Committed Not Possible Possible Possible

Repeatable Read Not Possible Not Possible Possible

Serializable Not Possible Not Possible NotPossible

In JDBC, the isolation level is set by Connection.setTransactionIsolation(int level) with the default being auto-commit. Note that a particular database may not support all isolation levels ( DatabaseMetaData.supportsTransactionIsolationLevel(int) will validate a particular isolation level. ) Also, isolation level is a Connection property; this means that it applies to all Statements created by a Connection, and that a commit or rollback also applies to all Statements.

A complete explanation could take a several chapters in a book, so take a look at Where can I find online documentation for database xyz? for more information.

Finally, isolation levels are more concerned with data integrity in the face of concurrent transactions, than with allowing concurrent access for many users of the database.

Page 68: Jdbc Faq From Jguru

Can ResultSets and Connections be passed around like other objects? Location: http://www.jguru.com/faq/view.jsp?EID=59456 Created: May 29, 2000 Modified: 2000-05-29 11:12:11.681Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Venkata R Kotte (http://www.jguru.com/guru/viewbio.jsp?EID=20756

Yes, although, as usual, technically we are passing object references. However, there is a chain of dependency that must be kept in mind and should be tracked for Connection, Statement and ResultSet.

For example, If a ResultSet is is not scrollable, rows already read are not available, so passing the same ResultSet to different methods may not work as expected. If the originating Statement is closed, the ResultSet is generally no longer viable.

If there are multiple Statements on a Connection, a commit will affect all of them. Addtionally, as seen in Is Connection thread safe for Oracle drivers?, a Connection may carry out its requirement to be threadsafe by executing Statements serially.

Last ( although not exhaustively, ) once a Connection is closed, all associated Statements and ResultSets are effectively closed as well.

What is the best way to provide a unique identifier as a primary key that will work in a database independent manner? I'm looking for functionality similar to Oracle's proprietary MY_SEQ.NEXTVAL.Location: http://www.jguru.com/faq/view.jsp?EID=59469 Created: May 29, 2000 Modified: 2000-05-29 11:44:17.799Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Pankaj Tandon (http://www.jguru.com/guru/viewbio.jsp?EID=50563

The "best way" probably lies in the eye of the beholder and/or the requirements of the particular application. Here are some possibilities in no particular order:

1) For databases that support them, an insert trigger or stored procedure that uses a proprietary means such as MY_SEQ.NEXTVAL OR that uses one of the following methods.

2) Use a server socket whose job is to control and hand out new identifiers, either with proprietary means or one of the following.

3) Use a singleton object whose job is to control and hand out identifiers. The identifiers would typically be tracked in a table containing a row for each table in the database which uses this mechanism. Each row would have the affected table name as the key and a numeric column containing the next key. The singleton can get identifiers one at a time or in groups ( at the potential price of skipping some identifiers. )

4) Do the same as 3 in your own individual classes.

For 2), 3) and 4) either the supporting mechanism or your individual classes must be prepared to handle identifier clashes, since there is no way to guarantee that all database operations will use this mechanism in a production environment.

Page 69: Jdbc Faq From Jguru

Other suggestions have included random numbers with checks for clashes and trying to generate a totally unique number internally. The problem with the last is complexity and the size of the generated key, which can impact performance.

Comments and alternative answers

You can also use the java.server.rmi.UID object to... Author: Toby Hede (http://www.jguru.com/guru/viewbio.jsp?EID=326325), Mar 6, 2001You can also use the java.server.rmi.UID object to generate uids as follows:

import java.rmi.server.UID

UID uid = new UID(); String id = uid.toString();

How can I design my servlet/JSP so that query results get displayed on several pages, like the results of a search engine? Each page should display, say, 10 records each and when the next link is clicked, I should see the next/previous 10 records and so on. Location: http://www.jguru.com/faq/view.jsp?EID=60818 Created: May 31, 2000 Modified: 2000-10-03 10:16:08.397Author: Richard Raszka (http://www.jguru.com/guru/viewbio.jsp?EID=7963) Question originally posed by arun prathap (http://www.jguru.com/guru/viewbio.jsp?EID=43168

Use a Java Bean to store the entire result of the search that you have found. The servlet will then set a pointer to the first line to be displayed in the page and the number of lines to display, and force a display of the page. The Action in the form would point back to the servlet in the JSP page which would determine whether a next or previous button has been pressed and reset the pointer to previous pointer + number of lines and redisplay the page. The JSP page would have a scriplet to display data from the Java Bean from the start pointer set to the maximum number of lines with buttons to allow previous or next pages to be selected. These buttons would be displayed based on the page number (i.e. if first then don't display previous button).

Joe Sam Shirah adds:

There are many of methods to accomplish this. One way is to use the Pager Tag Library, recently discussed at Implementing Page Scrolling on the servlet mailing list. You may also want to look through the list Archives for other ideas. Comments and alternative answers

The problem with the ResultSet object in the JDBC1.2.2... Author: Alexandros Kotsiras (http://www.jguru.com/guru/viewbio.jsp?EID=64209), Jun 3, 2000The problem with the ResultSet object in the JDBC1.2.2 version is that it is not scrollable. It is scrollable in the latest JDBC2.0 version which only the latest

Page 70: Jdbc Faq From Jguru

versions of the RDBMS support. Note that you can still use a JDBC2.0 Type 4 driver (eg. classes12.zip for Oracle) with an RDBMS that does not support JDBC2.0 features (like Oracle 8.1.5) but you won't be able to use the new JDBC2.0 functionality. The new features can only be used if the RDBMS supports them by itself like Oracle 8.1.6.

I found very useful the CachedRowSet API from Sun which is an extension to java.sql. After you create your ResultSet object you wrap it arround a CachedRowSet object which is disconnected and scrollable. It's like putting all you result records in a Collection object but the CachedRowSet does this job for you plus it offers all the methods that you need to scroll like : next(), previous(), relative(numberOfRows), getRow(rowPosition), size() (to determine the number of records in your ResultSet) etc.

Then you just need to put it in the users session, retrieve from the next page, scroll to the appropriate position and display a range of records.

The above approach might not be the appropriate one if you have a very large ResultSet since the CachedRowSet object that you will store in the session will take a lot of memory. For ResultSets of some hundrends of records you should be fine. It can be downloaded from the Sun/JDBC page at http://java.sun.com/products/jdbc/

The approaches discussed above are good for a few ... Author: jeyabalan sethuraman (http://www.jguru.com/guru/viewbio.jsp?EID=120328), Aug 5, 2000The approaches discussed above are good for a few hundreds of records as mentioned above. What is the best approach when the result set is huge ( for example, more than 10000 records ) ?

As noted above, there are many ways to do this, but... Author: yogesh tk (http://www.jguru.com/guru/viewbio.jsp?EID=200141), Oct 6, 2000As noted above, there are many ways to do this, but all basically involve storing a variable in order to know which set of records is to be shown next. Following are three methods of storing the count:

1. Keep the count in the session.2. Keep a hidden field in the page.3. Place this count in the URL as a part of the QueryString.

The servlet then uses the count in its logic to determine the next set of records to display.

Having had the same problem I found that in PostgreSQL... Author: Tarmo Kallas (http://www.jguru.com/guru/viewbio.jsp?EID=227773), Oct

Page 71: Jdbc Faq From Jguru

13, 2000Having had the same problem I found that in PostgreSQL database one can make SQL-queries so that resultSet returns only records from certain record to certain record (e.g. records 5->10)  In SELECT statement one needs only add LIMIT and OFFSET atributes (e.g. 'SELECT * FROM table_name ORDER BY one_field_name LIMIT 5 OFFSET 5' this statement should return the records from 5 to 10 in table_name table when sorted by one_field_name field).

See the LIMIT CLAUSE documentation in the PostgreSQL documentation for additional information.

I have never been able to figure out if there is any... Author: martin smith (http://www.jguru.com/guru/viewbio.jsp?EID=260406), Dec 31, 2000I have never been able to figure out if there is any way to have the DBMS retain a scrollable cursor/resultset and feed only parts of it to the client or mid-tier.

This is NOT the same as re-executing the query and somehow restricting the number of values returned to a page-full.

I actually want the resultset retained on the server side, since it seems this would be MUCH more efficient for complex ad-hoc multi-table join queries on large tables (which is what we do.)

Is this implementable within Oracle?

Re: I have never been able to figure out if there is any... Author: Prasoon Kumar Choudhary (http://www.jguru.com/guru/viewbio.jsp?EID=588711), Dec 18, 2001There are many solutions to this problem. I agree that if the result set is a too large, storing 1000 of record in session will not be a good idea. Better solution will be to get record from database for each page. If you are working with mysql there is a limit key work that will help you the featch for the particular page. On oracle there is no such keyword but there is a query throught which you can select record form middle of the total selected record for your search condition. say you are fetching emp name from emp table and you want names from 20th to 30th record for a search criteria say in emp in city newyork. The query will be select x.emp_name from (select rownum y, emp_name from emp where city='newyork')x where x.y between 20 and 30;

I have used this many time in my projects

Re[2]: I have never been able to figure out if there is any... Author: Ajay Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=746666), Feb 4, 2002Hi Prasoon , U are absolutely right , but the this is possible only in

Page 72: Jdbc Faq From Jguru

MYSQL .But if U see Oracle , it isn't possible. I feel there are a number of ways U can do this and it all depends upon the application requirements. Ajay Sharma

Re[3]: I have never been able to figure out if there is any... Author: Prasoon Choudhary (http://www.jguru.com/guru/viewbio.jsp?EID=264897), Feb 5, 2002The query you see above works with oracle. Rownum ect is part of oracle sql implementation. On Mysql you do not have rownum if you are working with mySql use Limit keword

Re[4]: I have never been able to figure out if there is any... Author: Robert Williams (http://www.jguru.com/guru/viewbio.jsp?EID=1080681), Apr 30, 2003How about for Microsoft SQL Server? Is there any keyword like rownum or limit?

Re[2]: I have never been able to figure out if there is any... Author: E L (http://www.jguru.com/guru/viewbio.jsp?EID=819637), Apr 1, 2002

this sounds like a good idea but how can i retrieve the total number of records even after I set the rownum range?eg. select rownum y, emp_name from emp where city='newyork' the total number of employees.

I need to retrieve the total number so that I can determine the number of pages needed to display all the records. (with PageCount=RecordSize/PageSize) where PageSize is the rownum range.

Pls help..

Re[3]: I have never been able to figure out if there is any... Author: Prasoon Choudhary (http://www.jguru.com/guru/viewbio.jsp?EID=264897), Apr 1, 2002You will have you fire a select count(*) from emp where city='newyork' before that. you can store this count in session so that you dont have to do this for every page. This will work well for most of the cases where count will not change very frequently i,e there is not much insert or delete taking place on the table.

"select x.emp_name from (select rownum y, emp_name from emp where city='newyork')x where x.y between 20 and 30;" Author: X F (http://www.jguru.com/guru/viewbio.jsp?EID=887397), May 28, 2002select emp_name from emp where city = 'newyork' and rownum < 31

Page 73: Jdbc Faq From Jguru

MINUS select emp_name from emp where city = 'newyork' and rownum < 20

this clause will perform better, i think so but no test.

Re: "select x.emp_name from (select rownum y, emp_name from emp where city='newyork')x where x.y between 20 and 30;" Author: segmoti segmoti (http://www.jguru.com/guru/viewbio.jsp?EID=415596), Jun 15, 2002One of the issues I find (in the query you have given with a minus clause) is inability to sort by using 'order by' clause. For a query like 'select emp_name from emp where city = 'newyork' and rownum < 20 order by emp_name' 'Rownum' is executed before the order by clause. So if I put both rownum and order by in a query, then oracle first gets the set of rows as evaluated using rownum and then sorts it. Whereas behaivor I require is that sort the records first and then use rownum to limit the rows. Any idea how to get past it? Regards Mohit

Good Sql,but can not execute under ODBC for access Author: Jeason Zhao (http://www.jguru.com/guru/viewbio.jsp?EID=1037417), Dec 13, 2002Good Sql,but can not execute under ODBC for access

Re[2]: I have never been able to figure out if there is any... Author: HAKAN YILDIZ (http://www.jguru.com/guru/viewbio.jsp?EID=1175989), Jun 3, 2004what about if I have a query containing a group by clause in it. My query is : select /*+ ALL_ROWS +*/ policeno pno,bitistarih bittar,Sum(primfark) prim,sum(komisyonfark) komisyon from police where statu='E' and baslangictarih<to_date'01/05/2005','dd/MM/yyyy') and bitistarih>=to_date('01/05/2005','dd/MM/yyyy') group by policeno,bitistarih order by policeno )pol this query gets about 2 million rows and I go through these rows for calculating something,and my compiler(jdk 1.3.1) gives an outofmemory exception in the middle. I dont want to increase heap size of jvm . I want to get rows in three or more parts like the example you gave. but as I mentioned I have a group by clause in my query and I am forced to put rownum into groupby. if I do that I got wrong data from query ! has anybody suggestion about this. thanks lot.

See also Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Feb 13, 2002

How can I cache the results of my servlet, so the next request doesn't have to go through all the calculation / database access / other time-consuming stuff all over again?

Page 74: Jdbc Faq From Jguru

Search Reasult Author: Birendar Waldiya (http://www.jguru.com/guru/viewbio.jsp?EID=1131260), Dec 1, 2003One more way to acheive the result, in a page wise display of page r is by using Scrollable ResultSet every time you want to get the next page shift the cursor to that particular point in ResultSet.absolute(int) method.

How can I ensure that database security is applied to the current user when I use a connection pool since the connections are created with a default user ID and password?Location: http://www.jguru.com/faq/view.jsp?EID=61453 Created: May 31, 2000 Modified: 2000-05-31 21:04:17.293Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Daniel Weimer (http://www.jguru.com/guru/viewbio.jsp?EID=25540

In general, you can't. Nearly all optimizations involve trade-offs and a large part of the developer's job is to select those that make the most sense under a given set of circumstamces. This is really a security question, which can easily evolve into a can of worms. I'll start with a quote from JDBC Performance Tips that connection pooling "may also be best suited to apps in which there is a certain class of users that can share connections... This would not be well-suited to apps in which each user had to have their own individual authority verified and used for the connection, since this would conflict with the concept of saving away connections for use by any number of users." While you may find some database engine that allows a temporary user, it certainly isn't a common or standard feature.

Most workable security involves groups or levels of users, so that a security conscious connection pool would probably set up connections based on group level passwords. If security is a concern, one should get or create a pool that works as hinted by the ConnectionPoolDataSource class JDBC 2.0 Optional Package. It has the method getPooledConnection(String user, String password). Clearly the intent is that classes of connections are created and when one is requested, the user and password is compared to those of current connections. If there is a request that doesn't match the group levels, a new connection is created and passed back. Of course, this raises the spector of a program having knowledge of passwords and potentially passing them around over the internet, bringing up another yet another security issue, which is probably best resolved by having the pool manager resident on the server.

Why do I get the exception: "ALTER TABLE only allows columns to be added which can contain nulls. Column 'F' cannot be added to table..." with this code?

stmt.executeUpdate("ALTER TABLE MYTABLE ADD F INTEGER"); Location: http://www.jguru.com/faq/view.jsp?EID=71063 Created: Jun 10, 2000 Modified: 2000-06-10 00:37:30.463Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Yoo-Jin Lee (http://www.jguru.com/guru/viewbio.jsp?EID=68179

Page 75: Jdbc Faq From Jguru

When one adds a column to an existing table with an ALTER TABLE statement, the database adds the column to every row and initializes the column to a value depending on the values supplied in the ADD (COLUMN) clause. If a default value is given, that value is applied; otherwise the column is set to null. SQL Server and some other databases have a current default for assuming NULL/NOT NULL constraints for new columns. If the current default is NOT NULL, but no default value is given in the ADD (COLUMN) clause, this error occurs because the database would otherwise set a null value in a NOT NULL column.

Is it possible to use Microsoft Access as the database while implementing entity beans? (Weblogic refuses to use the JDBC-ODBC bridge, since it needs a thin driver.) Location: http://www.jguru.com/faq/view.jsp?EID=70556 Created: Jun 10, 2000 Modified: 2000-06-16 08:15:11.171Author: Prasad Thammineni (http://www.jguru.com/guru/viewbio.jsp?EID=36479) Question originally posed by Nilesh Bhattad (http://www.jguru.com/guru/viewbio.jsp?EID=62514

You are right about the JDBC-ODBC bridge. Since it does not support multi-threading it is not of much use. But you can find 3rd-party drivers in the market that will allow you to work with MS Access from EJBs.

For a list of those drivers search for MS Access drivers from the following page:

http://industry.java.sun.com/products/jdbc/drivers.

How can I place a lock on a single row?Location: http://www.jguru.com/faq/view.jsp?EID=60956 Created: Jun 12, 2000 Modified: 2000-06-12 13:14:42.983Author: Geoff Sovde (http://www.jguru.com/guru/viewbio.jsp?EID=51938) Question originally posed by NAGARAJA SHARMA ROTTE (http://www.jguru.com/guru/viewbio.jsp?EID=50586

First, not all databases support row level locks, so check the documentation for your DMBS. If you are using Oracle, you can issue a select...for update statement. Make sure your JDBC connection has autocommit turned off- otherwise, you'll get an ORA-01002- "Fetch out of sequence" error. Here's an example:

String cmd = "SELECT * FROM my_table WHERE my_column_a = criteria FOR UPDATE OF my_column_b";

ResultSet rset = stmt.executeQuery(cmd);Zac Corbiere adds

The important bit is the 'for update' tagged on the end.

From your resultset invoke 'rs.getCursorName' and pass that back in to an update statement with 'where current of' like:

String updateStmt = "update foo set bar=\"FUBAR\" where current of " + rs.getCursorName();Comments and alternative answers

Page 76: Jdbc Faq From Jguru

How can I place a lock on a single row? Author: Murali Krishna (http://www.jguru.com/guru/viewbio.jsp?EID=109547), May 17, 2001If i lock a column using For Update statement with Select statement when it gets unlocked ??, after i do an update on that row and commit the transaction or when?

Re: How can I place a lock on a single row? Author: Markus Schneider (http://www.jguru.com/guru/viewbio.jsp?EID=438498), Jun 13, 2001Your lock is released after COMMIT or ROLLBACK.

How can I pass data retrieved from a database by a servlet to a JSP page?Location: http://www.jguru.com/faq/view.jsp?EID=73439 Created: Jun 12, 2000 Modified: 2000-08-14 11:16:49.756Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14) Question originally posed by senthil kumar (http://www.jguru.com/guru/viewbio.jsp?EID=57182

One of the better approaches for passing data retrieved from a servlet to a JSP is to use the Model 2 architecture as shown below:

Basically, you need to first design a bean which can act as a wrapper for storing the resultset returned by the database query within the servlet. Once the bean has been instantiated and initialized by invoking its setter methods by the servlet, it can be placed within the request object and forwarded to a display JSP page as follows:

com.foo.dbBean bean = new com.foo.dbBean(); //call setters to initialize bean req.setAttribute("dbBean", bean); url="..."; //relative url for display jsp page ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(req, res);

The bean can then be accessed within the JSP page via the useBean tag as:

<jsp:useBean id="dbBean" class="com.foo.dbBean"

Page 77: Jdbc Faq From Jguru

scope="request"/>...<% //iterate through the rows within dbBean and //access the values using a scriptlet%>

Also, it is best to design your application such that you avoid placing beans into the session unless absolutely necessary. Placing large objects within the session imposes a heavy burden on the performance of the servlet engine. Of course, there may be additional design considerations to take care of - especially if your servlets are running under a clustered or fault-tolerant architecture.

Comments and alternative answers

We currently are not allowed to use beans at our site.... Author: Doug Weems (http://www.jguru.com/guru/viewbio.jsp?EID=69536), Jun 13, 2000We currently are not allowed to use beans at our site. To communicate with servlets, we use something similiar to above code w/o the bean stuff. We pass information back and forth with the session object. It's clunky, but it works.

How can I read and write serialized objects to and from a database?Location: http://www.jguru.com/faq/view.jsp?EID=74403 Created: Jun 13, 2000 Modified: 2000-06-13 12:12:18.258Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588) Question originally posed by edwin abiraham (http://www.jguru.com/guru/viewbio.jsp?EID=41880

If your RDBMS supports them, you can store serialized objects as BLOBs.

These are JDBC 2.0 features, but take a look at java.sql.Blob, ResultSet and PreparedStatement for more information.

Comments and alternative answers

Storing Objects as Text Author: Scott McKinney (http://www.jguru.com/guru/viewbio.jsp?EID=727047), Jan 19, 2002You could store relatively small objects in VARCHAR fields by encoding the byte array e.g., using the Base64 encoding.

Alternatively, instead of using standard java serialization you might consider storing an object in XML using your own (or third-party) serialization scheme. Since the objects are stored in XML you have the benefit using VARCHAR fields as well.

Base64 Encoding

Page 78: Jdbc Faq From Jguru

Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685), Sep 24, 2002Open source, GPL implementation from com.Ostermiller.util:http://ostermiller.org/utils/Base64.htmlIt can encode and decode strings, byte arrays, files, and streams.

Open source, public domain encoder/decoder by Robert W. Harder:http://iharder.sourceforge.net/base64/Encodes to strings from several formats including byte arrays and strings. It has a method of encoding and decoding streams but it looks awkward.

Open source, freeware (except military) from Roedy Green's Java Glossary:http://mindprod.com/jglossbase64.htmlhttp://mindprod.com/products.html#BASE64Encodes from byte arrays to strings, decodes from strings to byte arrays.

Open source, GPL implementation by Kevin Kelley:http://kevinkelley.mystarband.net/java/goodies.htmlEncodes and decodes from byte arrays to byte arrays.

Open source, freeware (any purpose with attribution) by Bob Withers:http://www.ruffboy.com/download.htmEncodes and decodes from byte arrays to byte arrays and comes with C++ code too.

JavaWorld tip with annotated code and nifty graphic that shows how Base64 encoding works (license unknown). http://www.javaworld.com/javaworld/javatips/jw-javatip36-p2.htmlSupports byte array to byte array operations.

Why do I get an UnsupportedOperationException?Location: http://www.jguru.com/faq/view.jsp?EID=78054 Created: Jun 16, 2000 Modified: 2000-06-16 11:46:33.987Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

JDBC 2.0, introduced with the 1.2 version of Java, added several capabilities to JDBC. Instead of completely invalidating all the older JDBC 1.x drivers, when you try to perform a 2.0 task with a 1.x driver, an UnsupportedOperationException will be thrown. You need to update your driver if you wish to use the new capabilities.Comments and alternative answers

Thanks! Author: ax m (http://www.jguru.com/guru/viewbio.jsp?EID=944068), Jul 10, 2002I guess I have the same problem, and your solution seems... cool :)

Page 79: Jdbc Faq From Jguru

How do I set a default character encoding for file I/O operations, JDBC requests and so on?Location: http://www.jguru.com/faq/view.jsp?EID=78088 Created: Jun 16, 2000 Modified: 2001-08-18 17:31:58.349Author: Sandip Chitale (http://www.jguru.com/guru/viewbio.jsp?EID=14537) Question originally posed by Dmitry Popov (http://www.jguru.com/guru/viewbio.jsp?EID=45003

The default encoding used by locale/encoding sensitive API in the Java libraries is determined by the System property "file.encoding". This system property is initialized by the JVM startup code after querying the underlying native operating system. For example on my English USA NT box it is initialized to: Cp1252 It is generally recommended that you do not modify it. However if you know what you are doing you could override the system property either on the command line using the -

java -Dfile.encoding=...

syntax or programmatically at startup.

Here is the reference URL for supported encodings -

http://java.sun.com/products/jdk/1.2/docs/guide/internat/ encoding.doc.html

You may also find Sun's online tutorial helpful: http://java.sun.com/docs/books/tutorial/i18n/index.html

Comments and alternative answers

For an example of non-default file encoding and links... Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Jun 16, 2000For an example of non-default file encoding and links to supported encodings ( and this can be done with Strings as well, ) see:

How can I store and retrieve Unicode or Double Byte data in a file using the java.io libraries?

How can I store and retrieve Unicode or Double Byte data in a database using JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=79756 Created: Jun 18, 2000 Modified: 2000-07-25 17:34:57.98Author: Kalyanaraman Parthasarathy (http://www.jguru.com/guru/viewbio.jsp?EID=61494) Question originally posed by Tian Hao (http://www.jguru.com/guru/viewbio.jsp?EID=56209

The underlying DBMS must support Unicode or the desired encoding. Internally, Java data are stored as Unicode only. So, if the Database supports Unicode and the table was created that way, the data will be written to the encoding of the table. Nothing

Page 80: Jdbc Faq From Jguru

needs to be done specifically, because the driver will handle the translation. See Supported Encodings and your DBMS documentation for more on encodings, code pages and so on.

What advantage is there to using prepared statements if I am using connection pooling or closing the connection frequently to avoid resource/connection/cursor limitations?Location: http://www.jguru.com/faq/view.jsp?EID=92138 Created: Jun 30, 2000 Modified: 2000-06-30 09:13:17.884Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by arun anand (http://www.jguru.com/guru/viewbio.jsp?EID=78217

The ability to choose the 'best' efficiency ( or evaluate tradeoffs, if you prefer, ) is, at times, the most important piece of a mature developer's skillset. This is YAA ( Yet Another Area, ) where that maxim applies. Apparently there is an effort to allow prepared statements to work 'better' with connection pools in JDBC 3.0, but for now, one loses most of the original benefit of prepared statements when the connection is closed. A prepared statement obviously fits best when a statement differing only in variable criteria is executed over and over without closing the statement.

However, depending on the DB engine, the SQL may be cached and reused even for a different prepared statement and most of the work is done by the DB engine rather than the driver. In addition, prepared statements deal with data conversions that can be error prone in straight ahead, built on the fly SQL; handling quotes and dates in a manner transparent to the developer, for example.

Portions of this answer are based on input from William Crawford and Craig R. McClanahan.

Comments and alternative answers

PreparedStatements with a pool. Author: glenn bullock (http://www.jguru.com/guru/viewbio.jsp?EID=846081), May 7, 2002I have a PS pool in my connection pool class that stores them in a map. When I need one, I pull it out of the map (so no other thread tries to use it), and plug it back in when I'm done. If it's being used, then I create a new one.

I think the connection pool scenario is the more common of the two that you mentioned. HTH

What is JDBC, anyhow?Location: http://www.jguru.com/faq/view.jsp?EID=92327 Created: Jun 30, 2000 Modified: 2000-06-30 15:01:47.853Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

Page 81: Jdbc Faq From Jguru

JDBC is Java's means of dynamically accessing tabular data, and primarily data in relational databases, in a generic manner, normally using standard SQL statements. While most developers think of it as Java Database Connectivity, actually JDBC is the trademarked name and is not an acronym. JDBC is based on the X/Open SQL Command Level Interface ( CLI ) and the API is composed of interfaces that allow the same code to run against any data(base) that has a supporting JDBC driver. JDBC drivers, of which there are four types, are loaded at runtime and provide the implementation of the JDBC API interfaces.

If you are just beginning with JDBC, a good place to start is in the JDK documentation, which includes the JDBC(tm) Technology Guide: Getting Started, the specs and links to basic and advanced tutorials. For information regarding specific databases, see "Where can I find online documentation for database xyz?" and for general information, you are already in the right place.

When I retrieve data from EBCDIC based machines, particularly IBM mainframes and AS/400s, sometimes I get what appears to be garbage. Why and how do I resolve the issue? Location: http://www.jguru.com/faq/view.jsp?EID=92410 Created: Jun 30, 2000 Modified: 2000-07-01 18:42:04.364Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

These machines use CCSIDs ( Coded Character Set Identifiers ) for National Language Support. While in general, data will be converted sensibly for Java, under certain conditions data will be created, often inadvertently, with a CCSID of 65535. This code means "binary data, do not convert." While the best answer is to get the data to a proper CCSID, this is not always possible and a good JDBC driver for these platforms will have a property like "convert binary" or "translate CCSID 65535 data." Set this property and the garbage ( which is actually EBCDIC data being displayed on an ASCII machine, ) becomes good data.

Could we get sample code for retrieving more than one parameter from a stored procedure? Location: http://www.jguru.com/faq/view.jsp?EID=93232 Created: Jul 1, 2000 Modified: 2000-07-02 08:06:01.675Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Sakthivelu Sivaraman (http://www.jguru.com/guru/viewbio.jsp?EID=70819

Assume we have a stored procedure with this signature:

MultiSP (IN I1 INTEGER, OUT O1 INTEGER, INOUT IO1 INTEGER)

The code snippet to retrieve the OUT and INOUT parameters follows:

CallableStatement cs = connection.prepareCall( "(CALL MultiSP(?, ?, ?))" );

cs.setInt(1, 1); // set the IN parm I1 to 1cs.setInt(3, 3); // set the INOUT parm IO1 to 3

cs.registerOutParameter(2, Types.INTEGER); // register the OUT parm O1

Page 82: Jdbc Faq From Jguru

cs.registerOutParameter(3, Types.INTEGER); // register the INOUT parm IO1

cs.execute();int iParm2 = cs.getInt(2);int iParm3 = cs.getInt(3);cs.close();

The code really is just additive; be sure that for each IN parameter that setXXX() is called and that for each INOUT and OUT parameter that registerOutParameter() is called.Comments and alternative answers

Erase parenthesis Author: Amaury Quintero (http://www.jguru.com/guru/viewbio.jsp?EID=895098), Jul 31, 2002Hello Your code with parenthesis before call has a problem, better erase parenthesis that enclose CALL Best Regards

How can I find out the names of the ODBC data sources available through the JDBC-ODBC driver?Location: http://www.jguru.com/faq/view.jsp?EID=94778 Created: Jul 5, 2000 Modified: 2000-07-05 07:29:28.011Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is no Pure Java mechanism to get this information. If you don't mind locking yourself into the Microsoft VM, the following program demonstrates: import com.ms.wfc.app.*;public class ODBCSource { public static void main(String args[]) { RegistryKey regKey = Registry.CURRENT_USER.getSubKey ("Software\\ODBC\\ODBC.INI\\ODBC Data Sources"); if (regKey != null) { String dsn[] = regKey.getValueNames(); for(int i = 0; i < dsn.length; i++) { System.out.println(dsn[i]); } } }}

What considerations should be reviewed when using MS Access as opposed to a standards based RDBMS/ODBMS?Location: http://www.jguru.com/faq/view.jsp?EID=104132 Created: Jul 17, 2000 Modified: 2000-07-25 18:03:43.437Author: James House (http://www.jguru.com/guru/viewbio.jsp?EID=104094) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

Page 83: Jdbc Faq From Jguru

1 - Access is very limited as to the number of records it can manage. Once the database gets to be near the size of 1 megabyte, Access is notorious for data corruption.

2 - Access is not "thread safe" - only one connection to the database can be used at a time.

3 - Access has poor performance (speed-wise.)

4 - Access does not support complicated SQL joins and other features.Comments and alternative answers

Access can be a great tool used properly. However,... Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Jul 25, 2000Access can be a great tool used properly. However, in addition to the above comments, SQL compliance is iffy and Access is not really a DBMS. To quote Microsoft/Microsoft sponsored mouths:

"Access targets the desktop category and works best for individuals and workgroups managing megabytes of data. For multiuser access to the same database, Access uses file-server architecture, rather than client-server architecture."

"Before Access 2000, users and developers were using the Jet data engine, whether they knew it or not." BTW, this does not imply that people are not still using Jet if they take the default installation.

If one goes to the MSDN Search Page and performs a boolean search with "Access AND SQL", many articles appear. Here are some samples regarding compliance and migration considerations that might make you think about using Access in a production environment, particularly if you ever need to go to the real thing:

Microsoft Access and SQL Integration Resources

A More Powerful SQL

Migrating the Duwamish Books Access Database to SQL Server

Microsoft SQL Server: Microsoft Access 2000 Data Engine Options

I have a requirement to store Chinese, Japanese, Korean and more data in SQL Server. How? Location: http://www.jguru.com/faq/view.jsp?EID=114155 Created: Jul 29, 2000 Modified: 2000-07-29 13:48:07.302Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question

Page 84: Jdbc Faq From Jguru

originally posed by Mohammed Khadeer Ahmed (http://www.jguru.com/guru/viewbio.jsp?EID=111146

Most database engines support double byte character sets ( DBCS ) and this was the primary method of supporting these languages in the past. While this is generally still available, Unicode is probably a better answer now, along with some efficiency gain in Java.

For SQL Server specifically, one can use the nchar, nvarchar and ntext types to support Unicode. See Using Unicode Data for an overview. For more information, see: Where can I find online documentation for database xyz?, along with Unicode related questions in the FAQ.

Comments and alternative answers

Storing Multi-Language data in SQL Server Author: Karthik Gopal (http://www.jguru.com/guru/viewbio.jsp?EID=423274), May 28, 2001Making the column data types as nchar, nvarchar and ntext solves the problem from the SQL Server end, but from the Java application end it is still there, as the SQL Server Driver and SQL Server support UCS-2 while java supports UTF-8 and doesn't support UCS-2. Any help with regard to this problem would be appreciated.

Re: Storing Multi-Language data in SQL Server Author: Atul Pitroda (http://www.jguru.com/guru/viewbio.jsp?EID=805786), Mar 20, 2002hi karthik, i am solving same problem as in my textboxes i can enter korean characters but it stores in sql server in a different wat though we tried utf-8,euc-kr character sets in jsp and changing code pages in sql server. so if you get the solution please mail me at [email protected] Atul

Re[2]: Storing Multi-Language data in SQL Server Author: Brian Snyder (http://www.jguru.com/guru/viewbio.jsp?EID=1012328), Oct 15, 2002Has anyone found a successful way to store a currency symbol in any database and display it successful in a Java GUI?

Currently, we have no problem storing the EURO, loading it from within a SQL server on Windows platorm, and displaying in a GUI. The problem occurs when we use a Linux driver to load from the database. Have you seen this type of problem as well?

Thanks in advance for your help.

regards,Brian SnyderJava DeveloperSCJ2P

Page 85: Jdbc Faq From Jguru

Cetova Corp.W 201-938-0200 x355

Can a stored procedure return an updatable ResultSet?Location: http://www.jguru.com/faq/view.jsp?EID=114329 Created: Jul 30, 2000 Modified: 2000-07-30 04:12:26.303Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Matt Gaul (http://www.jguru.com/guru/viewbio.jsp?EID=29651

This depends on your driver. If it supports JDBC 2.0, then the answer is yes, although the functionality is in the driver. As you can see from Creating a CallableStatement Object, there is no difference in the stored procedure itself.

Where do I find information about operations on Excel, Word, text files and other non-DBMS products that can be accessed via the JDBC-ODBC Bridge?Location: http://www.jguru.com/faq/view.jsp?EID=114331 Created: Jul 30, 2000 Modified: 2000-07-30 04:13:20.692Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

The best source is, the source, that is, Microsoft. See: Microsoft ODBC Desktop Database Drivers, which includes considerations for non-DBMS operations.

You can also check The ODBC FAQ and here's a java example for Using MS-Excel and JDBC.

How do I connect to a database back-end using trusted applets?Location: http://www.jguru.com/faq/view.jsp?EID=114333 Created: Jul 30, 2000 Modified: 2000-09-14 08:38:57.264Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by gary besterwitch (http://www.jguru.com/guru/viewbio.jsp?EID=104419

The main thing that a trusted applet buys you, in this context, is the ability to connect to a machine other than the one from which the applet was served. Otherwise, connecting is the same as explained in How can I connect from an applet to a database on the server? Note that while the answer mentions using a local JDBC driver, there are some browser classpath issues that make this problematic for wisdespread use; a type 3 or 4 driver serves the purpose better for direct database connections.

Can I reuse a Statement or must I create a new one for each query? Location: http://www.jguru.com/faq/view.jsp?EID=115621 Created: Jul 31, 2000 Modified: 2000-07-31 19:52:35.821Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by timo guenzel (http://www.jguru.com/guru/viewbio.jsp?EID=115224

When using a JDBC compliant driver, you can use the same Statement for any number of queries. However, some older drivers did not always "respect the spec."

Page 86: Jdbc Faq From Jguru

Also note that a Statement SHOULD automatically close the current ResultSet before executing a new query, so be sure you are done with it before re-querying using the same Statement. For more information, see: Executing Statements Using Statement Objects.

Why does my "if(rs==null)" condition always evaluate to false after executing a query?Location: http://www.jguru.com/faq/view.jsp?EID=115622 Created: Jul 31, 2000 Modified: 2000-07-31 19:53:19.492Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Anoop Kumar A (http://www.jguru.com/guru/viewbio.jsp?EID=12385

The driver's executeXXX() methods will always return a ResultSet object unless there was some serious internal problem or error. Therefore the reference to the returned ResultSet is never normally null. The ResultSet can be empty, that is, nothing met the criteria, but the ResultSet object itself still is not null. Instead, the normal way of checking if data was returned is to use the next() method, as if( rs.next() ) or while( rs.next() ), which returns a boolean. For more information, see: ResultSet and the API documentation for java.sql.ResultSet.

Are there any good books that will help me learn JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=120201 Created: Aug 5, 2000 Modified: 2000-08-05 22:20:42.292Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

If you already know SQL, the JDBC API Tutorial and Reference, Second Edition : Universal Data Access for the Java 2 Platform book is probably the best of the bunch. It covers the original JDBC 1.x capabilities like statements and resultsets as well as the newer JDBC 2.0 capabilies like updatable cursors, BLOBS/CLOBS, as well as rowsets.

If you don't know SQL (Structured Query Language), I like the SQL Database Programming with Java book. While around 2 years old now, it will get you started with database development with Java.

Comments and alternative answers

JDBC Tutorial Author: Kevin 95112 (http://www.jguru.com/guru/viewbio.jsp?EID=847704), Apr 21, 2002JDBC 3 is a good book for both veteran or newcomer

What is a three-tier architecture? Location: http://www.jguru.com/faq/view.jsp?EID=125072 Created: Aug 11, 2000 Modified: 2000-08-11 14:55:10.431Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question originally posed by joy choudhury (http://www.jguru.com/guru/viewbio.jsp?EID=104345

A three-tier architecture is any system which enforces a general separation between the following three parts:

Page 87: Jdbc Faq From Jguru

1. Client Tier or user interface 2. Middle Tier or business logic 3. Data Storage Tier

Applied to web applications and distributed programming, the three logical tiers usually correspond to the physical separation between three types of devices or hosts:

1. Browser or GUI Application 2. Web Server or Application Server 3. Database Server (often an RDBMS or Relational Database)

However, inside of the application server, there is a further division of program code into three logical tiers. This is kind of fractal: the part (app server object design) resembles the whole (physical system architecture). In a classic JSP/Servlet system, these objects are usually implemented as:

1. JSPs or Servlets responsible for creating HTML or WML user interface pages

2. Servlets or JavaBeans responsible for business logic 3. Servlets, JavaBeans, or Java classes responsible for data access.

These objects usually use JDBC to query the database.

In an EJB system, the three logical tiers are usually implemented somewhat differently:

1. JSPs, Servlets, or Java client applications responsible for user interface

2. Session Beans or Entity Beans whose methods implement business logic and business rules

3. Entity Beans whose fields represent data; these fields are "persisted" (stored and retrieved) either by the EJB server (for container-managed persistence) or by the Entity Beans themselves (for bean-managed persistence)

As you can see, the precise definition of "tiers" can vary widely depending on the particular needs and choices of an application designer. However, they all maintain the general division of client-logic-storage.

If the architecture contains more than three logical tiers -- for instance, multiple data feeds, multiple transactional data sources, multiple client applications -- then it is typically called an "N-tier" or "Distributed" architecture.

See also:

What seperates one tier from another in the context of n- tiered architecture?

In distributed architecture (typical three tier consisting of thin client, middleware & database) which type of JDBC driver should be used and why?

What is meant by the term "business logic"? Are the following schemes 3 tiered architecture? What is the recommended, "best" architecture for JSP

applications?

Comments and alternative answers

Page 88: Jdbc Faq From Jguru

NEED SOME HELP WITH THE FOLLOWING QUESTIONS Author: hapz happy (http://www.jguru.com/guru/viewbio.jsp?EID=1239371), Apr 18, 2005hi, just need some answers to some questions about XML coz i dont hav a clue. 1) how to identify a website that is using XML? 2) in which way can you identify a website is using XML and not xhtml? 3) what is server-side XML, what is client-side XML? 4) how to identify a website that is using a Three-Tier Architecture

Re: NEED SOME HELP WITH THE FOLLOWING QUESTIONS Author: hapz happy (http://www.jguru.com/guru/viewbio.jsp?EID=1239371), Apr 18, 2005reply to [email protected] thanx

Re[2]: NEED SOME HELP WITH THE FOLLOWING QUESTIONS Author: Felix Zhu (http://www.jguru.com/guru/viewbio.jsp?EID=1241528), Apr 28, 2005You should think twice about your post on this website. There are many other methods of gaining knowledge. See me in class. I can help.

Re[2]: NEED SOME HELP WITH THE FOLLOWING QUESTIONS Author: Leonardo DaVinci (http://www.jguru.com/guru/viewbio.jsp?EID=1245556), May 24, 2005Meow :)

How can I use JDO with EJB? Location: http://www.jguru.com/faq/view.jsp?EID=125704 Created: Aug 13, 2000 Modified: 2000-08-13 15:51:33.693Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3) Question originally posed by Corneanu Dan (http://www.jguru.com/guru/viewbio.jsp?EID=41082

JDO and EJB are different and incompatible persistence models. While there may in the future be an EJB server that uses JDO, no such thing currently exists, and IMHO never should. Comments and alternative answers

Sun's site states that JDO could be used to implement... Author: John Francis (http://www.jguru.com/guru/viewbio.jsp?EID=296576), Jan 8, 2001Sun's site states that JDO could be used to implement persistence for a bean using bean managed persistence. JDO is an object to relational mapping layer, so can live inside the implementation of the bean.

ejb and jdo answer unsatisfactory Author: chris mountford (http://www.jguru.com/guru/viewbio.jsp?EID=528277), Mar 7, 2004I think EJB would better be described as a component model with CMP its stock

Page 89: Jdbc Faq From Jguru

persistence model. BMP is an alternate persistence model that delegates and this could easily delegate to JDO. Of course some people disprefer CMP. JDO is not a component model at all so I can't see the incompatibility you cite.

Is there a freely available Java tool for testing SQL?Location: http://www.jguru.com/faq/view.jsp?EID=128537 Created: Aug 16, 2000 Modified: 2000-08-18 22:40:51.724Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

The Java InstantDB relational database management system has a command line module called commsql for testing SQL, as well as a Swing based utility called SQLBuilder. The classes are oriented towards InstantDB, but the source is included to allow modification for accessing other databases.Comments and alternative answers

You can also use the Sun provided JDBC TestTool. Author: Fabrizio Audisio (http://www.jguru.com/guru/viewbio.jsp?EID=320408), Feb 4, 2001You can also use the Sun provided JDBC TestTool.

Re: Sun provided JDBC TestTool. Author: Jay Truesdale (http://www.jguru.com/guru/viewbio.jsp?EID=389617), Mar 28, 2001As of 03/28/2001, This tool supports the JDBC 1.2 API only

What separates one tier from another in the context of n-tiered architecture? Location: http://www.jguru.com/faq/view.jsp?EID=128826 Created: Aug 16, 2000 Modified: 2000-10-13 08:54:19.448Author: John Kroubalkian (http://www.jguru.com/guru/viewbio.jsp?EID=1461)

It depends on the application.

In a web application, for example, where tier 1 is a web-server, it may communicate with a tier 2 Application Server using RMI over IIOP, and subsequently tier 2 may communicate with tier 3 (data storage) using JDBC, etc.

Each of these tiers may be on separate physical machines or they may share the same box.

The important thing is the functionality at each tier.

Tier 1 - Presentation - should be concerned mainly with display of user interfaces and/or data to the client browser or client system.

Tier 2 - Application - should be concerned with business logic Tier 3+ - Storage/Enterprise Systems - should be focused on data

persistence and/or communication with other Enterprise Systems.

Comments and alternative answers

Page 90: Jdbc Faq From Jguru

See also http://www.jguru.com/jguru/faq/view.jsp?E... Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Oct 13, 2000See also http://www.jguru.com/jguru/faq/view.jsp?EID=125072

How do I map database specific ( non-standard ) types to JDBC types?Location: http://www.jguru.com/faq/view.jsp?EID=130563 Created: Aug 19, 2000 Modified: 2000-08-19 13:58:51.751Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

The first answer is to stick with SQL standard types whenever possible; otherwise you'll have costly migration headaches when moving to or working with other databases.

If that's not possible, then the SQL/JDBC manuals for the specific database SHOULD provide this information. See Where can I find online documentation for database xyz? for links.

The JDK documentation, particularly for 1.3, also has mapping information and a section on database specific type mapping. See: 8 Mapping SQL and Java Types , subsection 8.9.7 JDBC Types Mapped to Database-specific SQL Types.

What SQL learning and reference resources are available online?Location: http://www.jguru.com/faq/view.jsp?EID=130933 Created: Aug 20, 2000 Modified: 2000-12-09 12:29:18.984Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

SQL online resources are not nearly as plentiful as many other areas, but here is a good basic tutorial: Introduction to Structured Query Language The page additionally has a number of links to other resources.

Also, and I hope it is legal, Teach Yourself SQL in 21 Days, Second Edition is online. And, of course, vendor manuals provide reference materials and some examples. See Where can I find online documentation for database xyz?

Comments and alternative answers

Bad link on page Author: John Bundy (http://www.jguru.com/guru/viewbio.jsp?EID=1072741), Apr 3, 2003What SQL learning and reference resources are available online? The link given to an 'Introduction to Structured Query Language' is bad. I would like to see some online SQL tutorial.

Page 91: Jdbc Faq From Jguru

What areas should I focus on for the best performance in a JDBC application? Location: http://www.jguru.com/faq/view.jsp?EID=131579 Created: Aug 21, 2000 Modified: 2000-08-24 09:23:14.236Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306) Question originally posed by arun anand (http://www.jguru.com/guru/viewbio.jsp?EID=78217

These are few points to consider: Use a connection pool mechanism whenever possible. Use prepared statements. These can be beneficial, for example with

DB specific escaping, even when used only once. Use stored procedures when they can be created in a standard

manner. Do watch out for DB specific SP definitions that can cause migration headaches.

Even though the jdbc promotes portability, true portability comes from NOT depending on any database specific data types, functions and so on.

Select only required columns rather than using select * from Tablexyz. Always close Statement and ResultSet objects as soon as possible. Write modular classes to handle database interaction specifics. Work with DatabaseMetaData to get information about database

functionality. Softcode database specific parameters with, for example, properties

files. Always catch AND handle database warnings and exceptions. Be sure

to check for additional pending exceptions. Test your code with debug statements to determine the time it takes

to execute your query and so on to help in tuning your code. Also use query plan functionality if available.

Use proper ( and a single standard if possible ) formats, especially for dates.

Use proper data types for specific kind of data. For example, store birthdate as a date type rather than, say, varchar.

Rahul kumar Gupta adds:

Use scrollable ResultSet ( JDBC 2.0 ). Stay away from the JDBC-ODBC and other Type 1 drivers where

possible.

Peter Kua adds:

For more detailed information, take a look at JDBC Performance Tips. While these are aimed specifically at the AS/400, most of the tips are applicable to JDBC in general.

Joe Sam Shirah adds:

The DB reference manuals covering JDBC for your own and other databases can also provide valuable tips. See: Where can I find online documentation for database xyz?

How can I determine the value of a DBMS auto-generated key after record insertion? Location: http://www.jguru.com/faq/view.jsp?EID=131634

Page 92: Jdbc Faq From Jguru

Created: Aug 21, 2000 Modified: 2000-08-21 16:32:18.391Author: Hans Gerwitz (http://www.jguru.com/guru/viewbio.jsp?EID=100248) Question originally posed by Hans Gerwitz (http://www.jguru.com/guru/viewbio.jsp?EID=100248

I had to research this issue for both MySQL and MS SQL and was able to answer my own question.

With JDBC 2.0 or greater, this can be accomplished using scroll-sensitive ResultSets. See sections 5.8 and 5.9.

Unfortunately, I was limited to JDBC 1.2.

In the case of MySQL, the popular tjFM driver supports a getLastInsertID method on twz1.jdbc.mysql.jdbcMysqlBase.

In the case of MS SQL 7, no 1.2.2 or lesser JDBC driver appears to provide a similar method, but the magic variable @@IDENTITY can be used on the same connection, using a trick to execute both statements sequentially. A good example of this is documented in the FAQ for the i-net UNA driver.

How do I write a stored procedure in SQL that will return an Array as an OUT parameter? Location: http://www.jguru.com/faq/view.jsp?EID=132021 Created: Aug 22, 2000 Modified: 2000-09-04 13:17:19.871Author: Nicholas Whitehead (http://www.jguru.com/guru/viewbio.jsp?EID=1260) Question originally posed by Nitin Bahadur (http://www.jguru.com/guru/viewbio.jsp?EID=90254

This is dependent on the JDBC driver and the database interface implementation and is therefore vendor specific.

Joe Sam Shirah adds: In addition, not all databases support the SQL3 types, so you should ensure that your database has this capability as well. However, at that point, there should be little difference, keeping Nicholas' caveat in mind, between returning an Array and any other type. Oracle supports the Array type and you might want to look at their site for examples. See:

Where can I find online documentation for database xyz?

We are trying to access a large volume of data from a remote database, but the time it takes to get the data from the database is more than the maximum timeout for the web server, so the webpage is not getting displayed. How can we solve this problem?Location: http://www.jguru.com/faq/view.jsp?EID=132065 Created: Aug 22, 2000 Modified: 2000-08-25 20:14:51.715Author: Nicholas Whitehead (http://www.jguru.com/guru/viewbio.jsp?EID=1260) Question originally posed by Geetha Santhanam (http://www.jguru.com/guru/viewbio.jsp?EID=63150

JDBC is not usually the root cause of the delay, so I'll make the obvious suggestions first:

Extend the maximum timeout for the web page.

Page 93: Jdbc Faq From Jguru

Optimize the query to return the data faster. Reduce the amount of data you return. Increase the bandwidth to the database. Tune the transport protocol to carry more data per packet. Last and most importantly for remote access across a slow line:

denormalize the query. One query returning many rows will have a far faster throughput than many queries returning a small number of rows. Differently put, the submission and processing of a query itself can easily longer than the actual retrieval of the rows.

Joe Sam Shirah adds:

jGuru received several answers to this question on the JDBC side, most of which emphasized narrowing the query to take less time. This is excellent advice, but not always possible. Additionally, other tasks may bring up the same issues with servlets. During January, 2000, there was an exchange of messages on Sun's servlet mailing list which discussed the issue and provided a more general answer. Essentially, the advice is to start a new thread in the servlet to do the work and then, using refresh in the header, repeatedly send a status message until the long running task is done.

See the series Timing out of response data. Interestingly, probably the one that outlines the process best is http://archives.java.sun.com/cgi-bin/wa?A2=ind0001&L=servlet-interest&D=0&P=80267 by one Nicholas Whitehead.

Swarraj "sk or raj" Kulkarni and Kesav Kumar Kolla also contributed to this answer.

Comments and alternative answers

Preventing browser HTTP connection timeout Author: Abu Daniel (http://www.jguru.com/guru/viewbio.jsp?EID=50542), Mar 5, 2003You can send dummy tags to the browser, just to keep the connection alive. A patch-code which I wrote for my JSPs was: <%///// dummy tags to the browser so that connection is maintained ///////// final java.util.Vector vec = new java.util.Vector(); final java.io.PrintWriter writer = response.getWriter(); Runnable runnable = new Runnable() { public void run() { int count = 0; while(vec.size() == 0) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } try { writer.write("<keepAlive id=\"" + count++ + "\"/>\r\n"); writer.flush(); } catch (Exception e) { e.printStackTrace();

Page 94: Jdbc Faq From Jguru

} } } }; Thread transectionThread = new Thread(runnable); transectionThread.start();///////////// End New Code to send dummy tags to browser so connection is maintained /////////%>

After the last line of your bean call (or processing) write the following line: <%vec.addElement("test");%>

Where can I find the API documentation for Java Database Connectivity (JDBC)?Location: http://www.jguru.com/faq/view.jsp?EID=134142 Created: Aug 24, 2000 Modified: 2000-08-25 22:31:33.435Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

You can find the core JDBC API documentation from Sun's J2SE API documentation page. See the sections javax.sql, javax.transaction and javax.transaction.xa from Sun's J2EE API documentation page for the JDBC extension API documentation.

Joe Sam Shirah adds:

If you're wondering what happened to the JDBC(tm) Technology Guide: Getting Started when you download the 1.3 JDK documentation, it's still there, just a bad hyperlink. On the JDBC(tm) API Documentation page, which is under your docs directory at docs/guide/jdbc/index.html, change the relative link from this: /products/jdk/1.3/docs/guide/jdbc/getstart/GettingStartedTOC.fm.html to this: getstart/GettingStartedTOC.fm.html.

Does Oracle maintain a FAQ for Oracle specific JDBC issues?Location: http://www.jguru.com/faq/view.jsp?EID=204855 Created: Sep 13, 2000 Modified: 2000-09-13 19:49:04.986Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Member's of Oracle's Technet can access their JDBC FAQ at http://technet.oracle.com/tech/java/sqlj_jdbc/htdocs/jdbc_faq.htm.

Membership is free.

I am using ResultSetMetaData.getColumnLabel() to create headers for a table. I have specified column labels on the table ( DB2 on an AS/400, ) which show up when I run an SQL statement directly over the table, but the method returns the same data as getColumnName(). Any ideas, help or explanation?Location: http://www.jguru.com/faq/view.jsp?EID=210959 Created: Sep 20, 2000 Modified: 2000-09-28 02:59:44.977Author: Sreeram Mohan (http://www.jguru.com/guru/viewbio.jsp?EID=51029)

Page 95: Jdbc Faq From Jguru

Question originally posed by Brenda Groenwald (http://www.jguru.com/guru/viewbio.jsp?EID=66017

Many drivers implement this method identically to getColumnName(), apparently because it is a "suggested" title, but always be sure you have the latest versions. For the AS/400 drivers in particular, which have gone open source, you can check at the JTOpen site for the to do list or suggest/implement something yourself.

Where can I find code examples specific to the JDBC-ODBC bridge and Access?Location: http://www.jguru.com/faq/view.jsp?EID=217794 Created: Sep 28, 2000 Modified: 2000-09-28 08:02:53.807Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

Starting with what should be the source: JDBC Data Source Applet.

Then from the Java Developer Connection:

Duke's Bakery - A JDBC(tm) Order Entry Prototype - Part I

and

JDBC(tm) Short Course.

Why do I get "Driver Not Capable" errors and what does it mean?Location: http://www.jguru.com/faq/view.jsp?EID=217917 Created: Sep 28, 2000 Modified: 2000-09-29 22:35:01.397Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

This error indicates that: the operation is valid but not supported by either the driver or the data source.

For example, if the user is trying to use the callable statement to call a stored procedure but the database does not support stored procedures, then the operation will fail and give this error.

To provide robust code, you should always work with the DatabaseMetaData to find out whether the operation you are trying to perform with your database specific classes is supported by the underlying database and have alternative mechanisms in place to carry out the desired operation.

If you know that the database supports the operation and you get this error, then change to a more robust JDBC driver.

Where do I get JDBC drivers for the AS/400's database?Location: http://www.jguru.com/faq/view.jsp?EID=219413 Created: Sep 30, 2000 Modified: 2000-09-30 00:29:12.17Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Page 96: Jdbc Faq From Jguru

The native driver and a version of the Toolbox for Java, which includes the type 4 driver, comes with OS/400. One can also purchase or get an evaluation copy of the latest "official" version of the Toolbox. However, the open source version, JTOpen, is generally more up to date and is free.

You can find both versions from the Java Home Page. For third party drivers, check Where can I find a comprehensive list of JDBC drivers, including the databases they support?

Why do I get "Invalid Cursor State" errors when I insert/update/delete data with executeQuery()?Location: http://www.jguru.com/faq/view.jsp?EID=219416 Created: Sep 30, 2000 Modified: 2000-09-30 00:31:14.637Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The base answer is that you should be using executeUpdate() for these operations. The JDBC spec specifically "allows any query string to be passed through to an underlying DBMS driver" and this is probably why a number of databases will actually perform the requested operation. However, no ResultSet is returned. executeQuery() expects a ResultSet, and so reports the error when none is returned.Comments and alternative answers

Not true Author: sri karthi (http://www.jguru.com/guru/viewbio.jsp?EID=948693), Jul 14, 2002I am facing the same issue. I am getting the Invalid Cursor State even with a select comment... My processing involves a query with 2 subqueries... I guess jdbc:odbc connection cannot handle complex queries... or some other setup is required in SQL server to handle queries...

Invalid cursor state Author: Mlu Sincuba (http://www.jguru.com/guru/viewbio.jsp?EID=1210853), Nov 12, 2004query = "SELECT * FROM Customer WHERE meterNum = " + "'"+ meterNumber + "'"; try { db.statement = db.connect.createStatement(); db.results = db.statement.executeQuery(query); postBalance = Integer.parseInt(db.results.getString("balance")); newBalance = postBalance + amount; if ( db.results.next() ) { query = "INSERT INTO Transaction (transDateTime, amount, postBalance, newBalance, meterNumber)"+ " VALUES('" + date + "','" + amount + "','"+ postBalance + "','" + newBalance + "','" + meterNumber + "')"; db.result = db.statement.executeUpdate(query); if (db.result==0){ out.println("Not saved"); db.connect.rollback(); } else out.println("Saved"); out.println("your post balance is: "+postBalance); out.println("</body></html>"); out.close(); } else{ out.println("Customer not found!"); out.println("</body></html>"); out.close(); } }

Keeping query result sets in server memory can provide a significant performance enhancement for supporting a high volume of repetitive data access, but how can this functionality be implemented?

Page 97: Jdbc Faq From Jguru

Location: http://www.jguru.com/faq/view.jsp?EID=219669 Created: Sep 30, 2000 Modified: 2000-09-30 19:21:55.207Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Vinod Tadepalli (http://www.jguru.com/guru/viewbio.jsp?EID=19366

Some initial considerations are sufficient memory to hold the data and possible periodic refreshes. For the actual implementation you can use arrays, vectors or a Collection, but the most blessed way at the moment is to implement or use a third party implementation of Rowset. Javasoft has an Early Access JDBC(tm) Rowset implementation at the Java Developer Connection. Note that you must be a member to download the classes.

How can I convert a java array to a java.sql.Array? Location: http://www.jguru.com/faq/view.jsp?EID=219786 Created: Sep 30, 2000 Modified: 2000-12-27 11:06:54.106Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Marc Breslow (http://www.jguru.com/guru/viewbio.jsp?EID=121408

You may want to first review JDBC(tm) Technology Guide: Getting Started, Section 8: Mapping SQL and Java Types. You'll see that the JDBC ( java.sql ) Array is consistently mapped to an array. Unfortunately, capitalization not particularly enforced there.

However, in some sense, one never converts from an array to a java.sql.Array, which is an interface for retrieving and materializing an SQL3 ARRAY data type. A Java array is a first class object and all of the references basically use PreparedStatement.setObject() or ResultSet.updateObject() methods for putting the array to an ARRAY in the database. Here's a basic example:

String[] as = { "One", "Two", "Three" };...PreparedStatement ps = con.prepareStatement( "UPDATE MYTABLE SET ArrayNums = ? WHERE MyKey = ?" );...

ps.setObject( 1, as );

For more information see: Array and Using SQL3 Datatypes.

When I use the AS400JDBCDatabaseMetadata.getColumns(), the columns arrive in alphabetical order not in physical order. Is there a way other than SELECT * FROM... to get the physical order ? Location: http://www.jguru.com/faq/view.jsp?EID=219792 Created: Sep 30, 2000 Modified: 2000-09-30 19:34:29.132Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by isreal vinner (http://www.jguru.com/guru/viewbio.jsp?EID=208799

Page 98: Jdbc Faq From Jguru

Unfortunately, if you look at the Toolbox documentation for AS400JDBCDatabaseMetaData.getColumns(), you'll see this statement:

"The following column in the description is not currently supported:

ORDINAL_POSITION"

I'm not aware of an alternative at this time. Obviously it is critical to read the driver documentation for (un)supported features.

How can I insert multiple rows into a database in a single transaction? Location: http://www.jguru.com/faq/view.jsp?EID=226749 Created: Oct 11, 2000 Modified: 2000-10-15 08:32:49.388Author: Anil Datt (http://www.jguru.com/guru/viewbio.jsp?EID=20887) Question originally posed by Ravi Shankar (http://www.jguru.com/guru/viewbio.jsp?EID=223578

//turn off the implicit commit

Connection.setAutoCommit(false);

//..your insert/update/delete goes here

Connection.Commit();

a new transaction is implicitly started.

Joe Sam Shirah comments: This question could be taken a couple of ways, so we included this answer as well:

Ryan Breidenbach adds:

JDBC 2.0 provides a set of methods for executing a batch of database commands. Specifically, the java.sql.Statement interface provides three methods: addBatch(), clearBatch() and executeBatch(). Their documentation is pretty straight forward.

The implementation of these methods is optional, so be sure that your driver supports these.

I've heard that the Sun JDBC-ODBC bridge driver is buggy. Are there any commercial alternatives?Location: http://www.jguru.com/faq/view.jsp?EID=229690 Created: Oct 16, 2000 Modified: 2000-10-17 09:22:02.726Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

Yes, it is buggy, specifically in support for multithreaded access.

Sun keeps a list of commercial JDBC drivers. Go to http://industry.java.sun.com/products/jdbc/drivers, select "ODBC" from the "Supported DBMS" list, and click "Search".

Comments and alternative answers

Page 99: Jdbc Faq From Jguru

I am using the driver that comes with IDSSERVER from... Author: Mahendra Babu (http://www.jguru.com/guru/viewbio.jsp?EID=231681), Oct 31, 2000I am using the driver that comes with IDSSERVER from IDS Software. I find it quite good, user friendly and useful.

I've heard that the Sun JDBC-ODBC bridge driver is buggy. Are there any commercial alternatives? Author: John Peters (http://www.jguru.com/guru/viewbio.jsp?EID=535674), Nov 1, 2001We use the Easysoft JDBC-ODBC Bridge. Works fine.

www.easysoft.com

How can I obtain a vendor specific error code?Location: http://www.jguru.com/faq/view.jsp?EID=234532 Created: Oct 23, 2000 Modified: 2000-10-24 09:57:59.316Author: Yongfeng Xiao (http://www.jguru.com/guru/viewbio.jsp?EID=216776) Question originally posed by klaus peter (http://www.jguru.com/guru/viewbio.jsp?EID=230333

Use the SQLException method getErrorCode:

public int getErrorCode()Retrieves the vendor-specific exception code for this SQLException object.Returns:the vendor's error code

How do I get a scrollable ResultSet?Location: http://www.jguru.com/faq/view.jsp?EID=243611 Created: Nov 2, 2000 Modified: 2000-11-03 06:05:02.116Author: swarraj kulkarni (http://www.jguru.com/guru/viewbio.jsp?EID=121306) Question originally posed by sundarv varadarajan (http://www.jguru.com/guru/viewbio.jsp?EID=29816

You can get scrollable ResultSets by using the JDBC 2.0 API. You must have a driver that supports JDBC 2.0. The following code will give a Statement the capability to create scrollable ResultSets:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

Now use the Statement object to execute the query: For example:-

ResultSet srs = stmt.executeQuery("SELECT FIRST_NAME, AGE FROM STUDENTS_TABLE");

For more information refer to: Java - JDBC2.0 Information.

Page 100: Jdbc Faq From Jguru

Can ResultSets be passed between methods of a class? Are there any special usage considerations?Location: http://www.jguru.com/faq/view.jsp?EID=245663 Created: Nov 5, 2000 Modified: 2000-11-20 21:48:12.454Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212) Question originally posed by Daniel Yawitz (http://www.jguru.com/guru/viewbio.jsp?EID=241695

Yes. There is no reason that a ResultSet can't be used as a method parameter just like any other object reference. You must ensure that access to the ResultSet is synchronized. This should not be a problem is the ResultSet is a method variable passed as a method parameter - the ResultSet will have method scope and multi-thread access would not be an issue.

Aa an example, say you have several methods that obtain a ResultSet from the same table(s) and same columns, but use different queries. If you want these ResultSets to be processed the same way, you would have another method for that. This could look something like:

public List getStudentsByLastName(String lastName) { ResultSet rs = ... (JDBC code to retrieve students by last name); return processResultSet(rs);}

public List getStudentsByFirstName(String firstName) { ResultSet rs = ... (JDBC code to retrieve students by first name); return processResultSet(rs);}

private List processResultSet(ResultSet rs) { List l = ... (code that iterates through ResultSet to build a List of Student objects); return l;}

Since the ResultSet always has method scope - sychronization is never an issue.

Joe Sam Shirah comments: Ryan's answer is exactly correct in the given context. However, there are other possible areas and concerns as seen by these addtional responses.

swarraj kulkarni notes that: ResultSet does not implement the Serializable interface , so it can not be transferred across the network (for example in RMI calls.)

Brian O'Byrne adds:

1. There is only one ResultSet. Dont assume that the ResultSet is at the start (or in any good state...) just because you received it as a parameter. Previous operations involving the ResultSet will have had the side-effect of changing its state.

2. You will need to be careful about the order in which you close the ResultSet and CallableStatement/PreparedStatement/etc.

Page 101: Jdbc Faq From Jguru

From my own experience using the Oracle JDBC drivers and CallableStatements the following statements are true:

If you close the CallableStatement the ResultSet retrieved from that CallableStatement immediately goes out-of-scope.

If you close the ResultSet without reading it fully, you must close the CallableStatement or risk leaking a cursor on the database server.

If you close the CallableStatement without reading it's associated ResultSet fully, you risk leaking a cursor on the database server.

No doubt, these observations are valid only for Oracle drivers. Perhaps only for some versions of Oracle drivers.

The recommended sequence seems to be:

Open the statement Retrieve the ResultSet from the statement Read what you need from the ResultSet Close the ResultSet Close the Statement

Dieter Wimberger points out an important consideration:"...a ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results."[java.sql.ResultSet API Specification]

John Zukowski adds: You have to be sure not to close the connection the result set was acquired from or else the result set will become invalid. You should probably use a CachedRowSet if the connection can/should close.

When will JDBC 3.0 be available?Location: http://www.jguru.com/faq/view.jsp?EID=263119 Created: Nov 27, 2000 Modified: 2000-11-28 07:17:16.111Author: Mahendra Babu (http://www.jguru.com/guru/viewbio.jsp?EID=231681) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

The JDBC 3.0 API is scheduled to be available with the JDK 1.4 release.

How do I convert a java.sql.Timestamp to a java.util.Date?Location: http://www.jguru.com/faq/view.jsp?EID=270884 Created: Dec 6, 2000 Modified: 2001-01-23 14:38:20.401Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

While Timesteamp extends Date, it stores the fractional part of the time within itself instead of within the Date superclass. If you need the partial seconds, you have to add them back in.

Date date = new Date(ts.getTime() + (ts.getNanos() / 1000000 ));

Does anyone maintain a FAQ for Java Blend?Location: http://www.jguru.com/faq/view.jsp?EID=270913

Page 102: Jdbc Faq From Jguru

Created: Dec 6, 2000 Modified: 2000-12-06 18:19:29.595Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Sun maintains the official FAQ for Java Blend.

What does SQL stand for?Location: http://www.jguru.com/faq/view.jsp?EID=270925 Created: Dec 6, 2000 Modified: 2000-12-06 16:02:33.747Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

SQL stands for Structured Query Language.

What is SQL?Location: http://www.jguru.com/faq/view.jsp?EID=270926 Created: Dec 6, 2000 Modified: 2000-12-09 12:35:49.556Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

SQL is a standardized language used to create, manipulate, examine, and manage relational databases. See What SQL learning and reference resources are available online? for tutorials and further information.

How do I pronounce SQL?Location: http://www.jguru.com/faq/view.jsp?EID=270930 Created: Dec 6, 2000 Modified: 2000-12-06 18:36:57.436Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You can either spell it out S-Q-L or pronouce it like See - QueL (equal, but beginning with an S).

Joe Sam Shirah adds:

IBM was the pioneer in this area and their first go was called Structured English Query Language and pronounced "Sequel". The later version, which led to today's SQL standard, was trimmed to Structured Query Language and technically pronounced Ess-Que- Ell; that is, pronounce the letters individually.

In primarily the PC world, it became the vogue to pronounce it "sequel" and those in the know often received snickers for saying Ess-Que-Ell. In today's world, either pronounciation should be correctly understood as a "you say tom-A-to and I say tom-AH-toe" thing. For some products, when in Rome..., so MS' and Sybase's SQL Server products are always pronounced "sequel server".

Comments and alternative answers

Would not recomment unless you want strange looks but Author: Robert H (http://www.jguru.com/guru/viewbio.jsp?EID=457281), Jul 18, 2001WE often use the pharse SQUIRREL

How can I connect to an Oracle database not on the web server from an untrusted applet?

Page 103: Jdbc Faq From Jguru

Location: http://www.jguru.com/faq/view.jsp?EID=271882 Created: Dec 7, 2000 Modified: 2000-12-09 09:48:12.064Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You can use the thin ORACLE JDBC driver in an applet (with some extra parameters on the JDBC URL). Then, if you have NET8, you can use the connection manager of NET8 on the web server to proxy the connection request to the database server.

What method do I use to specify that a CallableStatement's parameter is a SQL CHAR type as opposed to a SQL VARCHAR? I cannot find a corresponding setChar method.Location: http://www.jguru.com/faq/view.jsp?EID=274481 Created: Dec 10, 2000 Modified: 2000-12-10 15:54:46.041Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by david smith (http://www.jguru.com/guru/viewbio.jsp?EID=138335

Actually, you don't have to specify CHAR, VARCHAR or LONGVARCHAR. Use setString(), inherited from PreparedStatement, and the driver/DBMS will handle the proper type for you. Although the setString() javadoc only references VARCHAR and LONGVARCHAR, in Getting Started with the JDBC API the topic CHAR, VARCHAR, and LONGVARCHAR says this:

"Java programmers do not need to distinguish among the three types of JDBC strings, CHAR, VARCHAR, and LONGVARCHAR. Each can be expressed as a Java String, and it is possible to read and write an SQL statement correctly without knowing the exact data type that was expected."

The same is true for getString().

If you, for some reason, feel better directly specifying the type, you should be able to use this method, submitted by Gabriel Artaud:

Use setObject(int parameterIndex, Object x, int targetSqlType) with targetSqlType set to Types.CHAR.

Comments and alternative answers

INOUT parameter from CallableStatement has unnecessary padded spaces Author: varma mudunuru (http://www.jguru.com/guru/viewbio.jsp?EID=923617), Jun 22, 2002Hi, I'm using JDBC Oracle thin driver to connect to Oracle 8i. I'm calling a stored procedure for which I use a CallableStatement. I have an INOUT parameter of datatype CHAR(1) in the procedure, which I set using the setString() and do the registerOutParameter(3, Types.CHAR). When I excute the CallableStatement(), the INOUT parameter is appended with unnecessary spaces by the JDBC driver. In the procedure when I print the length of the parameter received, it shows 32512. This causes the procedure to throw a SQLException. How can we avoid these blank spaces? You might suggest that I put RTRIM() in the procedure as a simple solution, but that is not possible. I have observed the same thing in the OUT

Page 104: Jdbc Faq From Jguru

parameter. When the procedure returns a 1 char value, Java shows a 32512 length value (padded with unnecessary spaces). How can we tell the driver not to do such mischief. Please help. Thanks Varma [email protected]

I want to insert a blob retrieved from a form field (with type='file') into a database. How can I convert the data returned by request.getParameter() to a BLOB type? Location: http://www.jguru.com/faq/view.jsp?EID=275076 Created: Dec 11, 2000 Modified: 2000-12-24 21:47:29.092Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Jewel Chen (http://www.jguru.com/guru/viewbio.jsp?EID=265610

Given a set of bytes, see How do I upload SQL3 BLOB & CLOB data to a database? for how to insert it into a database that supports BLOBs.

Joe Sam Shirah adds:

To upload file data from a browser to a servlet, see: How do I upload a file to my servlet?.

Jorge Jordão, Eduardo Estefano, and Trapix Smith also contributed to this answer.

Comments and alternative answers

Some code that may help you. Author: Paul Hunnisett (http://www.jguru.com/guru/viewbio.jsp?EID=504117), Sep 27, 2001The following code will do what you want once you have got hold of your file as a file.

conn.setAutoCommit(false);String prepare = "insert into news_xml values(" + id + ", empty_blob())";String cmd = "SELECT * FROM news_xml where id=" + id + " for update";Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);stmt.executeUpdate(prepare);ResultSet rset = stmt.executeQuery(cmd);rset.next();BLOB blob = (BLOB)((OracleResultSet)rset).getBlob(2);FileInputStream instream = new FileInputStream(f);OutputStream outstream = blob.getBinaryOutputStream();int size = blob.getBufferSize();byte[] buffer = new byte[size];int length = -1;while ((length = instream.read(buffer)) != -1) outstream.write(buffer, 0, length);instream.close();

Page 105: Jdbc Faq From Jguru

outstream.close();conn.commit();

How do I send e-mail through Oracle triggers?Location: http://www.jguru.com/faq/view.jsp?EID=276261 Created: Dec 12, 2000 Modified: 2000-12-13 00:32:53.091Author: Mark Bradley (http://www.jguru.com/guru/viewbio.jsp?EID=276260) Question originally posed by Rajagopalan Varadarajan (http://www.jguru.com/guru/viewbio.jsp?EID=273011

A good set of responses I've seen is from the Oracle Magazine. From there select the "Ask Tom" column. You can search his articles for "JavaMail" or just "mail". It has responses for Oracle 8i and previous releases. Versions prior to 8.1.5 rely on Oracle packages instead of Java.

The questions and answers on that page are, naturally, heavily Oracle-specific!

It describes a way to load the activation.jar and mail.jar files (which cannot be compressed) into the database using the "loadjava" program.

There is Java and PL/SQL sample code which supports attachments using BLOBs. It has the repackaged JAR files.

You will need to modify the code to handle your specific needs. Load this code, then just call the PL/SQL function from the trigger.

Is Class.forName(Drivername) the only way to load a driver? Can I instantiate the Driver and use the object of the driver?Location: http://www.jguru.com/faq/view.jsp?EID=284881 Created: Dec 22, 2000 Modified: 2000-12-23 05:11:15.673Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by nadella srikanth (http://www.jguru.com/guru/viewbio.jsp?EID=72838

Yes, you can use the driver directly. Create an instance of the driver and use the connect method from the Driver interface. Note that there may actually be two instances created, due to the expected standard behavior of drivers when the class is loaded.

How can I retrieve string data from a database in Unicode format?Location: http://www.jguru.com/faq/view.jsp?EID=285758 Created: Dec 26, 2000 Modified: 2000-12-26 02:14:24.367Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Jan Borchers (http://www.jguru.com/guru/viewbio.jsp?EID=48743

The data is already in Unicode when it arrives in your program. Conversion from and to the encoding/charset/CCSID in the database from/to Unicode in the program is part of the JDBC driver's job.

Page 106: Jdbc Faq From Jguru

If, for some reason, you want to see the data in '\uHHHH' format ( where 'H' is the hex value ), the following code, while not very efficient, should give you some ideas:

public class UniFormat{

public static void main( String[] args ) { char[] ac = args[0].toCharArray(); int iValue; String s = null; StringBuffer sb = new StringBuffer();

for( int ndx = 0; ndx < ac.length; ndx++ ) { iValue = ac[ndx];

if( iValue < 0x10 ) { s = "\\u000"; } else if( iValue < 0x100 ) { s = "\\u00"; } else if( iValue < 0x1000 ) { s = "\\u0"; }

sb.append( s + Integer.toHexString( iValue ) ); } // end for

System.out.println("The Unicode format of " + args[0] + " is " + sb );

} // end main

} // end class UniFormat

Are there any JDBC drivers available that support using SSL to communicate between the Java program and the database server?Location: http://www.jguru.com/faq/view.jsp?EID=289193 Created: Dec 29, 2000 Modified: 2000-12-29 20:14:34.385Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question

Page 107: Jdbc Faq From Jguru

originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

For Oracle, the JDBC-OCI driver can use SSL with native threads, but not with green threads. The JDBC-Thin driver cannot use SSL, but can use ANO encryption instead.

JDataConnect provides a whole FAQ for their SSL support.

The IDS JDBC Driver supports SSL also.

The the Novell JDBC Driver for NDS driver uses SSL by default, and must be disabled to not use.

WebLogic / Tengah supports SSL when your protocol begins with t3s (jdbc:weblogic:t3s I guess, or just create the T3Client with a t3s URL).

Cloudscape supports SSL through a special extended URL with the RmiJdbc driver. (jdbc:cloudscape:weblogic-ssl:)

The HiT driver supports SSL communications with JDBC and DB2.

This list is not meant to be exhaustive. Feel free to add feedback if you know of any others.

Joe Sam Shirah adds:

The AS/400 Toolbox for Java will also support SSL Connections, although there must be a specific match between Toolbox and OS/400 versions. In addition, the Connection must be made in a way specific to the Toolbox driver.

Comments and alternative answers

how can i use ssl in my app Author: anil dash (http://www.jguru.com/guru/viewbio.jsp?EID=874769), May 11, 2002how can i use ssl in my app can u send me a sample code for that anil

StarSQL for Java JDBC driver supports SSL Author: David Brown (http://www.jguru.com/guru/viewbio.jsp?EID=1232510), Mar 14, 2005StarSQL for Java (a type 4 driver for accessing DB2, including AS/400, via DRDA) supports SSL.

see http://www.starquest.com

On the client side, SSL is set up by using the appropriate port (default 448 rather than 446) and including an extra .jar file in the Classpath.

Page 108: Jdbc Faq From Jguru

The Users Guide contains info on setting up the AS/400 for SSL :

StarSQL for Java User's Guide 79

Configuring Support for the SSL Protocol

To configure an iSeries host system to use the Secure Sockets Layer (SSL) protocol you must have the following components:

OS/400 v5r1 or later 5722-SS1 option 34 Digital Certificate Manager 5722-TC1 TCP/IP Connectivity Utilities 5722-DG1 IBM HTTP Server Either 5722-AC2 (56-bit) or 5722-AC3 (128-bit) Cryptographic Access Provider

Preparing Hosts for StarSQL Access

Following are general procedures for configuring SSL on the iSeries host. Refer to your IBM documentation for details, especially the AS/400 documentation and the IBM iSeries Wired Network Security OS/400 V5R1 DCM and Cryptography Enhancements Redbook.

1. Start the Admin HTTP instance and use a browser to configure the Digital Certificate Manager.a. Create a local Certificate Authority or obtain a certificate from a public Internet Certificate Authority.b. Create a *SYSTEM certificate store.c. Use Manage Applications to assign a server certificate to the OS/400 DDM/DRDA server.d. After you assign the certificate, restart the DDM/DRDA server:ENDTCPSVR *DDMSTRTCPSVR *DDM

2. If necessary, set the port on which the DDM/DRDA server listens for SSL conversations. The default port for SSL is 448.

How do I display and parse a date?Location: http://www.jguru.com/faq/view.jsp?EID=290174 Created: Dec 31, 2000 Modified: 2001-01-23 14:37:34.041Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The Java I18N way is to use a DateFormat. While SimpleDateFormat, which is generally returned, creates a large number of objects, it is locale aware and will handle most of your needs. The following sample code initially creates a java.sql.Date object and formats it for the default locale. An initial actionPerformed call additionally formats/displays it for a German locale and also displays the resulting java.sql.Date in

Page 109: Jdbc Faq From Jguru

standard escape format. Other dates can be entered and parsed after the initial display.

// JDFDP.java - Display and Parse java.sql.Date

import java.sql.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.text.*;import java.util.*;

public class JDFDP extends JFrame implements ActionListener, WindowListener{ // create a java.sql.Date java.sql.Date jsqlDate = new java.sql.Date( System.currentTimeMillis() );

DateFormat dfLocal = DateFormat.getDateInstance( DateFormat.SHORT ); DateFormat dfGermany = DateFormat.getDateInstance( DateFormat.SHORT, Locale.GERMANY );

JButton jb = new JButton( "Go" ); JLabel jlI = new JLabel("Input a Date:"), jlD = new JLabel("Display German:"), jlP = new JLabel("Parsed:");

JPanel jp = new JPanel();

JTextField jtI = new JTextField( 10 ), jtD = new JTextField( 10 ), jtP = new JTextField( 10 );

public JDFDP() { super( "JDFDP" ); addWindowListener( this );

jb.addActionListener( this );

jp.add(jlI); jp.add(jtI); jp.add(jb);

Page 110: Jdbc Faq From Jguru

jp.add(jlD); jp.add(jtD); jp.add(jlP); jp.add(jtP);

getContentPane().add( jp, BorderLayout.CENTER ); pack();

// set text by sending dummy event jtI.setText( dfLocal.format( jsqlDate ) ); actionPerformed( new ActionEvent( this, 12, "12" ) );

show();

} // end constructor

// ActionListener Implementation public void actionPerformed(ActionEvent e) { jtD.setText( "" ); jtP.setText( "" ); try { java.util.Date d = dfLocal.parse( jtI.getText() ); jtI.setText( dfLocal.format( d ) ); jtD.setText( dfGermany.format( d ) ); d = dfGermany.parse( jtD.getText() ); // get new java.sql.Date jsqlDate = new java.sql.Date( d.getTime() ); jtP.setText( jsqlDate.toString() ); } catch( ParseException pe ) { jtI.setText( "" ); }

} // End actionPerformed

// Window Listener Implementation public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { dispose(); System.exit(0); }

Page 111: Jdbc Faq From Jguru

public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {}// End Window Listener Implementation

public static void main(String[] args) { new JDFDP(); }

} // end class JDFDP

I am interested in developing a Type 4 JDBC Driver for MS-SQL Server. Where can I get further information regarding the TDS protocol in order to write the code?Location: http://www.jguru.com/faq/view.jsp?EID=292012 Created: Jan 3, 2001 Modified: 2001-01-03 05:53:12.168Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Ravi Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=286580

A search for "TDS" AND "JDBC" at altavista brought up a number of sites dealing with the Tabular DataStream protocol. Probably most other search engines would do the same. Obviously the Microsoft/Sybase sites make sense and you would probably be interested in the FreeTDS site.

Why do my transactions fail when I invoke executeUpdate()? I've set autocommit to false, but I get the SQLException: "The file is not valid for the operation" and getTransactionIsolation() returns TRANSACTION_UNCOMMITED.Location: http://www.jguru.com/faq/view.jsp?EID=313818 Created: Jan 27, 2001 Modified: 2002-03-23 23:05:30.986Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Maribel Marco (http://www.jguru.com/guru/viewbio.jsp?EID=281878

Transactions require underlying support. In general, there must be

1) A database table.

2) The database must support transactions.

3) Any setup required by the specific database to allow transactions must be performed.

For example, the AS/400 supports transactions via a process called journaling. Journals must be specifically created and operational or SQL Collections, rather than standard libraries, must be created for automatic journals.

Page 112: Jdbc Faq From Jguru

To check whether transactions are valid, use DatabaseMetaData.supportsTransactions().

Comments and alternative answers

autocommit Author: Charles Xavier (http://www.jguru.com/guru/viewbio.jsp?EID=384410), Mar 28, 2001If the autocommit status has been set to false, then shouldn't there be an explicit call to commit the transaction using the commit method of the Connection object ?

Re: autocommit Author: N Jain (http://www.jguru.com/guru/viewbio.jsp?EID=795169), Mar 13, 2002See if there is a journal on the file that you are trying to update.

Re: autocommit Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Mar 23, 2002Of course, but the focus of the question was transactional support. If that is not there, commit won't work.

What is Java Blend and how does it relate to JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=315088 Created: Jan 29, 2001 Modified: 2001-01-29 11:00:04.238Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

JDBC is a relatively low level means of accessing tabular data. This was actually one of the goals of the specification and there was an explicit expectation that alternate tools could and would be built on top of the API. Java Blend is Sun's commercial offering in this area. It claims to achieve transparent persistence across multiple databases, to provide object-relational mapping that overcomes the "impedance mismatch", and to eliminate the need for SQL and even JDBC programming, among other things.

Please note that jGuru makes no judgements or recommendations about this or any other product. For more information, see the Java Blend Overview and the Java Blend Homepage.

How can I generate a java.sql.Timestamp from text fields formatted as MM/DD/YYYY and/or HH:MM:SS ( Month/Day/Year - Hours/Minutes/Seconds )?Location: http://www.jguru.com/faq/view.jsp?EID=315648 Created: Jan 29, 2001 Modified: 2001-01-29 20:29:52.677Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by shoma bowmick (http://www.jguru.com/guru/viewbio.jsp?EID=290151

Page 113: Jdbc Faq From Jguru

Let's assume that the data has been parsed ( probably with StringTokenizer ) validated and converted ( probably with Integer.parseInt() ) to the ints MM, DD, YYYY and HH, MM, SS. Since the Timestamp constructor that takes these values has been deprecated, the blessed way is:

GregorianCalendar cal = new GregorianCalendar( YYYY, MM - 1, DD, HH, MM, SS );

OR

Calendar cal = Calendar.getInstance();cal.set( CALENDAR.YEAR, YYYY );cal.set( CALENDAR.MONTH, MM - 1 );...cal.set( CALENDAR.SECOND, SS );

Then, for either,

cal.set( CALENDAR.MILLISECOND, 0 ); // or other value

Timestamp ts = new Timestamp( cal.getTime().getTime() );

ts.setNanos( 0 ); // or other valueAnd you're done. Simple, right? The getTime().getTime() is particularly annoying, but that's the way it is. Comments and alternative answers

It's also possible to create a Timestamp object in... Author: Cristian Pelin (http://www.jguru.com/guru/viewbio.jsp?EID=230179), Jan 30, 2001It's also possible to create a Timestamp object in this way:

Timestamp ts = Timestamp.valueOf(<your formatted string>);

where <your formatted string> may be: "2001-01-30 09:45:46.0"

Note that valueOf() is a static method and that nanoseconds should still be set separately.

A simpler approach Author: Peter Heinrich (http://www.jguru.com/guru/viewbio.jsp?EID=389575), May 11, 2001DateFormat df = new SimpleDateFormat( "MM/dd/yyyy" );Timestamp ts = new Timestamp( df.parse( text ).getTime() );

Of course, you can change the format string used to initialize df as appropriate...

Page 114: Jdbc Faq From Jguru

peter

How can I get the same effect as an Order By query on an existing CachedRowSet?Location: http://www.jguru.com/faq/view.jsp?EID=316941 Created: Jan 31, 2001 Modified: 2001-01-31 00:43:27.042Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Venugopal Bonugu (http://www.jguru.com/guru/viewbio.jsp?EID=235758

Remember that RowSets are extensions of ResultSets and were not designed as mini-databases. Probably the easiest way to handle new orders is to use the toCollection method, create an ordered Collection and work off the data from there.

The other way would be to read the data ( possibly again into a Collection ) sort it and then create a new RowSet using the insertRow method or with your own Reader.

Comments and alternative answers

CachedRowSet usability and accessibility from you Client and server Author: Ghassan Zahdan (http://www.jguru.com/guru/viewbio.jsp?EID=426857), May 23, 2001I was not able to find CachedRowSetin the latest SDK. Can anyone help tell how to use it no send me an example of importing it in you application.

Re: CachedRowSet usability and accessibility from you Client and server Author: Detlev Valentini (http://www.jguru.com/guru/viewbio.jsp?EID=540113), Nov 6, 2001The implementations of RowSet are still in Early Access Phase.If you want to download it, you have to register at developers.java.sun.com.You can get download (and register) by using this address:http://developer.java.sun.com/developer/earlyAccess/crs.They also provide you with some examples.

What's new in JDBC 3.0?Location: http://www.jguru.com/faq/view.jsp?EID=317275 Created: Jan 31, 2001 Modified: 2001-01-31 09:44:31.44Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

Probably the new features of most interest are: Savepoint support Reuse of prepared statements by connection pools Retrieval of auto-generated keys Ability to have multiple open ResultSet objects Ability to make internal updates to the data in Blob and Clob objects

Page 115: Jdbc Faq From Jguru

Ability to Update columns containing BLOB, CLOB, ARRAY and REF types

Both java.sql and javax.sql ( JDBC 2.0 Optional Package ) are expected to be included with J2SE 1.4.

For additional features and complete information, the specification can be downloaded from JDBC API Specifications.

Why do I get "Unknown SQL Type" when I try to store an object with the JAVA_OBJECT type?Location: http://www.jguru.com/faq/view.jsp?EID=317278 Created: Jan 31, 2001 Modified: 2001-01-31 09:45:08.064Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

While the JDBC spec supports the JAVA_OBJECT type and has had getObject() and setObject() for quite a while, the underlying DBMS engine must also specifically understand and support Java objects ( not many do at this point ) or you will get this type of exception.

Are there any Java classes available that provide SQL builder/SQL by example functionality?Location: http://www.jguru.com/faq/view.jsp?EID=317300 Created: Jan 31, 2001 Modified: 2001-01-31 10:23:18.737Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Yongfeng Xiao (http://www.jguru.com/guru/viewbio.jsp?EID=216776

One resource is the SQLQueryBuilderPane contained in JTOpen. Although much of the code in JTOpen is oriented towards and specific to the AS/400, this class and many others may be used in any Java application. The price is right ( free ) and the ( open ) source is available for download.Comments and alternative answers

Another free and open source ( GPL ) resource is Admin... Author: Christopher Bowland (http://www.jguru.com/guru/viewbio.jsp?EID=217833), Feb 2, 2001Another free and open source ( GPL ) resource is Admin Tool.

What considerations apply if I want to write portable SQL statements that work on many different databases? Is it enough to follow the SQL-92 standard?Location: http://www.jguru.com/faq/view.jsp?EID=317319 Created: Jan 31, 2001 Modified: 2001-01-31 10:55:05.514Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Erik Winlöf (http://www.jguru.com/guru/viewbio.jsp?EID=44108

Unfortunately, no. There are lots of databases and drivers out there with varying levels of support. It's worth taking note of all the getXXX and supportsXXX methods in the DatabaseMetaData class for those who want to provide and check everything.

However, a JDBC Compliant ( and that is a specific, meaningful term ) driver will always support ANSI SQL-92 Entry Level. For more information, see the SQL

Page 116: Jdbc Faq From Jguru

Conformance section in my JDBC 2.0 Fundamentals Short Course at the Java Developer Connection.

How can I retrieve an Oracle VARRAY from a stored procedure? Location: http://www.jguru.com/faq/view.jsp?EID=317321 Created: Jan 31, 2001 Modified: 2001-01-31 10:55:34.157Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Arun Solleti (http://www.jguru.com/guru/viewbio.jsp?EID=298895

In JDBC(tm) Technology Guide: Getting Started, Section 8: Mapping SQL and Java Types, the table in 8.9.7, JDBC Types Mapped to Database-specific SQL Types, shows that an Oracle VARRAY maps to a java.sql.Array, which should resolve your issue.

How can I format, display, parse and update a java.sql.Date? Code examples would be helpful. Location: http://www.jguru.com/faq/view.jsp?EID=338014 Created: Feb 24, 2001 Modified: 2001-02-24 22:11:45.47Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Steve Pence (http://www.jguru.com/guru/viewbio.jsp?EID=250050

As several responders noted, java.sql.Date is a subclass of java.util.Date, with hour, minute, second and millisecond values set to zero. The various databases differ in their expectation of the exact form of the value to be sent to update/insert a date column. JDBC handles this by means of an escape in the form {d 'yyyy-mm-dd'}. That is how one would send it in a straight ahead VALUES clause or 'SET xxx =' phrase for a Statement. As is often the case, a prepared statement is very helpful; One can create a java.sql.Date and use PreparedStatement.setDate(), which will handle this format for you. In any event, the driver is responsible for the final format acceptable to the specific database.

Date retrieval is straightforward, just use ResultSet.getDate().

How do I display and parse a date? gives code to display and retrieve Date information.

If the date value you need is not immediately available as a long, the Calendar, and specifically the GregorianCalendar, class can be used. For examples and information, see How can I get yesterday's date? and How can I generate a java.sql.Timestamp from text fields formatted as MM/DD/YYYY and/or HH:MM:SS ( Month/Day/Year - Hours/Minutes/Seconds )?

Thanks to

Arif Amjad

Jorge Jordão

CJ Jouhal

Dawei Jiang

Page 117: Jdbc Faq From Jguru

Luis F. Canals Samaniego

for contributing to this answer.

Comments and alternative answers

java.sql.Date and time zone Author: denis cardon (http://www.jguru.com/guru/viewbio.jsp?EID=1112424), Sep 2, 2003It looks like as if the java.sql.Date contains time zone information. I think this behavior is strange, since there is no time component in the java.sql.Date. This is probably due to the java.util.Date inheritance. I noticed this when I sent java.sql.Date object over RMI between a server (in GMT) and a client (in GMT+2) : the result of date.toString(); give different values (ie one day behind) on client and on server side.I hope this info may be interesting for people dealing with pure date (ie. not time, no timezone) objects within java rich client communicating with a app server.

How do I create an updatable ResultSet?Location: http://www.jguru.com/faq/view.jsp?EID=338049 Created: Feb 24, 2001 Modified: 2001-02-24 23:43:53.831Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Just as is required with a scrollable ResultSet, the Statement must be capable of returning an updatable ResultSet. This is accomplished by asking the Connection to return the appropriate type of Statement using Connection.createStatement(int resultSetType, int resultSetConcurrency). The resultSetConcurrency parameter must be ResultSet.CONCUR_UPDATABLE.

The actual code would look like this:

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); Note that the spec allows a driver to return a different type of Statement/ResultSet than that requested, depending on capabilities and circumstances, so the actual type returned should be checked with ResultSet.getConcurrency().

How do I get runtime information about the JDBC Driver?Location: http://www.jguru.com/faq/view.jsp?EID=338050 Created: Feb 24, 2001 Modified: 2001-02-24 23:44:28.666Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Use the following DatabaseMetaData methods:

getDriverMajorVersion()

Page 118: Jdbc Faq From Jguru

getDriverMinorVersion()

getDriverName()

getDriverVersion()

What is required for a driver to be JDBC Compliant?Location: http://www.jguru.com/faq/view.jsp?EID=391290 Created: Mar 30, 2001 Modified: 2001-04-30 15:20:20.908Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The requirements for a JDBC Compliant driver are spelled out at JDBC Data Access API For Driver Writers in section A1. The additional sections A2 through A5 should be thoroughly reviewed as allowed variants and suggested implementations are discussed there. Note that some specifics are mentioned in the API descriptions as "A JDBC Compliant driver will return..."

How can I determine whether a Statement and its ResultSet will be closed on a commit or rollback?Location: http://www.jguru.com/faq/view.jsp?EID=391306 Created: Mar 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Use the DatabaseMetaData methods supportsOpenStatementsAcrossCommit() and supportsOpenStatementsAcrossRollback().

Where can I find information about SQL-92 that a JDBC Compliant driver must support? Location: http://www.jguru.com/faq/view.jsp?EID=391318 Created: Mar 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

A JDBC Compliant driver must support SQL-92 at the entry level, A good resource for these, as well as the Intermediate and Full levels, is FIPS PUB 127-2: The Standard for Database Language SQL.

Where can I find information about the ODBC-defined SQL grammar that a JDBC Compliant driver must support? Location: http://www.jguru.com/faq/view.jsp?EID=391319 Created: Mar 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

A JDBC Compliant driver must support the ODBC Minimum SQL grammar. Some resources for the grammar levels are CodeBase SQL/ODBC Conformance and AcuODBC SQL Conformance. Also see What considerations apply if I want to write portable SQL statements that work on many different databases? Is it enough to follow the SQL-92 standard? for more information.

What is the best strategy to determine that the DBMS is up and that the Connections from my pool are still viable before handing them out?Location: http://www.jguru.com/faq/view.jsp?EID=391331 Created: Mar 30, 2001 Modified: 2002-03-23 22:34:15.73Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question

Page 119: Jdbc Faq From Jguru

originally posed by Rakesh Sahu (http://www.jguru.com/guru/viewbio.jsp?EID=127108

There were a number of responses to this question. I am including a distillation of these plus some additional information to consider.

It should be obvious that: A) Some statement that requires a database engine response must be executed. B) That any interaction with the DBMS engine will take some time and therefore slow down application responsiveness. C) That the validity of the Connection can only be guaranteed as of the time of the last check, meaning that the class using the method must still check for exceptions.

With these in mind, my own conclusions are that the application should handle any problems with invalid Connections using a standard exception handler for this case and that connection pools should have a returnInvalidConnection method to insure that the bad Connection is not checked out again.

For those that still want to validate a Connection from within the pool, I did some testing. One often sees Connection.getMetaData() used for validation. However, some production quality drivers report zero time spent in this method, even over a 56K modem. This implies to me that those drivers just check for a DatabaseMetaData object existence and return; clearly there is not a trip to the DBMS server and back in zero time. I also considered just issuing a Connection.commit(), but I suspect that there are drivers smart enough to know when no transactions are pending and therefore just swallow the call for efficiency.

In the end, I have concluded that, for certainty across drivers, a query probably must be issued. One possibility would be to create a table with no rows at pool initialization time and perform a SELECT COUNT(*) on it for validation. COUNT() is generally optimized for SELECTs without search criteria. jGuru would be happy to receive feedback from anyone who has tested timings on other methods guaranteed to force a response from the DBMS engine.

swarraj kulkarni, Modha Kumar, Harikrishna Neerkaje and Ari Manninen also contributed to this answer.

Can I use Connection.isClosed() to validate a Connection?Location: http://www.jguru.com/faq/view.jsp?EID=391332 Created: Mar 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

No. Here's the quote from 2.1.9 Freeing DBMS Resources:

"Note that the method Connection.isClosed is guaranteed to return true only when it is called after the method Connection.close has been called. As a result, a programmer cannot depend on this method to indicate whether a connection is valid or not. Instead, a typical JDBC client can determine that a connection is invalid by catching the exception that is thrown when a JDBC operation is attempted."

Comments and alternative answers

Validating a connection

Page 120: Jdbc Faq From Jguru

Author: Sean Batten (http://www.jguru.com/guru/viewbio.jsp?EID=395165), Apr 4, 2001Another way to validate a connection is to call Connection.getMetaData(). If the connection has been closed, for whatever reason, you'll get a SQLException. This approach saves you from having to issue a SQL request (such as SELECT COUNT(*) from sometable) which is not generic.

Re: Validating a connection Author: Anthony Yam (http://www.jguru.com/guru/viewbio.jsp?EID=441737), Jun 19, 2001If I do find that my connection has been lost, is there any way to reestablish my connection and execute a prepared statement that has already been created?

Re: Validating a connection Author: Erki Suurjaak (http://www.jguru.com/guru/viewbio.jsp?EID=501734), Sep 22, 2001That can be as (un)reliable as Connection.isClosed(), as it also might check the connection validity via isClosed() (and at least the sun.jdbc.odbc.JdbcOdbcDriver driver does). Basically, it would seem that performing a real server-side operation (like a query) is the only way of really determining whether a connection is usable.

Re: Validating a connection Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382), Apr 22, 2002With IBM's AS400 JDBC driver, the Connection.getMetaData method will always return a result. You can't rely upon that method to validate the connection.

Re[2]: Validating a connection Author: Gaurav Sharma (http://www.jguru.com/guru/viewbio.jsp?EID=66767), Jun 21, 2002Then is there any reliable way of cheking the validity of the coonection object!

diff between bad sql & bad connection Author: Marc Swingler (http://www.jguru.com/guru/viewbio.jsp?EID=1052065), Jan 30, 2003How do you tell the difference between a bad connection and invalid SQL when calling<Statement Object>.executeQuery(<valid-invalid SQL>)in a JDBC DB independent way?

It may be JDBC impl. independent as to whether the DB will be hit if you call getMetaData on the Connection object (you may have already done a connection.getMetaData(); I do this exactly once). Additionally, calling

Page 121: Jdbc Faq From Jguru

getMetaData before every query would be dog slow.

If I find warnings in getWarnings() after catching a SQLException does it guarantee that I've sucessfully connected to the DB (but had some other DB error)? And not just on JDBC Driver X, but on any compliant driver.

Why do I get the message "No Suitable Driver"?Location: http://www.jguru.com/faq/view.jsp?EID=391334 Created: Mar 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Often the answer is given that the correct driver is not loaded. This may be the case, but more typically, the JDBC database URL passed is not properly constructed. When a Connection request is issued, the DriverManager asks each loaded driver if it understands the URL sent. If no driver responds that it understands the URL, then the "No Suitable Driver" message is returned.Comments and alternative answers

Custom ClassLoaders Author: Douglas Seifert (http://www.jguru.com/guru/viewbio.jsp?EID=460284), Jul 23, 2001I have also seen this error when I load the driver class using a ClassLoader that is not the same as the ClassLoader that loads the class where DriverManager.getConnection() is called. I'm not sure if this is an error or a security feature, however.

Re: Custom ClassLoaders Author: Arjan van der Veen (http://www.jguru.com/guru/viewbio.jsp?EID=486198), Aug 29, 2001I've noticed the same problem. Do you know how to avoid this?

Re: Custom ClassLoaders Author: Ritesh M (http://www.jguru.com/guru/viewbio.jsp?EID=540882), Nov 7, 2001I am also getting this error. I am able to connect using a normal application. But when i am trying to do the same using JRun and JSP its giving error "No Suitable Driver". I am also able to connect using oracle driver/connect string... but DB2 gives a error...

Re: Re: Custom ClassLoaders Author: Sakwar Sudtzh (http://www.jguru.com/guru/viewbio.jsp?EID=545049), Nov 12, 2001Very often the error "No suitable driver" is caused by the following: http://www.tru64unix.compaq.com/data-access/doc/SequeLnk/java/body.htm Search for "suitable"

Page 122: Jdbc Faq From Jguru

Re[3]: Custom ClassLoaders Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Mar 23, 2002The reference here is to the fact that on some systems, the static code registration strategy just doesn't work. That's a reason I usually recommend using Class.forName("myJDBCDriver").newInstance();.

While this can be extra, duplicated work, it's much better than failing.

When I create multiple Statements on my Connection, only the current Statement appears to be executed. What's the problem? Location: http://www.jguru.com/faq/view.jsp?EID=391335 Created: Mar 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

All JDBC objects are required to be threadsafe. Some drivers, unfortunately, implement this requirement by processing Statements serially. This means that additional Statements are not executed until the preceding Statement is completed. See What is required for a driver to be JDBC Compliant ? for a link to driver requirements.

When is a Statement considered complete?Location: http://www.jguru.com/faq/view.jsp?EID=391336 Created: Mar 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

See 4.1.3 Statement Completion in the JDK documentation.

Note that, for a default ResultSet, the Statement is not complete until all rows have been retrieved. However, this can be affected by the state of autocommit and the capabilities of the driver. See: How can I determine whether a Statement and its ResultSet will be closed on a commit or rollback?

Can a single thread open up mutliple connections simultaneously for the same database and for same table?Location: http://www.jguru.com/faq/view.jsp?EID=391401 Created: Mar 31, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by OBUCHI MACHINI (http://www.jguru.com/guru/viewbio.jsp?EID=297581

The general answer to this is yes. If that were not true, connection pools, for example, would not be possible. As always, however, this is completely dependent on the JDBC driver.

You can find out the theoretical maximum number of active Connections that your driver can obtain via the DatabaseMetaData.getMaxConnections method. Although there is some ambiguity in the API documentation, the JDBC API Tutorial and Reference, 2nd Ed: Java 2 clarifies with "that can be made through this driver instance."

Page 123: Jdbc Faq From Jguru

How can I get a DBMS to connect to and use data on... How can I get a DBMS to connect to and use data on a CD?Location: http://www.jguru.com/faq/view.jsp?EID=409336 Created: Apr 25, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by nidhi shanker (http://www.jguru.com/guru/viewbio.jsp?EID=339706

In general you would need to use a DB engine that allows a connection to a database by drive and directory, like InstantDB or Cloudscape, which would also be small enough to run from the CD. Apparently this can also be done with Access, although in that case you would need a DSN and deal with the non-production quality JDBC-ODBC bridge.

Other DB engines often have an ATTACH command, but they usually expect to connect via another DB engine or middleware. While this would seem to be an ideal browser/applet combination, note that 1) without the plug-in you are limited to partial 1.1 support and 2) you must deal with the sandbox security model even for read-only data.

Where can I use parameter markers in prepared statements?Location: http://www.jguru.com/faq/view.jsp?EID=409344 Created: Apr 25, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The primary rule to keep in mind is that the DB engine must be able to determine the data type of the parameter. In addition, databases may have differing rules for specific situations. Here's what DB2 ( see subsection Rules > Parameter Markers ) and Cloudscape have to say. For other databases, see Where can I find online documentation for database xyz?Comments and alternative answers

prepared statements Author: Shirley C (http://www.jguru.com/guru/viewbio.jsp?EID=1243424), May 10, 2005Can a parameter marker be used in an order by?

IE: "select * from pubs order by ?"

I'm using a SQL server database.

Is there a practical limit for the number of SQL statements that can be added to an instance of a Statement objectLocation: http://www.jguru.com/faq/view.jsp?EID=410782 Created: Apr 26, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by gordon inamine (http://www.jguru.com/guru/viewbio.jsp?EID=406935

Page 124: Jdbc Faq From Jguru

While the specification makes no mention of any size limitation for Statement.addBatch(), this seems to be dependent, as usual, on the driver. Among other things, it depends on the type of container/collection used. I know of at least one driver that uses a Vector and grows as needed. I've seen questions about another driver that appears to peak somewhere between 500 and 1000 statements.

Unfortunately, there doesn't appear to be any metadata information regarding possible limits. Of course, in a production quality driver, one would expect an exception from an addBatch() invocation that went beyond the command list's limits.

Comments and alternative answers

size limit for addBatch method Author: Yinghui (Susan) Zeng (http://www.jguru.com/guru/viewbio.jsp?EID=743520), Feb 3, 2004I am using oracle driver. When the number of sql statments reach 1588, the addBatch() method quit without giveing any exception or error. Not only the method quit. It also break the loop that it was in, so other statements within the same loop quit also!!! Susan

What does setFetchSize() really do?Location: http://www.jguru.com/faq/view.jsp?EID=410783 Created: Apr 26, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The API documentation explains it pretty well, but a number of programmers seem to have a misconception of its functionality. The first thing to note is that it may do nothing at all; it is only a hint, even to a JDBC Compliant driver. setFetchSize() is really a request for a certain sized blocking factor, that is, how much data to send at a time.

Because trips to the server are expensive, sending a larger number of rows can be more efficient. It may be more efficient on the server side as well, depending on the particular SQL statement and the DB engine. That would be true if the data could be read straight off an index and the DB engine paid attention to the fetch size. In that case, the DB engine could return only enough data per request to match the fetch size. Don't count on that behavior. In general, the fetch size will be transparent to your program and only determines how often requests are sent to the server as you traverse the data.

Also, both Statement and ResultSet have setFetchSize methods. If used with a Statement, all ResultSets returned by that Statement will have the same fetch size. The method can be used at any time to change the fetch size for a given ResultSet. To determine the current or default size, use the getFetchSize methods.

How can I ensure that my app has the latest data?Location: http://www.jguru.com/faq/view.jsp?EID=411926 Created: Apr 28, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Page 125: Jdbc Faq From Jguru

Typically an application retrieves multiple rows of data, providing a snapshot at an instant of time. Before a particular row is operated upon, the actual data may have been modified by another program. When it is essential that the most recent data is provided, a JDBC 2.0 driver provides the ResultSet.refreshRow method.

Note that this can be quite expensive if the fetch size is high, causing multiple rows to be returned ( see What does setFetchSize() really do? ) and obviously causes a trip back to the server in any case. This will only work for a scrollable ResultSet requested with ResultSet.TYPE_SCROLL_SENSITIVE; the method call is ignored for other types. For more information, see 3.3.7 Getting the Most Recent Data in the Advanced Tutorial at the JDC.

How can I tell if the data I get from a default ResultSet reflects changes since the time the query was executed but not yet retrieved?Location: http://www.jguru.com/faq/view.jsp?EID=411927 Created: Apr 28, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

You can't, with complete confidence. That's because some ResultSets ( those that need to be sorted, for example ) require the creation of temporary tables using a data snapshot. However, those that can effectively read along an index can be checked for what is termed "incremental materialization" by using the DatabaseMetaData methods othersDeletesAreVisible(int type), othersInsertsAreVisible(int type) and othersUpdatesAreVisible(int type). The "type" parameter is one of ResultSet.TYPE_FORWARD_ONLY ( for a default ResultSet ), ResultSet.TYPE_SCROLL_SENSITIVE or ResultSet.TYPE_SCROLL_SENSITIVE.

Keep the initial caveat in mind: The methods will still return true ( if the DB engine is capable ) even when a sorted ResultSet is returned.

I've requested an updatable ResultSet and my driver supports them, but I still don't get an updatable ResultSet. Why?Location: http://www.jguru.com/faq/view.jsp?EID=411928 Created: Apr 28, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Aside from driver bugs, some queries cannot be updatable due to identification, integrity or DB limitation issues. For that reason, ResultSet.getConcurrency() generally should be invoked to determine if an updatable ResultSet was returned.

For more information and a list of guidelines that should return an updatable ResultSet, see 5.1.17 Queries That Produce Updatable Result Sets.

What scalar functions can I expect to be supported by JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=412811 Created: Apr 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

JDBC supports numeric, string, time, date, system, and conversion functions on scalar values. For a list of those supported and additional information, see section A.1.4 Support Scalar Functions in the JDBC Data Access API For Driver Writers. Note that drivers are only expected to support those scalar functions that are supported by the underlying DB engine.

Page 126: Jdbc Faq From Jguru

Where can I find an example of discovering and using supported scalar functions?Location: http://www.jguru.com/faq/view.jsp?EID=412813 Created: Apr 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

See Escape Syntax and Scalar Functions in the JDBCTM 2.0 Fundamentals short course.

How do I create a java.sql.Time object?Location: http://www.jguru.com/faq/view.jsp?EID=412831 Created: Apr 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

java.sql.Time descends from java.util.Date, but uses only the hour, minute and second values. There are two methods to create a Time object. The first uses a Calendar object, setting the year, month and day portions to January 1, 1970, which is Java's zero epoch. The millisecond value must also be set to zero. At that point, Calendar.getTime().getTime() is invoked to get the time in milliseconds. That value is then passed to a Time constructor:

Calendar cal = Calendar.getInstance(); // set Date portion to January 1, 1970 cal.set( cal.YEAR, 1970 ); cal.set( cal.MONTH, cal.JANUARY ); cal.set( cal.DATE, 1 ); cal.set( cal.MILLISECOND, 0 ); java.sql.Time jsqlT = new java.sql.Time( cal.getTime().getTime() );The second method is Time's valueOf method. valueOf() accepts a String, which must be the time in JDBC time escape format - "hh:mm:ss". For example,

java.sql.Time jsqlT = java.sql.Time.valueOf( "18:05:00" );creates a Time object representing 6:05 p.m. To use this method with a Calendar object, use:

java.sql.Time jsqlT = java.sql.Time.valueOf( cal.get(cal.HOUR_OF_DAY) + ":" + cal.get(cal.MINUTE) + ":" + cal.get(cal.SECOND) );which produces a Time object with the same value as the first example.Comments and alternative answers

java.sql.Time Author: Prasanna Tuladhar (http://www.jguru.com/guru/viewbio.jsp?EID=875912),

Page 127: Jdbc Faq From Jguru

May 13, 2002To create a java.sql.Time simply use this java.sql.Time tm = new java.sql.Time(System.currentTimeMillis()); //ly to get date java.sql.Date dt = new java.sql.Date(System.currentTimeMillis());

How do I create a java.sql.Date object?Location: http://www.jguru.com/faq/view.jsp?EID=422110 Created: May 15, 2001 Modified: 2001-05-20 11:44:56.136Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

java.sql.Date descends from java.util.Date, but uses only the year, month and day values. There are two methods to create a Date object. The first uses a Calendar object, setting the year, month and day portions to the desired values. The hour, minute, second and millisecond values must be set to zero. At that point, Calendar.getTime().getTime() is invoked to get the java.util.Date milliseconds. That value is then passed to a java.sql.Date constructor:

Calendar cal = Calendar.getInstance(); // set Date portion to January 1, 1970 cal.set( cal.YEAR, 1970 ); cal.set( cal.MONTH, cal.JANUARY ); cal.set( cal.DATE, 1 ); cal.set( cal.HOUR_OF_DAY, 0 ); cal.set( cal.MINUTE, 0 ); cal.set( cal.SECOND, 0 ); cal.set( cal.MILLISECOND, 0 ); java.sql.Date jsqlD = new java.sql.Date( cal.getTime().getTime() );The second method is java.sql.Date's valueOf method. valueOf() accepts a String, which must be the date in JDBC time escape format - "yyyy-mm-dd". For example,

java.sql.Date jsqlD = java.sql.Date.valueOf( "2010-01-31" );creates a Date object representing January 31, 2010. To use this method with a Calendar object, use:

java.sql.Date jsqlD = java.sql.Date.valueOf( cal.get(cal.YEAR) + ":" + cal.get(cal.MONTH) + ":" + cal.get(cal.DATE) );which produces a Date object with the same value as the first example.Comments and alternative answers

Wow, so complicated... !!! Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?

Page 128: Jdbc Faq From Jguru

EID=32727), May 15, 2001Joe,Your solution it's way complex and, performance wise, not better than this:

Calendar calendar = new GregorianCalendar(2001, 0, 1);java.sql.Date date = new java.sql.Date(calendar.getTimeInMillis());

or, if you like it on one line:

java.sql.Date date = new java.sql.Date((new GregorianCalendar(2001, 0, 1)).getTimeInMillis());

Re: Wow, so complicated... !!! Author: Mekaiel Hussain (http://www.jguru.com/guru/viewbio.jsp?EID=433855), Jun 5, 2001java.sql.Date date = new java.sql.Date(calendar.getTimeInMillis()); This will not work in Java as you get this at compile time "XmlSrmCreator.java": Error #: 306 : method getTimeInMillis() has protected access in class java.util.Calendar at line 180, column 57

Re: Re: Wow, so complicated... !!! Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727), Jun 5, 2001Hi,Yes, I forgot the fact that it's protected...Well, no problem, just use getTime()...

Calendar calendar = new GregorianCalendar(2001, 0, 1);java.sql.Date date = new java.sql.Date(calendar.getTime().getTime());

or, in one line:

java.sql.Date date = new java.sql.Date((new GregorianCalendar(2001, 0, 1)).getTime().getTime());

Convert current System date into a Date object Author: Mekaiel Hussain (http://www.jguru.com/guru/viewbio.jsp?EID=433855), Jun 5, 2001Calendar cal = Calendar.getInstance(); cal.set( cal.YEAR, cal.get (Calendar.YEAR) ); cal.set( cal.MONTH, cal.get(Calendar.MONTH)); cal.set( cal.DATE, cal.get(Calendar.DATE)); Date currentDate = new Date(cal.getTime().getTime()); System.out.println(currentDate.toString());

Re: Convert current System date into a Date object Author: Srinivas Murthy (http://www.jguru.com/guru/viewbio.jsp?

Page 129: Jdbc Faq From Jguru

EID=445144), Jun 25, 2001java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());

Re: Re: Convert current System date into a Date object Author: Zeljko Trogrlic (http://www.jguru.com/guru/viewbio.jsp?EID=4607), Jun 29, 2001java.sql.Date date = new java.sql.Date(System.currentMilis());

Normalization Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Mar 23, 2002The point of the "so complicated" code is to properly create a normalized Date that works correctly in all circumstances. java.util.Date, which underlies java.sql.Date, has some major flaws. If one creates a java.sql.Date by just grabbing milliseconds, as most of the suggestions do, one will have serious problems with date comparisons and arithmetic.

Re: Normalization Author: Yishai Hornbacher (http://www.jguru.com/guru/viewbio.jsp?EID=1008981), Oct 7, 2002Good point, but the suggestions create an unnecessary Calendar object, which may or may not be an issue, depending on how often you do this for a given JDBC call.

To do this without a Calendar object, this will do:

long currentTime = System.currentTimeMillis();new java.sql.Date(currentTime - (currentTime % 86400000));

Re[2]: Normalization Author: Yishai Hornbacher (http://www.jguru.com/guru/viewbio.jsp?EID=1008981), Oct 7, 2002Actually, the above does not account for time zones. That is just a warning, but having the Calendar take care of it for you can be useful.

Re[3]: Normalization Author: David Thirakul (http://www.jguru.com/guru/viewbio.jsp?EID=1205929), Oct 18, 2004Indeed, it doesn't consider time zones or locale values. Use Calendar especially if you need to manipulate your date.

What does normalization mean for java.sql.Date and java.sql.Time?Location: http://www.jguru.com/faq/view.jsp?EID=422111 Created: May 15, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Page 130: Jdbc Faq From Jguru

These classes are thin wrappers extending java.util.Date, which has both date and time components. java.sql.Date should carry only date information and a normalized instance has the time information set to zeros. java.sql.Time should carry only time information and a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and the milliseconds portion set to zero.

What's the fastest way to normalize a Time object?Location: http://www.jguru.com/faq/view.jsp?EID=422112 Created: May 15, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Of the two recommended ways when using a Calendar( see How do I create a java.sql.Time object? ), in my tests, this code ( where c is a Calendar and t is a Time ):

c.set( Calendar.YEAR, 1970 ); c.set( Calendar.MONTH, Calendar.JANUARY ); c.set( Calendar.DATE, 1 ); c.set( Calendar.MILLISECOND, 0 );

t = new java.sql.Time( c.getTime().getTime() );was always at least twice as fast as:

t = java.sql.Time.valueOf( c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) );When the argument sent to valueOf() was hardcoded ( i.e. valueOf( "13:50:10" ), the time difference over 1000 iterations was negligible.Comments and alternative answers

If speed is important, don't use the calendar object Author: Yishai Hornbacher (http://www.jguru.com/guru/viewbio.jsp?EID=1008981), Oct 7, 2002If speed is important in your normalization, it would be best to avoid the calendar object all together: new java.sql.Time(System.currentTimeMillis() % 86400000);

Re: If speed is important, don't use the calendar object Author: Yishai Hornbacher (http://www.jguru.com/guru/viewbio.jsp?EID=1008981), Oct 7, 2002The above does not account for time zones. It is possible to compensate yourself without using the Calendar object, but it will often not be worth the effort.

I've retrieved a Time value from a table and compared it to the current Time. Why don't the java.sql.Time methods before() and after() work properly?

Page 131: Jdbc Faq From Jguru

Location: http://www.jguru.com/faq/view.jsp?EID=422114 Created: May 15, 2001 Modified: 2001-07-26 12:02:44.899Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

There is one root cause to this problem, although it may come from two different directions. In order for Time comparisons to work properly, the Time objects must be normalized ( see How do I create a java.sql.Time object? ).

If the application doesn't normalize its Time object OR if the JDBC driver does not normalize returned Time objects ( this is a bug, but I know of one otherwise production quality driver that does not do this ), before() and after() will show seemingly erroneous results.

Why do I have problems writing BLOBs/CLOBs longer than 4k with an Oracle database?Location: http://www.jguru.com/faq/view.jsp?EID=431031 Created: May 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

JDBC functionality is completely dependent on the functionality of the JDBC driver AND the underlying DBMS engine. At one time there was a 4k restriction on LOBs. It's not clear from the documentation exactly when this restriction was lifted, although it definitely has been by 8i, Release 2(8.1.6). Even so, there are other limitations and restrictions that can cause write problems for LOBs.

The best resource is the source, even though Oracle has an annoying habit of giving examples using proprietary methods, which hinders portability. See: Oracle8i Application Developer's Guide - Large Objects (LOBs), especially section 6 Frequently Asked Questions, as well as the Oracle8i JDBC Developer's Guide and Reference. Note that Oracle Technical Network registration is required to access these documents.

Does catching an SQLException mean that the transaction was definitely not completed and/or that the invoked method did not execute?Location: http://www.jguru.com/faq/view.jsp?EID=431032 Created: May 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Not necessarily, and, unfortunately, there is no generic means of determining current state. As noted in JDBC API Tutorial and Reference, 2nd Ed: Java 2, "The safest course is to call the method rollback when there is any doubt and then to start again."

What is SQLException chaining?Location: http://www.jguru.com/faq/view.jsp?EID=431034 Created: May 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

There are often multiple reasons for a JDBC problem. SQLException has a method, getNextException, which returns either the next exception or null when all exceptions have been retrieved. Obtaining multiple exceptions this way is termed "chaining". You can see a minimal form of this at How to raise a custom SQLWarning?.

Page 132: Jdbc Faq From Jguru

For more information and a complete code example, see the SQL Exceptions section in my JDBC 2.0 Fundamentals Short Course at the Java Developer Connection.

What JDBC objects generate SQLWarnings?Location: http://www.jguru.com/faq/view.jsp?EID=431118 Created: May 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Connections, Statements and ResultSets all have a getWarnings method that allows retrieval. Keep in mind that prior ResultSet warnings are cleared on each new read and prior Statement warnings are cleared with each new execution. getWarnings() itself does not clear existing warnings, but each object has a clearWarnings method.

Can I chain SQLWarnings?Location: http://www.jguru.com/faq/view.jsp?EID=431120 Created: May 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Yes. SQLWarning is a subclass of SQLException. After the first warning is retrieved via getWarnings(), subsequent warnings are obtained in a way identical to SQLException chaining. You can see a minimal form of this at How to raise a custom SQLWarning?. For more information and a complete code example, see the SQL Warnings section in my JDBC 2.0 Fundamentals Short Course at the Java Developer Connection.

JDBC - General Error I am getting java.sql.SQLException: General error when working with my database. Please help me.Location: http://www.jguru.com/faq/view.jsp?EID=431130 Created: May 30, 2001 Author: JIA Java Italian Association (http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by Gireesh Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=406561

SQLException may provide further information in nested exceptions. Try SQLException chaining to help resolve the real issue.

Joe Sam Shirah adds: Tom is dead on in that no one can really resolve a problem with no more information than "General error" and that chaining exceptions ( or possibly checking a log ) is the way to get as much information as is available. For more on SQLException chaining, see: What is SQLException chaining?

Comments and alternative answers

java.sql.SQLException: General error Author: ganesh watve (http://www.jguru.com/guru/viewbio.jsp?EID=295982), Jul 2, 2002

i have also got same type of error.but when i checked the code i have closed the connection & was trying to call createStatement()

Page 133: Jdbc Faq From Jguru

method

Connection con;

Statement st;

con.close();

st=con.createStatement();

Re: java.sql.SQLException: General error Author: Paul s (http://www.jguru.com/guru/viewbio.jsp?EID=1018561), Oct 28, 2002Check the log if your running from a server. Thats how i fixed my problem, it ended up being a null pointer exception. I wish it just told me that instead of saying general error

Where can I learn (more) about managing collections of data in Java?Location: http://www.jguru.com/faq/view.jsp?EID=431186 Created: May 30, 2001 Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Collections FAQ.

Where can I learn (more) about Java's EJB (Enterprise JavaBeans)? Location: http://www.jguru.com/faq/view.jsp?EID=431189 Created: May 30, 2001 Modified: 2001-06-15 23:12:08.671Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru EJB FAQ.

Where can I learn (more) about Java running on IBM's AS/400 series computers? Location: http://www.jguru.com/faq/view.jsp?EID=431194 Created: May 30, 2001 Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Java400 FAQ.

Page 134: Jdbc Faq From Jguru

Where can I learn (more) about Java's support for transaction processing?Location: http://www.jguru.com/faq/view.jsp?EID=431948 Created: May 31, 2001 Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Transactions FAQ.

Getting a newly created id Is there any way I can determine the auto-generated number with MySQL after performing an insert without sending another query?Location: http://www.jguru.com/faq/view.jsp?EID=440259 Created: Jun 16, 2001 Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by Brian Smith (http://www.jguru.com/guru/viewbio.jsp?EID=13411

This is "MMSQL" specific functionality and you can get information on how to access it on the Using MySQL specific functionality page of the MM.MySQL Documentation.Comments and alternative answers

Is there a way to do something similar with SQLServer? Author: Luke Latimer (http://www.jguru.com/guru/viewbio.jsp?EID=449934), Jul 11, 2001Thanks

Why doesn't JDBC accept URLs instead of a URL string?Location: http://www.jguru.com/faq/view.jsp?EID=444384 Created: Jun 24, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

In order for something to be a java.net.URL, a protocol handler needs to be installed. Since there is no one universal protocol for databases behind JDBC, the URLs are treated as strings. In Java 1.4, these URL strings have a class called java.net.URI. However, you still can't use a URI to load a JDBC driver, without converting it to a string.Comments and alternative answers

That depends... Author: James Chen (http://www.jguru.com/guru/viewbio.jsp?EID=452107), Jul 23, 2001This kind of solution depends on how the java.sql.Driver to be implemented and how the connection url string handled. You could provide an implementation to support URL and remote database connection.

Re: That depends... Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Mar 23, 2002

Page 135: Jdbc Faq From Jguru

Yes, but then you've created your own non-standard API.

What are the components of the JDBC URL for Oracle's "thin" driver and how do I use them?Location: http://www.jguru.com/faq/view.jsp?EID=444466 Created: Jun 24, 2001 Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985) Question originally posed by lakshman prasad (http://www.jguru.com/guru/viewbio.jsp?EID=423825

Briefly: jdbc:oracle:thin:@hostname:port:oracle-sid 1. in green the Oracle sub-protocol (can be oracle:oci7:@, oracle:oci8:@,

racle:thin:@, etc...) is related on the driver you are unsign and the protocol to communicate with server.

2. in red the network machine name, or its ip address, to locate the server where oracle is running.

3. in blue the port (it is complementary to the address to select the specific oracle service)

4. in magenta the sid, select on which database you want to connect.

example: jdbc:oracle:thin:@MyOracleHost:1521:MyDBI've found sometime user/password encoded in the URL. I never used this form, but here's an example:

jdbc:oracle:thin:scott/tiger@MyOracleHost:1521:MyDBwhere user=scott and pass=tiger.

How can I connect to mysql database using jdbc?Location: http://www.jguru.com/faq/view.jsp?EID=444472 Created: Jun 24, 2001 Modified: 2001-06-30 20:04:35.74Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985) Question originally posed by vikrant charde (http://www.jguru.com/guru/viewbio.jsp?EID=433268

Use something like:

// loads the JDBC driver Class.forName("org.gjt.mm.mysql.Driver").newInstance(); // get a database connection Connection conn = DriverManager.getConnection( "jdbc:mysql://hostname/databaseName", "user", "password");obviously the JDBC driver "org.gjt.mm.mysql.Driver" must be in classpath. You can download it from here.

Where can I find Oracle specific JDBC examples?Location: http://www.jguru.com/faq/view.jsp?EID=448086

Page 136: Jdbc Faq From Jguru

Created: Jun 30, 2001 Modified: 2002-01-31 10:37:00.066Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The obvious starting point is Oracle's TechNet ( free membership required ). A specific area is SQLJ & JDBC Advanced Samples. Another site is Java JDBC Coding examples - Connecting to Oracle 8i.Comments and alternative answers

Here you go! Author: Shahram Khorsand (http://www.jguru.com/guru/viewbio.jsp?EID=3357), Jul 8, 2001http://otn.oracle.com/software/tech/java/sqlj_jdbc/software_index.htm

What do the terms catalog, schemaPattern, tableNamePattern, and types stand for in DatabaseMetaData.getTables()? Location: http://www.jguru.com/faq/view.jsp?EID=448087 Created: Jun 30, 2001 Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by peter mathew (http://www.jguru.com/guru/viewbio.jsp?EID=443312

Let's start from the last one. TableName is the name of a Table; Schema is the name of the container of tables ( some DBMSes normally call it 'user' ) and Catalog is a collection of Schemas ( some DBMS normally refer to it as Database ).

The word 'pattern' is just added to underline that you can insert not just a fixed name, but a pattern to narrow your search.

For example, if I use "", I will get back all the tables for the given Schema, in the given Catalog, while if I use "TAB%" I'll get a list of all the tables whose name starts with "TAB".

Where is console output sent (System.out/System.err) in stored procedures written in Java?Location: http://www.jguru.com/faq/view.jsp?EID=448096 Created: Jun 30, 2001 Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

With Oracle, console output from System.out.println()statements will be written to trace files in the Oracle UDUMP destination directory.

source: Oracle FAQ: Java Database Connectivity (JDBC) and JSQL, "What happens when you write to the console from a Java Stored Procedure?"

Joe Sam Shirah adds:

This is apparently one of those cases that is OS and/or DBMS engine dependent. On the AS/400, for example, any Java batch program ( one not running in an interactive

Page 137: Jdbc Faq From Jguru

subsystem ) sends System out and err to a spooled file ( queued printer output ). Therefore, if one wants to be portable, it might be best to redirect these streams to standard files.

Comments and alternative answers

See Java console output from sqlplus Author: Thomas Risberg (http://www.jguru.com/guru/viewbio.jsp?EID=455776), Jul 16, 2001

If you execute your stored procedure from sqlplus, then you can run the following commands before you call the procedure, and you should see the output from within sqlplus.

set serveroutput oncall dbms_java.set_output(2000);

I need to have result set on a page where the user can sort on the column headers. Any ideas?Location: http://www.jguru.com/faq/view.jsp?EID=448101 Created: Jun 30, 2001 Modified: 2001-06-30 20:03:18.499Author: Christopher Schultz (http://www.jguru.com/guru/viewbio.jsp?EID=138382) Question originally posed by Vasu S (http://www.jguru.com/guru/viewbio.jsp?EID=422150

One possibility: Have an optional field in your form or GET url called (appropriately) ORDER with a default value of either "no order" or whatever you want your default ordering to be (i.e. timestamp, username, whatever).

When you get your request, see what the value of the ORDER element is. If it's null or blank, use the default.

Use that value to build your SQL query, and display the results to the page.

If you're caching data in your servlet, you can use the Collection framework to sort your data (see java.util.Collections) if you can get it into a List format. Then, you can create a Collator which can impose a total ordering on your results.

Comments and alternative answers

I need to have result set on a page where the user can sort on the column headers. Any ideas? -Solution Author: Poornima Singh (http://www.jguru.com/guru/viewbio.jsp?EID=555639), Nov 21, 2001I had done the very same thing a couple of weeks back. i had a jsp page which was display the result set and i had to sort by the column header. I had the sql query built in the jsp page on which the selection crietria was done. Here I set the session variable.

Page 138: Jdbc Faq From Jguru

session.setAttribute("ssql",sql); The column Names, had a "href link" with the same request parameter ,but equaled to different Ints and checked the values in the jsp page in a switch case stmt.switch(nsortby) { case 1: { orderby=" order by cum "; break;} case 2: { orderby=" order by ctitle ";break;} case 3: { orderby=" order by cnames ";break;} }Some like this and then , add this string to the SQl string which is in the session with is retirved by,sessSQL=(String)session.getAttribute("ssql");And excute it as ususal.It really worked cool with me.All the best !

Sort on the Column headers Author: Murtuza Bohri (http://www.jguru.com/guru/viewbio.jsp?EID=1162092), Apr 13, 2004I had same requirement I used XML Islanding. Result was converted to XML and applied XSL on client side for sorting any particular row.

What's the best way, in terms of performance, to do multiple insert/update statements, a PreparedStatement or Batch Updates?Location: http://www.jguru.com/faq/view.jsp?EID=448102 Created: Jun 30, 2001 Author: Aron Tunzi (http://www.jguru.com/guru/viewbio.jsp?EID=446077) Question originally posed by Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.

A CallableStatement object provides a way to call stored procedures in a standard manner for all DBMSes. Their execution can be faster than that of PreparedStatement object.

Batch updates are used when you want to execute multiple statements together. Actually, there is no conflict here. While it depends on the driver/DBMS engine as to whether or not you will get an actual performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() method.

See section 3.4.1 Using Statement Objects for Batch Updates in the Advanced Tutorial for more information.

Comments and alternative answers

Faster PreparedStatement - Not true, rather slower than normal Statements. Author: Narendra Harnwal (http://www.jguru.com/guru/viewbio.jsp?EID=39423),

Page 139: Jdbc Faq From Jguru

Jan 29, 2003The claim always made "PreparedStatement are faster than normal Statement" is not true. I have seens PreparedStatement working really slow. No one seems to wear the responsibility as it was always said the implementation is in database vendors’ hand. Here I have further few questions- 1) How to make the best judgment when to use PreparedStatement or normal Statement in practical programming? 2) What are the drawbacks of PreparedStatement documented somewhere or in practical programming experience? Thanks, naren

Why does the JDBC specification recommend using getDouble() for SQL FLOAT types?Location: http://www.jguru.com/faq/view.jsp?EID=448108 Created: Jun 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

For the full answer, see the JDBC(tm) Technology Guide: Getting Started, Section 8.3.10: FLOAT. Briefly, "in practice all the major databases supporting FLOAT support a mantissa precision of at least 15 digits." That is, the equivalent of a Java double.

Why do I sometimes get the error "ODBC Driver Manager ...function Sequence Error"?Location: http://www.jguru.com/faq/view.jsp?EID=455201 Created: Jul 15, 2001 Author: Pramod Vuppalapanchu (http://www.jguru.com/guru/viewbio.jsp?EID=453652) Question originally posed by Hema latha (http://www.jguru.com/guru/viewbio.jsp?EID=405076

We had the same problem and we found that

1)SUN has reported that this Function Sequence error is a bug in JDK 1.2 Check out Sun's BUG List for more info on this.

2) If you are using JDK 1.2 try switching to JDK 1.3. It helped us.

Cheers, Pramod.

Comments and alternative answers

Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around Author: Darrell Teague (http://www.jguru.com/guru/viewbio.jsp?EID=517558), Oct 11, 2001We ran into this same problem with the same symptoms (i.e. random Function Sequence Errors). As ugly as this is, it is possibly the only sure-fire work-around if you cannot change your JRE (such as when integrating with another company's product that ships with and will not change their JRE from 1.2.3. to 1.3.x):

Page 140: Jdbc Faq From Jguru

Close the statement and re-create it between each call:

myStatement.close();myStatement = myConnection.createStatement();

This is ugly and incurs a performance hit (though not as bad as recycling the connection object) but it does work (at least in our case). Hope this helps.

Darrell Teague Architect Canopy International

Re: Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around Author: Rahul Pawar (http://www.jguru.com/guru/viewbio.jsp?EID=520149), Oct 14, 2001Hi Darrell,The work around you have suggested is not quite working for me. Instead of Statement object we are using the CallableStatement object in combi with stored procedures of MS SQL Server. I m doing exactly as suggested by you but then its not working. Pls try to delve into the problem.

Thanks, Rahul

Re: Re: Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around Author: Darrell Teague (http://www.jguru.com/guru/viewbio.jsp?EID=517558), Oct 15, 2001Yours sounds like a slightly different situation (CallableStatement Interface and stored procedures on MS SQLServer). However, if you will post a code snippet with all of the relavent pieces (creation of the CallableStatement, stored procedure execution calls, creation of ResultSets, closing of ResultSets, closing of Statement, etc), I (and perhaps others) will be glad to take a look at it.

Re: Re: Re: Sun JDBC-ODBC Bridge (JRE 1.2.2) Bug work-around Author: Rahul Pawar (http://www.jguru.com/guru/viewbio.jsp?EID=520149), Oct 15, 2001

Hi, Thanks for the prompt reply. The code snippet follows:

JavaBean code //get connection obj into mxConn var

Page 141: Jdbc Faq From Jguru

cs = mxConn.prepareCall("{call xt_someStoredProc(?)}"); cs.setInt(1,pk_activity); rs = cs.executeQuery(); while (rs.next()) { //do something; } rs.close(); cs.close(); //close connection in the finally block

The error occurs even for a simple select query when the functionality is used simultaneously by many users. Declaring the cs & rs obj at class or function level made no difference My mail adddress is [email protected]. Pls mail if you require more info.

Thanks

How can I generate an output in CSV format from a database query?Location: http://www.jguru.com/faq/view.jsp?EID=455207 Created: Jul 15, 2001 Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985) Question originally posed by Ritu kumar (http://www.jguru.com/guru/viewbio.jsp?EID=314981

CSV stands for "Comma Separated Values", so just keep any record and separe each field with a comma and each record with a newline ('\n'). You'll have a perfect CSV file, easy readable by any program supporting this simple format.

It's very common to put as first line the names of fields.

Comments and alternative answers

There are libraries to help Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685), Jan 28, 2002Comma Separated Values (CSV) in Java is an available library to help. It supports reading and writing the files.

Re: There are libraries to help Author: Namita Prakash (http://www.jguru.com/guru/viewbio.jsp?EID=1024031), Nov 11, 2002Hi, I need to convert MS Access files into CSV format.i cannot use the export function of MS Access coz it will require me to manually export a lot of files.how do i do it using JDBC-ODBC bridge. thaanks, namita

Re[2]: There are libraries to help Author: Richard Rodger (http://www.jguru.com/guru/viewbio.jsp?

Page 142: Jdbc Faq From Jguru

EID=1220174), Jan 7, 2005Use the ODBC Data Sources administration applet to define a DSN (data source name) for the CSV file. More details here: http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/bridge.doc.html

When I intersperse table creation or other DDL statements with DML statements, I have a problem with a transaction being commited before I want it to be. Everything ( commit and rollback ) works fine as long as I don't create another table. How can I resolve the issue?Location: http://www.jguru.com/faq/view.jsp?EID=455530 Created: Jul 16, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Clint Frederickson (http://www.jguru.com/guru/viewbio.jsp?EID=427806

While the questioner found a partially workable method for his particular DBMS, as mentioned in the section on transactions in my JDBC 2.0 Fundamentals Short Course:

DDL statements in a transaction may be ignored or may cause a commit to occur. The behavior is DBMS dependent and can be discovered by use of DatabaseMetaData.dataDefinitionCausesTransactionCommit() and DatabaseMetaData.dataDefinitionIgnoredInTransactions(). One way to avoid unexpected results is to separate DML and DDL transactions.

The only generally effective way to "rollback" table creation is to delete the table.

Is there a JDO FAQ available?Location: http://www.jguru.com/faq/view.jsp?EID=460343 Created: Jul 23, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

The closest thing to a JDO FAQ is the Transparent Persistence FAQ available with Forte.

What is the relationship between JDO and JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=460344 Created: Jul 23, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

Sun answers this question in their JDBC FAQ: Relationship of JDO and Java 2 Platform, Enterprise Edition APIs.

Where can I learn about Java Data Objects?Location: http://www.jguru.com/faq/view.jsp?EID=460407 Created: Jul 23, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

Page 143: Jdbc Faq From Jguru

The home of JDO is off the beaten path at Sun. You can find its home at http://access1.sun.com/jdo/.Comments and alternative answers

look for JDOs Author: shivaram madala (http://www.jguru.com/guru/viewbio.jsp?EID=200181), Jul 24, 2001hi, U can also get info from http://www.sun.com/forte/ffj/resources/articles/transparent.html

regards. shivaram.

What is JDO?Location: http://www.jguru.com/faq/view.jsp?EID=460410 Created: Jul 23, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

JDO provides for the transparent persistence of data in a data store agnostic manner, supporting object, hierarchical, as well as relational stores.

What is the difference between setMaxRows(int) and SetFetchSize(int)? Can either reduce processing time?Location: http://www.jguru.com/faq/view.jsp?EID=462124 Created: Jul 25, 2001 Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by salman zada (http://www.jguru.com/guru/viewbio.jsp?EID=419950

setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.

setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit.

Since we're talking about interfaces, be careful because the implementation of drivers is often different from database to database and, in some cases, may not be implemented or have a null implementation. Always refer to the driver documentation.

Comments and alternative answers

Page 144: Jdbc Faq From Jguru

setmaxrow, setfetchsize Author: max laenzlinger (http://www.jguru.com/guru/viewbio.jsp?EID=429148), Jul 25, 2001i am using mmmysql driver for mysql-database. setfetchsize has unfort. no effect in this driver (seems to be just dummy implementation), but astonishing setmaxrows helped me and speeded up my getnext calls; play with different values. depends on driver+database...

How can I tell if my JDBC driver normalizes java.sql.Date and java.sql.Time objects?Location: http://www.jguru.com/faq/view.jsp?EID=462998 Created: Jul 26, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

To actually determine the values, the objects must be converted to a java.util.Date and examined. See What does normalization mean for java.sql.Date and java.sql.Time? for the definition of normalization. Notice that even a debugger will not show whether these objects have been normalized, since the getXXX methods in java.sql.Date for time elements and in java.sql.Time for date elements throw an exception.

So, while a java.sql.Date may show 2001-07-26, it's normalized only if the java.util.Date value is:

Thu Jul 26 00:00:00 EDT 2001and while a java.sql.Time may show 14:01:00, it's normalized only if the java.util.Date value is: Thu Jan 01 14:01:00 EST 1970 Comments and alternative answers

A quick & dirty (but usable) solution to obtain all data from DATE fields Author: German DZ (http://www.jguru.com/guru/viewbio.jsp?EID=504469), Sep 26, 2001Resultset res;int field_num; // the ordinal number of a DATE field..// here make your query..GregorianCalendar fecha = new GregorianCalendar();GregorianCalendar hora = new GregorianCalendar();fecha.setTime(res.getDate(field_num));hora.setTime(res.getTime(field_num));fecha.add(Calendar.HOUR_OF_DAY, tm.get(Calendar.HOUR_OF_DAY));fecha.add(Calendar.MINUTE, tm.get(Calendar.MINUTE));

/*Now you have fecha with date & time data, probably you want add the seconds to, just add another fecha.add(...) sentence.*/

Page 145: Jdbc Faq From Jguru

Re: A quick & dirty (but usable) solution to obtain all data from DATE fields Author: Magne Groenhuis (http://www.jguru.com/guru/viewbio.jsp?EID=516289), Oct 10, 2001In the example above:replace tm with hora

What's the difference between MySQL and mSQL?Location: http://www.jguru.com/faq/view.jsp?EID=463307 Created: Jul 26, 2001 Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

The creators of mySQL are doing a great job in maintaining in the documentation pages with all the differences between the two databases (and others, like PostgreSQL). Personally I don't think these pages are fully objective, but many of the points are often confirmed on newsgroups and mailing lists. See:

25 How MySQL Compares to Other Databases

and, with specific attention to mSQL

25.1 How MySQL Compares to mSQL

Joe Sam Shirah adds: Additional information is available at What is MySQL? and Mini SQL 2.0 General Info.

What is the most efficient method of replicating data betwen databases using JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=464253 Created: Jul 29, 2001 Author: Surendra Chauhan (http://www.jguru.com/guru/viewbio.jsp?EID=45993) Question originally posed by sharad nangia (http://www.jguru.com/guru/viewbio.jsp?EID=82063

Within Java, the most efficient method would be, opening connections using the JDBC and inserting or updating the records from one database to the other database, but it depends upon the databases being replicated. If you are using Oracle databases, it has standard methods for replication, and you do not need the JDBC for the replication. Use snapshots like updateable and read-only.

There are different kind of replication. Let us consider the most widely used ones:

A) One Master - One slave

I) If there is not a significant difference between the structure of the database tables, the following method would be useful.

Page 146: Jdbc Faq From Jguru

FromDatabase=A; ToDatabase=B

1) Open JDBC connections between the databases A and B.

2) Read a record (RA ) from A using an SQL query.

3) Store the values in the local variables in the Java program.

4) Insert the record in B if PK does not exist for the record RA in B.

5) If the PK exists in B, update the record in B.

6) Repeat the steps 2-5 'til all the records are read by the query.

7) If there are multiple tables to be replicated, repeat steps 2-7 using the different queries.

II)If there is significant difference between the structure of the database tables, the following method would be useful.

FromDatabase=A; ToDatabase=B

1) Open the JDBC connections to the databases A.

2) Read a record ( RA ) from A using an SQL query.

3) Write the output to an XML file-XMLA, according to the DTD for the records for the database A structure.

4) Repeat steps 2 & 3 'til all the records are written to XMLA.

5) If there are more queries, repeat steps repeat steps from 2-4 and write the records to the different entities in the XML file.

6) Transform the XMLA file using the XSL and XSLT to the format useful for the database B and write to the XML file-XMLB.

7) Open the second JDBC connection to the Database B.

8) Read the XMLB file, one record at a time.

9) Insert the record in B if PK does not exist for the record RA in B.

10) If the PK exists in B, update the record in B.

B) One Master - Multiple slaves

The difference here is to open multiple JDBC connections to write to the different databases one record at a time.

C) Multiple Masters:

Page 147: Jdbc Faq From Jguru

For multiple masters, use timestamps to compare the times of the records to find out which is the latest record when a record is found in all the master databases. Alternatively, create a column to store the time and date a record is inserted or updated. When records are deleted, record the event in a log file along with the PK.

Joe Sam Shirah adds: Prepared statements and batch updates should be used wherever possible in this scenario. Also see responses by Suresh Rangan and Ivo Limmen for other views.

Can I get information about a ResultSet's associated Statement and Connection in a method without having or adding specific arguments for the Statement and Connection?Location: http://www.jguru.com/faq/view.jsp?EID=477499 Created: Aug 15, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Yes. Use ResultSet.getStatement(). From the resulting Statement you can use Statement.getConnection().Comments and alternative answers

About Statement.getConnection() Author: Erki Suurjaak (http://www.jguru.com/guru/viewbio.jsp?EID=501734), Sep 22, 2001You should keep in mind that Statement.getConnection() is not guaranteed to work. For example the JDBC driver org.gjt.mm.mysql.Driver (for MySQL) throws an AbstractMethodError.

What is pessimistic concurrency?Location: http://www.jguru.com/faq/view.jsp?EID=479241 Created: Aug 18, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

With a pessimistic approach, locks are used to ensure that no users, other than the one who holds the lock, can update data. It's generally explained that the term pessimistic is used because the expectation is that many users will try to update the same data, so one is pessimistic that an update will be able to complete properly. Locks may be acquired, depending on the DBMS vendor, automatically via the selected Isolation Level. Some vendors also implement 'Select... for Update', which explicitly acquires a lock.

What is optimistic concurrency?Location: http://www.jguru.com/faq/view.jsp?EID=479242 Created: Aug 18, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

An optimistic approach dispenses with locks ( except during the actual update ) and usually involves comparison of timestamps, or generations of data to ensure that data hasn't changed between access and update times. It's generally explained that the term optimistic is used because the expectation is that a clash between multiple updates to the same data will seldom occur.Comments and alternative answers

Page 148: Jdbc Faq From Jguru

Mimer-SQL is using OCC. Author: Peter Karlsson (http://www.jguru.com/guru/viewbio.jsp?EID=546511), Jan 25, 2002Se more at http://developer.mimer.com/features/feature_15.tml.

Why should I consider optimistic versus pessimistic approaches to database updates?Location: http://www.jguru.com/faq/view.jsp?EID=479243 Created: Aug 18, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

In a modern database, possibly the two most important issues are data integrity and concurrency ( multiple users have access to and can update the data ). Either approach can be appropriate, depending on the application, but it is important to be aware of possible consequences to avoid being blindsided.

A pessimistic approach, with locks, is usually seen as good for data integrity, although it can be bad for concurrency, especially the longer a lock is held. In particular, it guarantees against 'lost updates' - defined as an update performed by one process between the time of access and update by another process, which overwrites the interim update. However, other users are blocked from updating the data and possibly reading it as well if the read access also tries to acquire a lock. A notorious problem can arise when a user accesses data for update and then doesn't act on it for a period of time. Another situation that occurred with one of my clients is that a batch ( non-interactive ) process may need to update data while an interactive user has an update lock on the same data. In that case, data integrity goes out the window and, depending on how the application is written, more problems may be introduced. ( No, we did not write the interactive update program and yes, we had recovery procedures in place. )

An optimstic approach can alleviate lock concurrency problems, but requires more code and care for integrity. The "optimistic" definition usually says that expectations of update clashes are rare, but I view them as normal occurrances in a heavily used database. The basics are that any changes between time of access and time of update must be detected and taken into account. This is often done by comparing timestamps, but one must be sure that the timestamp is always changed for an update and, of course, that the table contains a timestamp column. A more involved, but more complete method involves saving the original columns and using them in the 'Where' clause of the Update statement. If the update fails, the data has changed and the latest data should be reaccessed.

When an SQL select statement doesn't return any rows, is an SQLException thrown?Location: http://www.jguru.com/faq/view.jsp?EID=480231 Created: Aug 20, 2001 Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955) Question originally posed by ming lee (http://www.jguru.com/guru/viewbio.jsp?EID=480124

No. If you want to throw an exception, you could wrap your SQL related code in a custom class and throw something like ObjectNotFoundException when the returned ResultSet is empty.

Page 149: Jdbc Faq From Jguru

Joe Sam Shirah adds:

A ResultSet can validly contain zero, one or many rows. For a related question and additional information see Why does my "if(rs==null)" condition always evaluate to false after executing a query?.

Are the code examples from the JDBC API Tutorial and Reference, Second Edition available online?Location: http://www.jguru.com/faq/view.jsp?EID=480723 Created: Aug 21, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Yes. The code examples for both the first and second editions of the closest thing to a JDBC bible can be downloaded from JDBC Data Access API BOOK CODE SAMPLES.

Which Java and java.sql data types map to my specific database types?Location: http://www.jguru.com/faq/view.jsp?EID=480892 Created: Aug 21, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

JDBC is, of necessity, reliant on the driver and underlying DBMS. These do not always adhere to standards as closely as we would like, including differing names for standard Java types. To deal with this, first, there are a number of tables available in the JDK JDBC documentation dealing with types. See How do I map database specific ( non-standard ) types to JDBC types? for more information.

You can also ask the driver and DBMS for this information programmatically, which should be the final word. See How do I extract SQL table column type information? and the examples TypeInfo.java, DataType.java and CreateNewTable.java in the JDBC API Tutorial and Reference, Second Edition. ( For download information, see Are the code examples from the JDBC API Tutorial and Reference, Second Edition available online?. ) These examples deal generically with the DatabaseMetaData.getTypeInfo method. Some of this information, like column type and DBMS specific type name, is also available from ResultSetMetaData for specific columns.

Additionally, with JDBC 2.0 drivers that support the method ( not all do ), ResultSetMetaData also has a getColumnClassName method available.

Does the database server have to be running Java or have Java support in order for my remote JDBC client app to access the database?Location: http://www.jguru.com/faq/view.jsp?EID=482649 Created: Aug 23, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The answer should always be no. The two critical requirements are LAN/internet connectivity and an appropriate JDBC driver. Connectivity is usually via TCP/IP, but other communication protocols are possible. Unspoken, but assumed here is that the DBMS has been started to listen on a communications port. It is the JDBC driver's job to convert the SQL statements and JDBC calls to the DBMS' native protocol. From the server's point of view, it's just another data request coming into the port, the programming language used to send the data is irrelevant at that point.

Page 150: Jdbc Faq From Jguru

What is a JDBC 2.0 DataSource?Location: http://www.jguru.com/faq/view.jsp?EID=483837 Created: Aug 25, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The DataSource class was introduced in the JDBC 2.0 Optional Package as an easier, more generic means of obtaining a Connection. The actual driver providing services is defined to the DataSource outside the application ( Of course, a production quality app can and should provide this information outside the app anyway, usually with properties files or ResourceBundles ). The documentation expresses the view that DataSource will replace the common DriverManager method.

Some downsides are: 1) Vendor specific set up tools must be used, with no particular standards specified. To quote from the source: "Now he ( the developer - JS ) needs to have his system administrator, SoLan, deploy the DataSource objects so that he... can start using them". 2) JNDI must be used to implement a lookup for the DataSource.

What types of DataSource objects are specified in the Optional Package?Location: http://www.jguru.com/faq/view.jsp?EID=483838 Created: Aug 25, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Basic - Provides a standard Connection object. Pooled - Provides a Connection pool and returns a Connection that is

controlled by the pool. Distributed - Provides a Connection that can participate in distributed

transactions ( more than one DBMS is involved). It is anticipated, but not enforced, that a distributed DataSource will also provide pooling.

However, there are no standard methods available in the DataSource class to determine if one has obtained a pooled and/or distributed Connection.

What is the significance of DataBaseMetaData.tableIndexStatistics? How to obtain and use it? Location: http://www.jguru.com/faq/view.jsp?EID=505862 Created: Sep 27, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Subramanian Umasankar (http://www.jguru.com/guru/viewbio.jsp?EID=489555

To answer the second question first, the tableIndexStatistic constant in the TYPE column will identify one of the rows in the ResultSet returned when DatabaseMetaData.getIndexInfo() is invoked. If you analyze the wordy API, a tableIndexStatistic row will contain the number of rows in the table in the CARDINALITY column and the number of pages used for the table in the PAGES column.

What is DML? Location: http://www.jguru.com/faq/view.jsp?EID=506544 Created: Sep 28, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

Page 151: Jdbc Faq From Jguru

DML is an abbreviation for Data Manipulation Language. This portion of the SQL standard is concerned with manipulating the data in a database as opposed to the structure of a database. The core verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.

What is DDL? Location: http://www.jguru.com/faq/view.jsp?EID=506546 Created: Sep 28, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

DDL is an abbreviation for Data Definition Language. This portion of the SQL standard is concerned with the creation, deletion and modification of database objects like tables, indexes and views. The core verbs for DDL are CREATE, ALTER and DROP. While most DBMS engines allow DDL to be used dynamically ( and available to JDBC ), it is often not supported in transactions. See When I intersperse table creation or other DDL statements with DML statements, I have a problem with a transaction being commited before I want it to be for more information.

Does anyone know of a JDBC driver for SQL Server 2000 that supports Windows Authentication?

Meaning a username and password does not need to be supplied when connecting to the database. Location: http://www.jguru.com/faq/view.jsp?EID=506614 Created: Sep 28, 2001 Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483) Question originally posed by James Davies (http://www.jguru.com/guru/viewbio.jsp?EID=494792

TWFreeTDS from ThinWeb is a free type 4 JDBC driver that uses the TDS protocol and can be used with SQL 7.0 and 2000.

Microsoft will release a beta JDBC driver for use with SQL 2000. The original driver is not from Microsoft but bought from Merant. The press release was issued on September 25, 2001.

For other possible drivers, see: Where can I find a comprehensive list of JDBC drivers, including the databases they support?.

Comments and alternative answers

That doesn't answer the question Author: Justin Hart (http://www.jguru.com/guru/viewbio.jsp?EID=1129920), Nov 24, 2003The question was whether or not there was a driver that supports windows authentication, IE, using a windows username and password rather than one that has been added to the database for sql authentication.

The answer is yes, but they're all commercial (with 1 open source one in development).

Page 152: Jdbc Faq From Jguru

I'm looking for a mature, fully developed, reasonably priced one myself. Most of the drivers out there that accomplish this goal are, to say the least, unreasonably priced.

Re: That doesn't answer the question Author: Martin Greenaway (http://www.jguru.com/guru/viewbio.jsp?EID=1213852), Nov 30, 2004

This may be too late to help you guys, but there are two that I know of:

jTDS is an open source driver that supports Windows Authentication (at least in v0.9), although it only supports SQL Server and Sybase RDBMS (may be enough for your needs). Apparently it's quite fast (I haven't tested it yet).

DataDirect Connect is a commercial driver which also supports Windows Authentication, but supports a wider range of RDBMS aside from SQL Server.

Hope this helps.

Martin

Can I use JDBC to execute non-standard features that my DBMS provides?Location: http://www.jguru.com/faq/view.jsp?EID=507039 Created: Sep 29, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

The answer is a qualified yes. As discussed under SQL Conformance: "One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS driver. This means that an application is free to use as much SQL functionality as desired, but it runs the risk of receiving an error on some DBMSs. In fact, an application query may be something other than SQL, or it may be a specialized derivative of SQL designed for specific DBMSs (for document or image queries, for example)."

Clearly this means either giving up portability or checking the DBMS curently used before invoking specific operations.

How can I get information about foreign keys used in a table? Location: http://www.jguru.com/faq/view.jsp?EID=507043 Created: Sep 29, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question

Page 153: Jdbc Faq From Jguru

originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign key columns, tables, sequence and update and delete rules. For sample code, look at ForeignKeysCoffees.java in the download from Are the code examples from the JDBC API Tutorial and Reference, Second Edition available online?

How can I determine where a given table is referenced via foreign keys? Location: http://www.jguru.com/faq/view.jsp?EID=507045 Created: Sep 29, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

DatabaseMetaData.getExportedKeys() returns a ResultSet with data similar to that returned by DatabaseMetaData.getImportedKeys(), except that the information relates to other tables that reference the given table as a foreign key container. In other words, what tables have foreign keys that reference this table?

Is there a standard JDBC means of creating a database? Location: http://www.jguru.com/faq/view.jsp?EID=507066 Created: Sep 29, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Joe Sam Shirah PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=42100

No, because there is no SQL standard method. The basis is mostly historical, because almost every DBMS uses a different syntax and arguments and often requires special permissions. In my JDBC 2.0 Fundamentals Short Course, for example, the Cloudscape database was created with a JDBC driver URL attribute, while DB2 on NT used CREATE DATABASE and AS/400 DB2 used CREATE COLLECTION.

If you want to use a DBMS specific means and are willing to account for ( or trade off ) portability, it is potentially possible to achieve it with JDBC. See: Can I use JDBC to execute non-standard features that my DBMS provides?

What is the JDBC syntax for using a date literal or variable in a standard Statement?Location: http://www.jguru.com/faq/view.jsp?EID=507218 Created: Sep 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Vipin Mathew (http://www.jguru.com/guru/viewbio.jsp?EID=507095

While you are generally advised to use a PreparedStatement and let the driver handle the syntax, the following is the standard form for regular Statements. The general escape syntax for standard SQL date columns is:

{d 'yyyy-mm-dd'}

For literals:

Page 154: Jdbc Faq From Jguru

String sSQL = "SELECT colName FROM aTable " +"WHERE colDate = {d '2001-10-21'}"

For variables ( note that toString() is implicitly called on the date variable ):

java.sql.Date jsqlDate;... // set dateString sSQL = "SELECT colName FROM aTable " +"WHERE colDate = {d '" + jsqlDate + "'}"

What are the considerations for deciding on transaction boundaries? Location: http://www.jguru.com/faq/view.jsp?EID=507220 Created: Sep 30, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Vinod Kaggal (http://www.jguru.com/guru/viewbio.jsp?EID=112370

Transaction processing should always deal with more than one statement and a transaction is often described as a Logical Unit of Work ( LUW ). The rationale for transactions is that you want to know definitively that all or none of the LUW completed successfully. Note that this automatically gives you restart capability. Typically, there are two conditions under which you would want to use transactions:

Multiple statements involving a single file - An example would be inserting all of a group of rows or all price updates for a given date. You want all of these to take effect at the same time; inserting or changing some subset is not acceptable.

Multiple statements involving multiple files - The classic example is transferring money from one account to another or double entry accounting; you don't want the debit to succeed and the credit to fail because money or important records will be lost. Another example is a master/detail relationship, where, say, the master contains a total column. If the entire LUW, writing the detail row and updating the master row, is not completed successfully, you A) want to know that the transaction was unsuccessful and B) that a portion of the transaction was not lost or dangling.

Therefore, determining what completes the transaction or LUW should be the deciding factor for transaction boundaries.

How does one get column names for rows returned in a ResultSet? Location: http://www.jguru.com/faq/view.jsp?EID=524526 Created: Oct 18, 2001 Modified: 2002-03-23 22:59:11.612Author: Jason Stell (http://www.jguru.com/guru/viewbio.jsp?EID=50780) Question originally posed by Maxim Markaitis (http://www.jguru.com/guru/viewbio.jsp?EID=521563

ResultSet rs = ......ResultSetMetaData rsmd = rs.getMetaData();int numCols = rsmd.getColumnCount();

for (int i = 1; i <= numCols; i++)

Page 155: Jdbc Faq From Jguru

{ System.out.println("[" + i + "]" + rsmd.getColumnName(i) + " {" + rsmd.getColumnTypeName(i) + "}");}Comments and alternative answers

i < numCols+1 Author: Maxim Markaitis (http://www.jguru.com/guru/viewbio.jsp?EID=521563), Nov 9, 2001.

Column count off by 1 Author: Corellian Trader (http://www.jguru.com/guru/viewbio.jsp?EID=774641), Feb 27, 2002

Because the Number of Columns use 1 to N numbering, instead of are 0 to n, Need to change the for statement to:

(int i = 1; i <= numCols; i++)

i.e. Make "i <= numCols" instead of "i < numCols"

Otherwise, the last column is dropped.

Correction Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100), Mar 23, 2002Thanks to both responders, the code has been corrected.

I have an application that queries a database and retreives the results into a JTable. This is the code in the model that seems to be taken forever to execute, especially for a large result set:

while ( myRs.next() ) { Vector newRow =new Vector();

for ( int i=1;i<=numOfCols;i++ ) { newRow.addElement(myRs.getObject(i)); } allRows.addElement(newRow);}fireTableChanged(null);newRow stores each row of the resultset and allRows stores all the rows. Are the vectors here the problem?

Page 156: Jdbc Faq From Jguru

Is there another way of dealing with the result set that could execute faster? Location: http://www.jguru.com/faq/view.jsp?EID=524658 Created: Oct 18, 2001 Author: Dermot Hennessy (http://www.jguru.com/guru/viewbio.jsp?EID=390903) Question originally posed by Jeffrey Mutonho (http://www.jguru.com/guru/viewbio.jsp?EID=513649

A couple of points for you:

java.util.Vector is largely thread safe, which means that there is a greater overhead in calling addElement() as it is a synchronized method. If your result set is very large, and threading is not an issue, you could use one of the thread-unsafe collections in Java 2 to save some time. java.util.ArrayList is the likeliest candidate here.

Do not use a DefaultTableModel as it loads all of your data into memory at once, which will obviously cause a large overhead - instead, use an AbstractTableModel and provide an implementation which only loads data on demand, i.e. when (if) the user scrolls down through the table.

Joe Sam Shirah adds: For another view on the best collection class, see Which is the preferred collection class to use for storing database result sets? Either way, Dermot's point on speed issues with Vectors is certainly valid.

Comments and alternative answers

Performace Tips Author: Chantal Ackermann (http://www.jguru.com/guru/viewbio.jsp?EID=88569), Oct 22, 2001I've just visited a site about jdbc performance tips: http://www.as400.ibm.com/developer/java/topics/jdbctips.html One thing they mention is, that the method getObject() is slower than the methods that specify the type of the retrieved data. Another hint for the table model comes from this place: http://java.sun.com/products/jfc/tsc/articles/javaOne2001/1339/index.html It says that the table model works fastest based on a hash table where the key is of class Point, using the parameters to specify the column and the row, and the value is the value in the cell specified by this Point. Chantal

What is the JDBC equivalent of "ODBC Data Source Administrator" ODBC Data Source Administartor facilitates for selecting a driver and setting up all data source specific attributes to establish a connection to the data store(DSN). To incorporate such a functionality in my software, is there any counterpart which I can use for JDBC drivers? Location: http://www.jguru.com/faq/view.jsp?EID=524668 Created: Oct 18, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question

Page 157: Jdbc Faq From Jguru

originally posed by Suresh Babu (http://www.jguru.com/guru/viewbio.jsp?EID=512486

There is not a JDBC specific equivalent, but the Java way, typically, is to use properties files or ResourceBundles. For an example, see Generalizing Connection Information--Batch in my JDBC 2.0 Fundamentals course.

How can I execute multiple select queries with a single executeQuery()? I just read the article in JavaWorld "JDBC usage for industrial-strength performance, Part 2". But when I ran the code I am getting an Oracle Exception complaining about an invalid character. I just separted my individual queries by semicolon and executed it.Location: http://www.jguru.com/faq/view.jsp?EID=524691 Created: Oct 18, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by sathish kumar (http://www.jguru.com/guru/viewbio.jsp?EID=513558

Different DBMS engines use different statement terminators. The usual advice is to use none at all and let the driver handle it. Unless the driver is smart enough to figure out where each statement begins and ends, in this case you really can't do that. Unfortunately, there doesn't seem to be a method in the driver or metadata classes to get the DBMS specific terminator used. So, this area doesn't appear to be very portable. If you are certain that there actually is nothing invalid in your statements, the other possibility is that your driver just won't handle this properly, so the last step is to check with your DBMS's technical support.Comments and alternative answers

A solution for Oracle calls: Author: Jason Stell (http://www.jguru.com/guru/viewbio.jsp?EID=50780), Oct 19, 2001Given tables "tbl_a" and "tbl_b": Connection conx = ... CallableStatement call = conx.prepareCall ("begin open ? for select * from tbl_a; open ? for select * from tbl_b; end;");call.registerOutParam (1, oracle.jdbc.driver.OracleTypes.CURSOR);call.registerOutParam (2, oracle.jdbc.driver.OracleTypes.CURSOR);call.execute ();ResultSet rs1 = (ResultSet)call.getObject (1);ResultSet rs2 = (ResultSet)call.getObject (2);while (rs1.next ()){ ...}

while (rs2.next ()){ ...}

Re: A solution for Oracle calls:

Page 158: Jdbc Faq From Jguru

Author: Michael Sabitov (http://www.jguru.com/guru/viewbio.jsp?EID=822163), Apr 4, 2002This solution gives forward only ResultSet objects. Is there any way to get scrollable ResultSets?

I'm using the Oracle thin driver to update a batch of records using a prepared statement, addBatch() and executeBatch(). All of the updates go through fine and the data is updated correctly, but all of the updateCounts returned are "-2". I haven't been able to find any documentation for the thin driver, so I don't know if this return code is something I should be worried about, or if I should just ignore it. Location: http://www.jguru.com/faq/view.jsp?EID=525335 Created: Oct 19, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Tim Duggan (http://www.jguru.com/guru/viewbio.jsp?EID=506387

From the JDK 1.3 Statement.executeBatch() API documentation: "A value of -2 -- indicates that the command was processed successfully but that the number of rows affected is unknown." See the documentation and Batch Update Facility for more information.

I have a Stored procedure, which consists of the following:

1. Creating a Temp Table 2. Inserting Records to that 3. Do some more modifications.. 4. Creating Cursors 5. Some Select Statements...

Moreover, my pocedure has a output parameter.

I try to execute this procedure through CallableStatement, then I execute by calling the execute() method. When I process this using getMoreResults() & I am getting only update count, not my output parameter. Location: http://www.jguru.com/faq/view.jsp?EID=525440 Created: Oct 19, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Kesavan Srinivasan PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=35037

Although you are always dependent on your driver capabilities, JDBC does provide a means of handling this sort of situation. execute() returns a boolean - true if the rusult is a ResultSet, false if an int is returned ( for update count or DDL ). From the API documentation: "The methods execute, getMoreResults, getResultSet, and getUpdateCount let you navigate through multiple results. The execute method executes an SQL statement and indicates the form of the first result. You can then use the methods getResultSet or getUpdateCount to retrieve the result, and getMoreResults to move to any subsequent result(s)."

Page 159: Jdbc Faq From Jguru

A more complete explanation and example code is provided in JDBC API Tutorial and Reference, 2nd Ed: Java 2 in "Statements - 40.1.8 Executing Special Kinds of Statements". Unfortunately, this particular section does not appear to be available online.

Comments and alternative answers

Stored Procedure Author: Cenan Yesiltas (http://www.jguru.com/guru/viewbio.jsp?EID=937310), Jul 3, 2002if you use the CalableStatement interface before don't use execute() method you must register the Out parameter with registerOutParameter method that the method takes parameter java.sql.Types which decides your parametertyp forexample : if your out parameter tweice par. CallableStatement statement; statement=conn.prepareCall("{call procedurename[(?,?)]}"); statement.registerOutParameter(2,java.sql.Types.FlOAT); .... . . then you use with statement.getFloat(2); your out parameter. I hope that i help you. cu

How can I write a CLOB object in weblogic using type 4 driver with Oracle? Location: http://www.jguru.com/faq/view.jsp?EID=525871 Created: Oct 20, 2001 Author: Denis Navarre (http://www.jguru.com/guru/viewbio.jsp?EID=495283) Question originally posed by Atam Govil (http://www.jguru.com/guru/viewbio.jsp?EID=89203

The following documentation from Oracle should help: Working with BLOBs and CLOBs

Also see Clob Updating.

Why can't Tomcat find my Oracle JDBC drivers in classes111.zip? Location: http://www.jguru.com/faq/view.jsp?EID=528159 Created: Oct 23, 2001 Author: Shaik Mujibur Rahman (http://www.jguru.com/guru/viewbio.jsp?EID=510047) Question originally posed by Shaik Mujibur Rahman (http://www.jguru.com/guru/viewbio.jsp?EID=510047

TOMCAT 4.0.1 on NT4 throws the foll exception when i try to connect to Oracle DB from JSP.

javax.servlet.ServletException : oracle.jdbc.driver.OracleDriver

Root Cause : java.lang.ClassNotFoundException: oracle:jdbc:driver:OracleDriver

But, the Oracle JDBC driver ZIP file (classes111.zip)is avbl in the system classpath.

My problem was solved. I copied the Oracle Driver class file (classes111.zip) in %TOMCAT_HOME%\lib directory and renamed it to classess111.jar. It worked.

Page 160: Jdbc Faq From Jguru

Now i am able to connect to Oracle DB from TOMCAT 4.01 via Oracle JDBC-Thin Driver.

Comments and alternative answers

thanks Author: shankar ram thyagarajan (http://www.jguru.com/guru/viewbio.jsp?EID=573833), Dec 5, 2001i had the same problem with classes12.zip. as per ur suggestion, i renamed it to classes12.jar, and it works fine. thanks a lot.

Re: any other solutions please ... Author: kiran gopal (http://www.jguru.com/guru/viewbio.jsp?EID=575866), Dec 6, 2001I am also struck by a similar problem, but I am Unixware 7.1.1 with jakarta Tomcat 3.3 with Oracle 8. Even though I copied the classes111.zip to the $TOMCAT_HOME/lib directory and renamed it as classes111.jar it dint work out. Please guide with some other probabale solutions if possible.. Thanx..

Re[2]: another solution here Author: kiran gopal (http://www.jguru.com/guru/viewbio.jsp?EID=575866), Dec 6, 2001When the same classes111.jar is copied to the WEB-INF/lib directort it worx. Thanx..

Re[3]: another solution here Author: Maxima Alles (http://www.jguru.com/guru/viewbio.jsp?EID=574700), Dec 13, 2001Hi all, please help, even tgough I copied classes111.jar and classes112.jar to directory %tomcat_home%\lib and to directory WEB-INF\lib, it still doesn't weork, please guide me !!

Re[4]: another solution here Author: steve manzi (http://www.jguru.com/guru/viewbio.jsp?EID=700812), Dec 24, 2001I had the same problem. I copied classes12.zip into the WEB-INF/lib directory then renamed it classes12.jar and still had problems. My solution: I extracted the files from the classes12.zip file and created a jar file (classes12.jar) then copied this file into the WEB-INF/lib directory. Also I would suggest that you only use the drivers that you need that is classes12 or classes11.

Re[5]:another solution here Author: kiran gopal (http://www.jguru.com/guru/viewbio.jsp?EID=705733), Dec 31, 2001Another solution is that you can copy classes111.jar, classes102.jar & liboci805jdbc.so ( these files for UNIX & it may

Page 161: Jdbc Faq From Jguru

change according to the OS), can be copied to the $TOMCAT_HOME/lib/common directory.This will surely work...bye

Re: Re[5]:another solution here Author: Yinghui (Susan) Zeng (http://www.jguru.com/guru/viewbio.jsp?EID=743520), Feb 1, 2002I tried all the solutions, none worked for me. I am using windows 98. tomcat 4.0.1.

Re[2]: Re[5]:another solution here Author: Yinghui (Susan) Zeng (http://www.jguru.com/guru/viewbio.jsp?EID=743520), Feb 1, 2002Here is more information. when I startup tomcat, the message display for using classpath is Using CLASSPATH: c:\jakarta-tomcat-4.0.1\bin\bootstrap.jar;c:\J2SDK_Forte\jd k1.4.0\lib\tools.jar although, the c:\J2SDK_Forte\jd k1.4.0\lib\classes12.jar is in the system classe path, it is not displayed when startup tomcat. I also put the classes12.jar in every lib folder that I can find in tomcat home. Please help!

Re[3]: Re[5]:another solution here Author: Yinghui (Susan) Zeng (http://www.jguru.com/guru/viewbio.jsp?EID=743520), Feb 1, 2002more information: I even extract classes12.jar and put the extracted classes12 folder in myapp/web-inf/classes folder why could tomcat find my own classes in that folder but not the extracted classes12.

Re[4]: Re[5]:another solution here Author: Yinghui (Susan) Zeng (http://www.jguru.com/guru/viewbio.jsp?EID=743520), Feb 2, 2002put classes12.jar in web-inf/lib worked later! don't know why did not work before.

Re[4]: Re[5]:another solution here Author: Jingkun Zhu (http://www.jguru.com/guru/viewbio.jsp?EID=833561), Apr 10, 2002This is a so useful solution. It works!

Page 162: Jdbc Faq From Jguru

Re[3]: another solution here Author: Efren Lugo (http://www.jguru.com/guru/viewbio.jsp?EID=726052), May 16, 2002Don't place classes12.zip on any place... place it on WEBINF/lib and tomcat lib can be helpfull... remember to restart tomcat... to make changes...

Re[2]: any other solutions please ... Author: Neo Gigs (http://www.jguru.com/guru/viewbio.jsp?EID=748386), Mar 11, 2002Hi there, My problem falls on the Solaris 8 with Tomcat 3.3a and Oracle 7.3.4. As I did was copy classes111.zip and rename to classes111.jar in both %TOMCAT_HOME%\lib and %my_Application%\WEB-INF\lib and it works! TQ

Re[3]: any other solutions please ... Author: lakshmi pillay (http://www.jguru.com/guru/viewbio.jsp?EID=877918), May 16, 2002using Tomcat 3.3.1/Oracle 8 in tomcat.sh directory, locate oldCP=$CLASSPATH add CLASSPATH=${CLASSPATH}:/usr/local/jdk1.2.2/jdbc/lib/classes111.zip bingo it works (substitute the path name of classes111.zip with the correct directory).

Re[2]: any other solutions please ... Author: Pradeep Vorugu (http://www.jguru.com/guru/viewbio.jsp?EID=116392), Apr 9, 2002I think if u place that zip file in your %JAVA_HOME%\jre\lib\ext It should work.

Re: thanks Author: Jason ye (http://www.jguru.com/guru/viewbio.jsp?EID=795899), Mar 13, 2002yes. after renamed it to lasses12.jar. it works . but i getting other problem . the same jsp file . the same jdbc connection pool . in tomcat3.2 it can working fine . but in tomcat4.0 the jsp program can't get any data without any errors . why ?

Re: thanks Author: Ramadevan MadhuSudanan (http://www.jguru.com/guru/viewbio.jsp?EID=733076), Jul 20, 2002i got the problem solved.i renamed the classes12.zip to classes12.jar. it worked. thanks a lot.I had faced the same problem with my WebSphere- Oracle- JDBC.Thanks once again.

Re[2]: thanks

Page 163: Jdbc Faq From Jguru

Author: srinivasa prasad (http://www.jguru.com/guru/viewbio.jsp?EID=1170424), May 13, 2004Yes. Renaming the classes12.zip to classes12.jar works fine. after renaming just place it in the web-inf/lib folder. Dont forget to restart the tomcat.

Oracle JDBC Drivers in Tomcat 4.0.x Author: Robert Nicholls (http://www.jguru.com/guru/viewbio.jsp?EID=527915), Feb 21, 2002We have gone through all of the permutations of directories for the Oracle classes12.zip (or renamed as .jar) encountering all the problems chronicled in the various replies. The only solution we have found is to unpack the classes into $TOMCAT_HOME/classes. This behaviour seems to be confined to just the Oracle drivers. Every other *.jar works fine! There is something strange going on in the deployment.

Re: Oracle JDBC Drivers in Tomcat 4.0.x Author: william lam (http://www.jguru.com/guru/viewbio.jsp?EID=803669), Mar 19, 2002We got oracle working by doing this: rename classesXXX.zip to classesXXX.jar, put it in the tomcat/common/lib directory. Open up the jar file, and delete any javax.sql.* classes. Tomcat 4 already has the javax.sql.* classes in another jar file, and it conflicts with the onees in the oracle jar file. If you are not comfortable modifying the jar file, just put the classesXXX.jar file in the webinf/lib directory in your web app, and it should work. We needed the oracle in the common/lib directory because we were implemnting a tomcat realm that needed access to oracle for the logins/passwords.

« previous beginning next »

How can I send input to an Excel file from my Java program?Location: http://www.jguru.com/faq/view.jsp?EID=534003 Created: Oct 30, 2001 Author: surya mp (http://www.jguru.com/guru/viewbio.jsp?EID=230258) Question originally posed by bhaskar ramaraju (http://www.jguru.com/guru/viewbio.jsp?EID=30638

Here some possible solutions for your problem: It's Excel-lent and The Java-Excel solution revisited.

Joe Sam Shirah adds: Also see How can I connect to an Excel spreadsheet file using jdbc? and Where do I find information about operations on Excel, Word, text files and other non-DBMS products that can be accessed via the JDBC-ODBC Bridge?.

Is there a way to find the primary key(s) for an Access Database table? Sun's JDBC-ODBC driver does not implement the getPrimaryKeys() method for the DatabaseMetaData Objects.Location: http://www.jguru.com/faq/view.jsp?EID=534011 Created: Oct 30, 2001 Author: Percy Wong (http://www.jguru.com/guru/viewbio.jsp?EID=522735) Question

Page 164: Jdbc Faq From Jguru

originally posed by Andrew Holm-Hansen (http://www.jguru.com/guru/viewbio.jsp?EID=529043

// Use meta.getIndexInfo() will get you the PK index. Once// you know the index, retrieve its column name

DatabaseMetaData meta = con.getMetaData();

String key_colname = null;

// get the primary key informationrset = meta.getIndexInfo(null,null, table_name, true,true);while( rset.next()){ String idx = rset.getString(6); if( idx != null) { //Note: index "PrimaryKey" is Access DB specific // other db server has diff. index syntax. if( idx.equalsIgnoreCase("PrimaryKey")) { key_colname = rset.getString(9); setPrimaryKey( key_colname ); } }}Comments and alternative answers

Could you please tell me about the other db server 's index syntax especially oracle and sybase? Author: Imam Raza (http://www.jguru.com/guru/viewbio.jsp?EID=863442), May 2, 2002

Hi!Referring to your following answere:================================================== //Note: index "PrimaryKey" is Access DB specific // other db server has diff. index syntax. ====================================================Could you please tell me about the other db server 's index syntax especially oracle and sybase?Thank You Good Bye

Need to get the foreign keys as well. Author: Galib Anwar (http://www.jguru.com/guru/viewbio.jsp?EID=884053), May 19, 2002I have tried the primary key finding algorithm, its great. Now I can't help asking for a little more help. How do i find the foreign keys for MSAccess database. I tried the getCrossReference() method, but got java.sql.SQLException: [Microsoft][ODBC Driver Manager] Driver does not support this function Eagerly awaiting response.

Page 165: Jdbc Faq From Jguru

Galib

Re: Need to get the foreign keys as well. Author: Markus Brüderl (http://www.jguru.com/guru/viewbio.jsp?EID=1056881), Feb 14, 2003You can read the MSAccess System-Table. Give the user read-permission to this tables inside Access. Statement stmt = dbMeta.getConnection().createStatement();ResultSet foreignKeys = stmt.executeQuery("SELECT szRelationship, szReferencedObject, szColumn, szReferencedColumn FROM MSysRelationships WHERE szObject like '"+tableName+"'");

while (foreignKeys.next()) { String fkName = foreignKeys.getString(1);//FK_NAME // if FK has no name - make it up (use tablename instead) if (fkName == null) { fkName = foreignKeys.getString(2);//PKTABLE_NAME

} String fkey = foreignKeys.getString(3); //local column //FKCOLUMN_NAME String pkey = foreignKeys.getString(4); //foreign column //PKCOLUMN_NAME

}

How do I insert/update records with some of the columns having NULL value?Location: http://www.jguru.com/faq/view.jsp?EID=545700 Created: Nov 12, 2001 Author: Harikrishna Neerkaje (http://www.jguru.com/guru/viewbio.jsp?EID=69829) Question originally posed by Tuan Truong (http://www.jguru.com/guru/viewbio.jsp?EID=32991

Use either of the following PreparedStatement methods:

public void setNull(int parameterIndex, int sqlType) throws SQLException

public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException

Joe Sam Shirah adds: Note that these methods assume that the columns are nullable. In this case, you can also just omit the columns in an INSERT statement; they will be automatically assigned null values.

Comments and alternative answers

How do I SELECT records with some of the columns having NULL value?

Page 166: Jdbc Faq From Jguru

Author: Fernando Cardoso (http://www.jguru.com/guru/viewbio.jsp?EID=717068), Jan 11, 2002I tried this example in some DBMS (Oracle 9i/SqlServer2000/DB2/Ms-access) with no results: ps = con.prepareStatement("Select * from COUNTRY where dbisocode = ?"); ps.setNull(1,java.sql.Types.VARCHAR); What's wrong with this code? Also, i tried with numeric fields.

Re: How do I SELECT records with some of the columns having NULL value? Author: Heng Cao (http://www.jguru.com/guru/viewbio.jsp?EID=735111), Jan 25, 2002The null check should be "is", instead of "=", "=" always return false if any of its operands is null.

Re[2]: How do I SELECT records with some of the columns having NULL value? Author: Ramesh Sakala (http://www.jguru.com/guru/viewbio.jsp?EID=1102113), Jul 17, 2003isNull(index, Types.VARCHAR) should work as per JDBC spec. With Oracle thin driver, it is not working. Can someone think of any other way of doing without changing the query back to "is null" because with this solution, query has to be written based on the values being passed into preparedstatement, which is not elegant.

You can also insert null strings. Author: Artur de Sousa Rocha (http://www.jguru.com/guru/viewbio.jsp?EID=70489), Oct 9, 2002At least some JDBC drivers also allow for setString(index, null), which can make your life easier.

How to get a field's value with ResultSet.getxxx when it is a NULL? I have tried to execute a typical SQL statement:

select * from T-name where (clause);

But an error gets thrown because there are some NULL fields in the table. Location: http://www.jguru.com/faq/view.jsp?EID=545713 Created: Nov 12, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by YU CUI (http://www.jguru.com/guru/viewbio.jsp?EID=539652

You should not get an error/exception just because of null values in various columns. This sounds like a driver specific problem and you should first check the original and any chained exceptions to determine if another problem exists.

In general, one may retrieve one of three values for a column that is null, depending on the data type. For methods that return objects, null will be returned; for numerics ( get Byte(), getShort(), getInt(), getLong(), getFloat(), and getDouble() ) zero will be

Page 167: Jdbc Faq From Jguru

returned; for getBoolean() false will be returned. To find out if the value was actually NULL, use ResultSet.wasNull() before invoking another getXXX method. For more information, see the JDBC(tm) Technology Guide: Getting Started 5.1.19 NULL Result Values.

Comments and alternative answers

Same Problem Author: k strele (http://www.jguru.com/guru/viewbio.jsp?EID=937119), Jul 25, 2002I have the same troubles. When a column within a Resultset contains a null-value, there is an Exception thrown immediatly. You dont have any chance at least within the JDBC to keep it back. Has anybody any idea?

Re: Same Problem Author: Bakor Kamal (http://www.jguru.com/guru/viewbio.jsp?EID=1185215), Jul 11, 2004Me to. I have the same troubles.

How do I disallow NULL values in a table?Location: http://www.jguru.com/faq/view.jsp?EID=561331 Created: Nov 26, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Null capability is a column integrity constraint, normally aplied at table creation time. Note that some databases won't allow the constraint to be applied after table creation. Most databases allow a default value for the column as well. The following SQL statement displays the NOT NULL constraint: CREATE TABLE CoffeeTable ( Type VARCHAR(25) NOT NULL, Pounds INTEGER NOT NULL, Price NUMERIC(5, 2) NOT NULL )

I've heard that I can save space by allowing NULLs for columns where no value is supplied. Is that correct?Location: http://www.jguru.com/faq/view.jsp?EID=561332 Created: Nov 26, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

While the answer is ultimately dependent on your specific DBMS, most databases create an extra byte for every null capable column to mark whether or not it contains a null value. This clearly means that more space is used and processing time is also usually longer, since the additional byte value must be checked.

How can I overwrite blob data in an Oracle database? I want to replace the blob in the selected row with byte[] blobData using the following code:

OracleResultSet rset=null;OutputStream os=null;CallableStatement stmt=null;

Page 168: Jdbc Faq From Jguru

conn.setAutoCommit(false);stmt = conn.prepareCall("select myblob from mytable " + "where mycolumn='foobar' for update");stmt.execute();rset=(OracleResultSet)stmt.getResultSet();rset.next();BLOB bdata=rset.getBLOB("myblob");os=bdata.getBinaryOutputStream();os.write(blobData);os.flush();os.close();conn.commit();However, this only replaces the first blobData.length bytes of the blob and leaves the rest. How can I replace the entire blob with the byte[]?Location: http://www.jguru.com/faq/view.jsp?EID=564073 Created: Nov 27, 2001 Author: Bernie Acs (http://www.jguru.com/guru/viewbio.jsp?EID=540259) Question originally posed by Joe R (http://www.jguru.com/guru/viewbio.jsp?EID=535256 This behavior is exactly how the function is designed to work; to accomplish a complete replacement of the orginal data you could set the blob column to the value empty_blob() prior to inputting your new data which would do the trick, or you must use the length written to determine the point to trim out the old blob data. The first is probably the best approach and would look something like the following: OracleResultSet rset=null;OutputStream os=null;CallableStatement stmt=null;Statement stmt1 = null;

// do connection stuff and set up statements

conn.setAutoCommit(false);

stmt1.execute("update mytable set myblob = empty_blob() " + "where mycolumn='foobar'");

stmt = conn.prepareCall("select myblob from mytable " + "where mycolumn='foobar' for update");stmt.execute();rset=(OracleResultSet)stmt.getResultSet();rset.next();BLOB bdata=rset.getBLOB("myblob");os=bdata.getBinaryOutputStream();os.write(blobData);os.flush();os.close();conn.commit();Note that BLOB and CLOB columns in an Oracle database can be modified at any offset from the beginning of the data. Special care must be exercised if the intent is to replace the entire existing data body. Comments and alternative answers

BLOB privileges? Author: Marie Ricketts (http://www.jguru.com/guru/viewbio.jsp?EID=575334),

Page 169: Jdbc Faq From Jguru

Dec 6, 2001When I use the method above I get:

java.io.IOException: ORA-01031: insufficient privilegesSystem Error: ORA-06512: at "SYS.DBMS_LOB", line 700

The userid the servlet is using has the following:

GRANT INSERT,SELECT,ALTER ON blob_file_table TO USERID

Is there some other privlege that I need?

read the javadocs for oracle.sql.BLOB Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382), Jul 5, 2003First, download Oracle's latest and greatest JDBC driver from www.oracle.com When you download the driver, you should also download the javadocs for Oracle's JDBC driver.

Look at the javadocs for oracle.sql.BLOB

Instead of this:BLOB bdata=rset.getBLOB("myblob");os=bdata.getBinaryOutputStream();

You need to do this: BLOB bdata=rset.getBLOB("myblob");bdata.trim(0);os=bdata.getBinaryOutputStream();

My driver claims to support JDBC 2.0, but some methods get an unsupported exception. How can I verify that the driver will work? Location: http://www.jguru.com/faq/view.jsp?EID=564164 Created: Nov 27, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The DatabaseMetaData class has a large number of supportsXXX methods which you can use to ensure that the operation will proceed or otherwise provide a workaround. See the API documentation for detailed information.

How can I ensure that my SQL statements meet SQL standards to get maximum portability?Location: http://www.jguru.com/faq/view.jsp?EID=564466 Created: Nov 27, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

One tool to use is Mimer SQL Validator. This page links to validators for SQL-92 and SQL-99 ( SQL3 ). In addition, there is a list of SQL reserved words.

Page 170: Jdbc Faq From Jguru

DB2 Universal claims to support JDBC 2.0, But I can only get JDBC 1.0 functionality. What can I do?Location: http://www.jguru.com/faq/view.jsp?EID=564469 Created: Nov 27, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

DB2 Universal defaults to the 1.0 driver. You have to run a special program to enable the 2.0 driver and JDK support. For detailed information, see Setting the Environment in Building Java Applets and Applications. The page includes instructions for most supported platforms.

Why do I get UnsatisfiedLinkError when I try to use my JDBC driver?Location: http://www.jguru.com/faq/view.jsp?EID=565442 Created: Nov 28, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The first thing is to be sure that this does not occur when running non-JDBC apps. If so, there is a faulty JDK/JRE installation. If it happens only when using JDBC, then it's time to check the documentation that came with the driver or the driver/DBMS support. JDBC driver types 1 through 3 have some native code aspect and typically require some sort of client install. Along with the install, various environment variables and path or classpath settings must be in place. Because the requirements and installation procedures vary with the provider, there is no reasonable way to provide details here. A type 4 driver, on the other hand, is pure Java and should never exhibit this problem. The trade off is that a type 4 driver is usually slower.

Many connections from an Oracle8i pooled connection returns statement closed.

I am using import oracle.jdbc.pool.* with thin driver. If I test with many simultaneous connections, I get an SQLException that the statement is closed.Location: http://www.jguru.com/faq/view.jsp?EID=567410 Created: Nov 29, 2001 Author: Bernie Acs (http://www.jguru.com/guru/viewbio.jsp?EID=540259) Question originally posed by Steve McRoberts (http://www.jguru.com/guru/viewbio.jsp?EID=501189

Here is an example of concurrent operation of pooled connections from the OracleConnectionPoolDataSource. There is an executable for kicking off threads, a DataSource, and the workerThread.

The Executable Member

// Copyright (c) 2000package package6;

/** * package6.executableTester * * @author Me */public class executableTester { protected static myConnectionPoolDataSource dataSource = null;

Page 171: Jdbc Faq From Jguru

static int i = 0;

/** * Constructor */ public executableTester() throws java.sql.SQLException { }

/** * main * @param args */ public static void main(String[] args) {

try{ dataSource = new myConnectionPoolDataSource(); } catch ( Exception ex ){ ex.printStackTrace(); }

while ( i++ < 10 ) { try{ workerClass worker = new workerClass(); worker.setThreadNumber( i ); worker.setConnectionPoolDataSource( dataSource.getConnectionPoolDataSource() ); worker.start(); System.out.println( "Started Thread#"+i ); } catch ( Exception ex ){ ex.printStackTrace(); } } }

}The DataSource Member // Copyright (c) 2000package package6;import oracle.jdbc.pool.*;

/** * package6.myConnectionPoolDataSource. * * @author Me */public class myConnectionPoolDataSource extends Object {protected OracleConnectionPoolDataSource ocpds = null;

/** * Constructor */ public myConnectionPoolDataSource() throws java.sql.SQLException { // Create a OracleConnectionPoolDataSource instance

Page 172: Jdbc Faq From Jguru

ocpds = new OracleConnectionPoolDataSource();

// Set connection parameters ocpds.setURL("jdbc:oracle:oci8:@mydb"); ocpds.setUser("scott"); ocpds.setPassword("tiger");

}

public OracleConnectionPoolDataSource getConnectionPoolDataSource() { return ocpds; }

}The Worker Thread Member // Copyright (c) 2000package package6;import oracle.jdbc.pool.*;import java.sql.*;import javax.sql.*;

/** * package6.workerClass . * * @author Me */public class workerClass extends Thread { protected OracleConnectionPoolDataSource ocpds = null; protected PooledConnection pc = null;

protected Connection conn = null;

protected int threadNumber = 0; /** * Constructor */

public workerClass() { }

public void doWork( ) throws SQLException {

// Create a pooled connection pc = ocpds.getPooledConnection();

// Get a Logical connection conn = pc.getConnection();

// Create a Statement Statement stmt = conn.createStatement ();

// Select the ENAME column from the EMP table ResultSet rset = stmt.executeQuery ("select ename from emp");

// Iterate through the result and print the employee names while (rset.next ())

Page 173: Jdbc Faq From Jguru

// System.out.println (rset.getString (1)); ;

// Close the RseultSet rset.close(); rset = null;

// Close the Statement stmt.close(); stmt = null;

// Close the logical connection conn.close(); conn = null;

// Close the pooled connection pc.close(); pc = null;

System.out.println( "workerClass.thread# "+threadNumber+" completed..");

}

public void setThreadNumber( int assignment ){ threadNumber = assignment; }

public void setConnectionPoolDataSource(OracleConnectionPoolDataSource x){ ocpds = x; }

public void run() { try{ doWork(); } catch ( Exception ex ){ ex.printStackTrace(); } }

}The OutPut Produced Started Thread#1Started Thread#2Started Thread#3Started Thread#4Started Thread#5Started Thread#6Started Thread#7Started Thread#8Started Thread#9Started Thread#10workerClass.thread# 1 completed..workerClass.thread# 10 completed..workerClass.thread# 3 completed..

Page 174: Jdbc Faq From Jguru

workerClass.thread# 8 completed..workerClass.thread# 2 completed..workerClass.thread# 9 completed..workerClass.thread# 5 completed..workerClass.thread# 7 completed..workerClass.thread# 6 completed..workerClass.thread# 4 completed..The oracle.jdbc.pool.OracleConnectionCacheImpl class is another subclass of the oracle.jdbc.pool.OracleDataSource which should also be looked over, that is what you really what to use. Here is a similar example that uses the oracle.jdbc.pool.OracleConnectionCacheImpl. The general construct is the same as the first example but note the differences in workerClass1 where some statements have been commented ( basically a clone of workerClass from previous example ).

The Executable Member

// Copyright (c) 2000package package6;import java.sql.*;import javax.sql.*;import oracle.jdbc.pool.*;

/** * package6.executableTester2 * * @author Me */public class executableTester2 { static int i = 0; protected static myOracleConnectCache connectionCache = null;

/** * Constructor */ public executableTester2() throws SQLException { }

/** * main * @param args */ public static void main(String[] args) { OracleConnectionPoolDataSource dataSource = null;

try{

dataSource = new OracleConnectionPoolDataSource() ; connectionCache = new myOracleConnectCache( dataSource );

} catch ( Exception ex ){ ex.printStackTrace(); }

while ( i++ < 10 ) {

Page 175: Jdbc Faq From Jguru

try{ workerClass1 worker = new workerClass1(); worker.setThreadNumber( i ); worker.setConnection( connectionCache.getConnection() ); worker.start(); System.out.println( "Started Thread#"+i ); } catch ( Exception ex ){ ex.printStackTrace(); } } } protected void finalize(){ try{ connectionCache.close(); } catch ( SQLException x) { x.printStackTrace(); } this.finalize(); }

}The ConnectCacheImpl Member // Copyright (c) 2000package package6;import javax.sql.ConnectionPoolDataSource;import oracle.jdbc.pool.*;import oracle.jdbc.driver.*;import java.sql.*;import java.sql.SQLException;

/** * package6.myOracleConnectCache * * @author Me */public class myOracleConnectCache extends OracleConnectionCacheImpl {

/** * Constructor */ public myOracleConnectCache( ConnectionPoolDataSource x) throws SQLException { initialize(); }

public void initialize() throws SQLException { setURL("jdbc:oracle:oci8:@myDB"); setUser("scott"); setPassword("tiger"); // // prefab 2 connection and only grow to 4 , setting these // to various values will demo the behavior clearly, if it is not // obvious already // setMinLimit(2); setMaxLimit(4);

Page 176: Jdbc Faq From Jguru

}

}The Worker Thread Member package package6;import oracle.jdbc.pool.*;import java.sql.*;import javax.sql.*;

/** * package6.workerClass1 * * @author Me */public class workerClass1 extends Thread { // protected OracleConnectionPoolDataSource ocpds = null; // protected PooledConnection pc = null;

protected Connection conn = null;

protected int threadNumber = 0; /** * Constructor */

public workerClass1() { }

public void doWork( ) throws SQLException {

// Create a pooled connection // pc = ocpds.getPooledConnection();

// Get a Logical connection // conn = pc.getConnection();

// Create a Statement Statement stmt = conn.createStatement ();

// Select the ENAME column from the EMP table ResultSet rset = stmt.executeQuery ("select ename from EMP");

// Iterate through the result and print the employee names while (rset.next ()) // System.out.println (rset.getString (1)); ;

// Close the RseultSet rset.close(); rset = null;

// Close the Statement stmt.close(); stmt = null;

// Close the logical connection

Page 177: Jdbc Faq From Jguru

conn.close(); conn = null;

// Close the pooled connection // pc.close(); // pc = null;

System.out.println( "workerClass1.thread# "+threadNumber+" completed..");

}

public void setThreadNumber( int assignment ){ threadNumber = assignment; }

// public void setConnectionPoolDataSource(OracleConnectionPoolDataSource x){ // ocpds = x; // }

public void setConnection( Connection assignment ){ conn = assignment; }

public void run() { try{ doWork(); } catch ( Exception ex ){ ex.printStackTrace(); } }

}The OutPut Produced Started Thread#1Started Thread#2workerClass1.thread# 1 completed..workerClass1.thread# 2 completed..Started Thread#3Started Thread#4Started Thread#5workerClass1.thread# 5 completed..workerClass1.thread# 4 completed..workerClass1.thread# 3 completed..Started Thread#6Started Thread#7Started Thread#8Started Thread#9workerClass1.thread# 8 completed..workerClass1.thread# 9 completed..workerClass1.thread# 6 completed..workerClass1.thread# 7 completed..Started Thread#10workerClass1.thread# 10 completed..

Page 178: Jdbc Faq From Jguru

How do I check in my code whether a maximum limit of database connections have been reached?Location: http://www.jguru.com/faq/view.jsp?EID=586776 Created: Dec 17, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Rajiv Onat (http://www.jguru.com/guru/viewbio.jsp?EID=473701

Use DatabaseMetaData.getMaxConnections() and compare to the number of connections currently open. Note that a return value of zero can mean unlimited or, unfortunately, unknown. Of course, driverManager.getConnection() will throw an exception if a Connection can not be obtained. For a little more discussion, see Can a single thread open up mutliple connections simultaneously for the same database and for same table?.

What is the JDBC syntax for using a literal or variable in a standard Statement?Location: http://www.jguru.com/faq/view.jsp?EID=593348 Created: Dec 21, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

First, it should be pointed out that PreparedStatement handles many issues for the developer and normally should be preferred over a standard Statement.

Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that often affects newbies ( and others ) is that SQL, like many languages, requires quotes around character ( read "String" for Java ) values to distinguish from numerics. So the clause:

"WHERE myCol = " + myValis perfectly valid and works for numerics, but will fail when myVal is a String. Instead use: "WHERE myCol = '" + myVal + "'"if myVal equals "stringValue", the clause works out to: WHERE myCol = 'stringValue'You can still encounter problems when quotes are embedded in the value, which, again, a PreparedStatement will handle for you.

Also see: What is the JDBC syntax for using a date literal or variable in a standard Statement?.

Comments and alternative answers

Gotcha for Oracle JDBC Driver Author: Avi Abrami (http://www.jguru.com/guru/viewbio.jsp?EID=31214), Dec 24, 2001Here's a "gotcha" regarding the Oracle JDBC driver that you may not be aware of.

Database table columns of type CHAR, when extracted from a ResultSet (using getString) will be padded with trailing spaces, e.g.

CREATE TABLE test (

Page 179: Jdbc Faq From Jguru

col CHAR(5));INSERT INTO test VALUES ('one');

and now the java code Connection c = DriverManager.getConnection();Statement s = c.createStatement();String q = "SELECT col FROM test";ResultSet rs = s.executeQuery(q);String col = rs.getString(1);System.out.println("'" + col + "'");

and the output is 'one '

in other words, two trailing spaces. Cheers,Avi.

My company says it can't aford a DBMS. What can I do? Location: http://www.jguru.com/faq/view.jsp?EID=593364 Created: Dec 21, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by taniem choudhury (http://www.jguru.com/guru/viewbio.jsp?EID=561166

Few companies can really afford NOT to use a DBMS. If nothing else, developer time spent on custom persistence methods can quickly surpass the cost of a DBMS. If the company doesn't understand this, one option often offered in jest may get serious: Find another company.

But there are low cost, production quality options available and it's worth using the drivers list ( see Where can I find a comprehensive list of JDBC drivers, including the databases they support? ) in reverse to check out DBMS candidates.

Open source DBMS engines are another possibility. For some options there, see Tools for the Open-Source Database

Another, possibly larger, consideration for a cost concious company is that a number of the large commercial databases effectively require a full time DBA, meaning another salary. For that reason, you'll want to look for an easy to use, low maintenance product.

I want to learn JDBC on a production quality DBMS, but I can't personally afford it. What can I do?Location: http://www.jguru.com/faq/view.jsp?EID=593394 Created: Dec 21, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

This is not the problem it once was, although your hard drive may groan. Many of the major DBMS vendors now offer personal or developer versions for download at no cost. The J2EE download also includes a supporting DBMS. In addition, there are several open source databases available. For more information on where to look for these products, see: My company says it can't aford a DBMS. What can I do?

Page 180: Jdbc Faq From Jguru

How do I set properties for a JDBC driver and where are the properties stored?Location: http://www.jguru.com/faq/view.jsp?EID=593758 Created: Dec 21, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Pradeep Kharvi (http://www.jguru.com/guru/viewbio.jsp?EID=342402

A JDBC driver may accept any number of properties to tune or optimize performance for the specific driver. There is no standard, other than user and password, for what these properties should be. Therefore, the developer is dependent on the driver documentation to automatically pass properties. For a standard dynamic method that can be used to solicit user input for properties, see What properties should I supply to a database driver in order to connect to a database?

In addition, a driver may specify its own method of accepting properties. Many do this via appending the property to the JDBC Database URL. However, a JDBC Compliant driver should implement the connect(String url, Properties info) method. This is generally invoked through DriverManager.getConnection(String url, Properties info).

The passed properties are ( probably ) stored in variables in the Driver instance. This, again, is up to the driver, but unless there is some sort of driver setup, which is unusual, only default values are remembered over multiple instantiations.

What is an SQL Locator?Location: http://www.jguru.com/faq/view.jsp?EID=594568 Created: Dec 23, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

A Locator is an SQL3 data type that acts as a logical pointer to data that resides on a database server. Read "logical pointer" here as an identifier the DBMS can use to locate and manipulate the data. A Locator allows some manipulation of the data on the server. While the JDBC specification does not directly address Locators, JDBC drivers typically use Locators under the covers to handle Array, Blob, and Clob data types. For more information, see SQL Locators.

Why do I have to reaccess the database for Array, Blob, and Clob data?Location: http://www.jguru.com/faq/view.jsp?EID=594583 Created: Dec 23, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Most DBMS vendors have implemented these types via the SQL3 Locator type ( see What is an SQL Locator? and the JDBC 2.1 core API specifies "By default, a JDBC driver should implement the Blob and Clob interfaces using the appropriate locator type." The same is true for the Array interface.

Some rationales for using Locators rather than directly returning the data can be seen most clearly with the Blob type. By definition, a Blob is an arbitrary set of binary data. It could be anything; the DBMS has no knowledge of what the data represents. Notice that this effectively demolishes data independence, because applications must now be aware of what the Blob data actually represents. Let's assume an employee table that includes employee images as Blobs.

Page 181: Jdbc Faq From Jguru

Say we have an inquiry program that presents multiple employees with department and identification information. To see all of the data for a specific employee, including the image, the summary row is selected and another screen appears. It is only at this pont that the application needs the specific image. It would be very wasteful and time consuming to bring down an entire employee page of images when only a few would ever be selected in a given run.

Now assume a general interactive SQL application. A query is issued against the employee table. Because the image is a Blob, the application has no idea what to do with the data, so why bring it down, killing performance along the way, in a long running operation?

Clearly this is not helpful in those applications that need the data everytime, but these and other considerations have made the most general sense to DBMS vendors.

What does it mean to "materialize" data?Location: http://www.jguru.com/faq/view.jsp?EID=594585 Created: Dec 23, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

This term generally refers to Array, Blob and Clob data which is referred to in the database via SQL locators ( see What is an SQL Locator? ) "Materializing" the data means to return the actual data pointed to by the Locator.

For Arrays, use the various forms of getArray() and getResultSet().

For Blobs, use getBinaryStream() or getBytes(long pos, int length).

For Clobs, use getAsciiStream() or getCharacterStream().

How can I get or redirect the log used by DriverManager and JDBC drivers? Location: http://www.jguru.com/faq/view.jsp?EID=594586 Created: Dec 23, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

As of JDBC 2.0, use DriverManager.getLogWriter() and DriverManager.setLogWriter(PrintWriter out). Prior to JDBC 2.0, the DriverManager methods getLogStream() and setLogStream(PrintStream out) were used. These are now deprecated.

How can I write to the log used by DriverManager and JDBC drivers? Location: http://www.jguru.com/faq/view.jsp?EID=594587 Created: Dec 23, 2001 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The simplest method is to use DriverManager.println(String message), which will write to the current log.

How do I receive a ResultSet from a stored procedure?Location: http://www.jguru.com/faq/view.jsp?EID=706497 Created: Jan 1, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question

Page 182: Jdbc Faq From Jguru

originally posed by prads gupta (http://www.jguru.com/guru/viewbio.jsp?EID=703714

Stored procedures can return a result parameter, which can be a result set. For a discussion of standard JDBC syntax for dealing with result, IN, IN/OUT and OUT parameters, see Stored Procedures. In addition, see How do I execute stored procedures?, How can I get data from multiple ResultSets?, Could we get sample code for retrieving more than one parameter from a stored procedure?. Comments and alternative answers

Also depends on database Author: Roger Hand (http://www.jguru.com/guru/viewbio.jsp?EID=292314), Jan 4, 2002Getting a ResultSet is much easier using MS SQL Server and possibly other databases. It's more of a runaround with Oracle.

Re: Also depends on database Author: Azeez Ahmed (http://www.jguru.com/guru/viewbio.jsp?EID=756868), Feb 13, 2002IF u want to retrieve from Oracle stored procedure.Register the out parameter using oracleTypes.Cursor and after executing the stored procedure use statement object's getObject() method which returns resultset.

Re[2]: Also depends on database Author: Rob van Oostrum (http://www.jguru.com/guru/viewbio.jsp?EID=829049), Apr 8, 2002my stor proc is defined like this:

PROCEDURE prc_getConfigurationItems (outConfigurationItems OUT curResultRecords, inVersionNumber epp_cat_xml_crossreference.val_version_number%TYPE)

my code looks like this:

protected static final String QUERY = "{ call pkg_catalogue.prc_getconfigurationitems ( ?, ? ) }";source = (DataSource)context.lookup(JDBC_DATASOURCE_NAME);Connection connection = source.getConnection();callable = connection.prepareCall(QUERY);callable.registerOutParameter( 1, Types.REF, "oracleTypes.Cursor" );callable.setString( 2, "1" );

I get an SQLException (invalid name pattern: oracleTypes.Cursor) on the registerOutParameter() call.

I've tried setting the out param as java.sql.Types.OTHER and NULL as well, but then I get an error 'invalid column type' what am I doing wrong here?

Page 183: Jdbc Faq From Jguru

Can't I just drop the output param name and use the ResultSet returned by executeQuery() instead?

Re[3]: Also depends on database Author: Rob van Oostrum (http://www.jguru.com/guru/viewbio.jsp?EID=829049), Apr 8, 2002I got it figured out. Sorry if I wasted anybody's time with this.

Re[3]: Also depends on database Author: steve wang (http://www.jguru.com/guru/viewbio.jsp?EID=1005153), Sep 27, 2002Rob, please share what you done to oracle procedure return resultset ! Thanks

Re[4]: Also depends on database Author: Jojo Vithayathil (http://www.jguru.com/guru/viewbio.jsp?EID=1042234), Jan 2, 2003Try this code below, I think it will solve your problem.. public class OracleFunction {

public static void main(String s[]) {try {

//Makes a connection to databaseConnection con = null;

Class.forName("oracle.jdbc.driver.OracleDriver");con =

(Connection)DriverManager.getConnection("jdbc:oracle:thin:@IP:PORT:SID","USER","PASSWORD");

//CallableStatement has to used to get back results from Oracle function

CallableStatement cstmt = con.prepareCall("{? = call PACKAGE_NAME.FUNCTION_NAME }");

//Set the Out Parameter type to be of type CURSOR

cstmt.registerOutParameter(1, oracle.jdbc.driver.OracleTypes.CURSOR );

cstmt.execute();

//Cast the returned parameter, OracleTypes.CURSOR to a JDBC ResultSet

ResultSet rs = (ResultSet)cstmt.getObject(1);

while(rs.next()) {

System.out.println(rs.getString(1));}rs.close();if(cstmt != null)cstmt.close();

Page 184: Jdbc Faq From Jguru

if(con != null) con.close();} catch (Exception e) {

System.out.println(e.toString());}

}}

Re[3]: Also depends on database Author: Prabu Kalyan (http://www.jguru.com/guru/viewbio.jsp?EID=1175180), May 31, 2004hi.. Can u share how did u sorted it

Re: Also depends on database Author: Patrick Brendel (http://www.jguru.com/guru/viewbio.jsp?EID=1216503), Dec 15, 2004can you submit what it would look like for SQL Server 2000.

Connecting to a database through the Proxy I want to connect to remote database using a program that is running in the local network behind the proxy. Is that possible? Location: http://www.jguru.com/faq/view.jsp?EID=731343 Created: Jan 22, 2002 Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955) Question originally posed by elisabeth jolly (http://www.jguru.com/guru/viewbio.jsp?EID=444588

I assume that your proxy is set to accept http requests only on port 80. If you want to have a local class behind the proxy connect to the database for you, then you need a servlet/JSP to receive an HTTP request and use the local class to connect to the database and send the response back to the client.

You could also use RMI where your remote computer class that connects to the database acts as a remote server that talks RMI with the clients. if you implement this, then you will need to tunnel RMI through HTTP which is not that hard.

In summary, either have a servlet/JSP take HTTP requests, instantiate a class that handles database connections and send HTTP response back to the client or have the local class deployed as RMI server and send requests to it using RMI.

How can I determine the isolation levels supported by my DBMS?Location: http://www.jguru.com/faq/view.jsp?EID=740638 Created: Jan 30, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Use DatabaseMetaData.supportsTransactionIsolationLevel(int level). See also: How does one manage concurrency issues with JDBC?

What isolation level is used by the DBMS when inserting, updating and selecting rows from a database?Location: http://www.jguru.com/faq/view.jsp?EID=740645

Page 185: Jdbc Faq From Jguru

Created: Jan 30, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by ani ani (http://www.jguru.com/guru/viewbio.jsp?EID=706510

The answer depends on both your code and the DBMS. If the program does not explicitly set the isolation level, the DBMS default is used. You can determine the default using DatabaseMetaData.getDefaultTransactionIsolation() and the level for the current Connection with Connection.getTransactionIsolation(). If the default is not appropriate for your transaction, change it with Connection.setTransactionIsolation(int level). See also: How does one manage concurrency issues with JDBC?

Update fails without blank padding. Alhough a particular row is present in the database for a given key, executeUpdate() shows 0 rows updated and, in fact, the table is not updated. If I pad the Key with spaces for the column length (eg if the key column is 20 characters long, and key is msgID, length 6, I pad it with 14 spaces), the update then works!!! Is there any solution to this problem without padding?Location: http://www.jguru.com/faq/view.jsp?EID=740854 Created: Jan 30, 2002 Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by Bobs Obs (http://www.jguru.com/guru/viewbio.jsp?EID=737948

Are you using a CHAR or a VARCHAR data field? I remember having the same problem with a CHAR type, and then we switched to a VARCHAR.

Joe Sam Shirah adds: In the SQL standard, CHAR is a fixed length data type. In many DBMSes ( but not all), that means that for a WHERE clause to match, every character must match, including size and trailing blanks. As Alessandro indicates, defining CHAR columns to be VARCHAR is the most general answer.

Comments and alternative answers

UPDATE int(5) zerofill key with 00003 instead of 3 in the WHERE clause of my prepared statement ?? Author: mad driver (http://www.jguru.com/guru/viewbio.jsp?EID=865419), Jun 29, 2002I currently have the same problem. I'm using MYSQL int(5) autoincrement with zerofill as only key. So far I used INSERT-statements.fine. Now I try my first UPDATE.No exception,error,nothing...but nothing got updated too!

Do i need to change the input in the WHERE clause from 3 to 00003 ?? Is there a varint?:)Is there the same problem with no zerofill option ?I see that real 0000's are different from blanks, but I never had a problem with blanks in my varchar, and I obviously have been a little naiv when I just expected leading zeros to be ignored?Is there a standard routine I could use with the jdbc?

Page 186: Jdbc Faq From Jguru

thanks for help in advance mad

What are the standard isolation levels defined by JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=740857 Created: Jan 30, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The values are defined in the class java.sql.Connection and are: TRANSACTION_NONE TRANSACTION_READ_COMMITTED TRANSACTION_READ_UNCOMMITTED TRANSACTION_REPEATABLE_READ TRANSACTION_SERIALIZABLE

Any given database may not support all of these levels. To find out if yours does, see: How can I determine the isolation levels supported by my DBMS? Comments and alternative answers

jdbc Author: jagadish varma (http://www.jguru.com/guru/viewbio.jsp?EID=1127658), Nov 11, 2003hi plz write me a sample code to demonstrate how to use constants defined java.sql.connection as well as java.sql.statement

is is possible to open a connection to a database with exclusive mode with JDBC?Location: http://www.jguru.com/faq/view.jsp?EID=742017 Created: Jan 31, 2002 Author: Jay Meyer (http://www.jguru.com/guru/viewbio.jsp?EID=708650) Question originally posed by Fofana Mamadi (http://www.jguru.com/guru/viewbio.jsp?EID=505453

I think you mean "lock a table in exclusive mode". You cannot open a connection with exclusive mode. Depending on your database engine, you can lock tables or rows in exclusive mode.

In Oracle you would create a statement st and run

st.execute("lock table mytable in exclusive mode");Then when you are finished with the table, execute the commit to unlock the table. Mysql, informix and SQLServer all have a slightly different syntax for this function, so you'll have to change it depending on your database. But they can all be done with execute().Comments and alternative answers

jdbc Author: payal ahuja (http://www.jguru.com/guru/viewbio.jsp?EID=991966), Aug 30, 2002

Page 187: Jdbc Faq From Jguru

what is jdbc?

Re: jdbc Author: payal ahuja (http://www.jguru.com/guru/viewbio.jsp?EID=991966), Aug 30, 2002good

comment Author: payal ahuja (http://www.jguru.com/guru/viewbio.jsp?EID=991966), Aug 30, 2002good

I'd like to evaluate the Object/Relational Mapping approach and products. Any discussion is helpful.Location: http://www.jguru.com/faq/view.jsp?EID=742027 Created: Jan 31, 2002 Author: Matt Goodall (http://www.jguru.com/guru/viewbio.jsp?EID=450000) Question originally posed by Roy Ngan (http://www.jguru.com/guru/viewbio.jsp?EID=485142

jguru Disclaimer: The following views and opinions are entirely those of the respondents and provided for our readers to consider. jGuru is not in the business of evaluating products.

Disclaimer: I'm still in the process of evaluating some of these tools so you should do your own tests before making any final decisions.

I think an O/R mapping tool could help a lot. After all, there is nothing more tedious and error prone than writing code to move data from a database to a Java class and back again!

If you are lucky enough that you have a database schema that reflects the object model reasonably well then I think these tools will help a lot.

Unfortunately, I think I'm coming to the conclusion that it is not worth trying to use these tools with a legacy database. By legacy, I mean one that was never designed in an object-oriented way. Instead, you should probably use a DAO approach.

I've looked at quite a few: TopLink, CocoBase, OJB, Castor. Of those, I favour TopLink and OJB. OJB is open source, if that appeals, and is nearing a 1.0 release. It's continuously improving, has active development and the lead developer is extremely responsive to both suggestions and bug reports.

You need to choose carefully. In particular, think about how you want to manage connections and transactions. Perhaps you want to use these tools inside an EJB container and take advantage of the container's transaction management?

Unless the application is fairly simple, I suspect there will always be the need for writing JDBC but hopefully that would be the exception.

Page 188: Jdbc Faq From Jguru

I would recommend reading Scott Ambler's white papers on the subject, just to get a feel for what an O/R tool should do:

Mapping Objects To Relational Databases The Design of a Robust Persistence Layer for Relational Databases

There is plenty more information on the internet. Please post your findings back here.

Jay Meyer adds: I have used Toplink in a large Weblogic environemnt, and it has good and bad points. You were right: do NOT use Toplink on a legacy database, it will not be able to handle some of the complex relationships. We ended up redesigning some tables to make Toplink work with our old schema. But once we did that it would gen the EJBs and change tables anytime we needed to add columns or tables to the database. This was useful in the large dev team. The downside to Toplink or any O-R mapping tool is that you invariably have to learn yet another query language. Toplink's query builder was really hard to understand especially when you have dozens of programmers who already know SQL and want to use SQL directly. For our next project, we used the Ambler persistence (mentioned in Matt's message) technique and wrote our own mapping classes. It turned out to be about the same amount of work/time as installing/configuring Toplink, we just needed some skilled Java/JDBC programmers to build it. But now we have full controll over queries and performance using the JDBC calls and we do not have to figure out Toplink's cryptic product.

Christopher Schultz adds: Although they don't seem to be common, Object Databases are a viable option. Some people say they are slow, but O-R mappings are difficult to write/maintain/understand. Check into Versant and others for an object database and see what they have to offer.

Joe Sam Shirah adds: Object databases are certainly an option, but there are many reasons the relational model has remained the data backbone. My own opinion is that when evaluating an object database, an important criteria should be that it also supports the relational model as much as possible.

Another open source O/R tool to review is the Java Layered Frameworks ( JLF ).

How can I insert images into a Mysql database? Location: http://www.jguru.com/faq/view.jsp?EID=742030 Created: Jan 31, 2002 Modified: 2002-01-31 19:22:59.694Author: Kasi Mono (http://www.jguru.com/guru/viewbio.jsp?EID=548189) Question originally posed by Sreenivas Kandikonda (http://www.jguru.com/guru/viewbio.jsp?EID=495259

This code snippet shows the basics: File file = new File(fPICTURE);FileInputStream fis = new FileInputStream(file);PreparedStatement ps = ConrsIn.prepareStatement("insert into dbPICTURE values (?,?)");

// ***use as many ??? as you need to insert in the exact order*** ps.setString(1,file.getName());ps.setBinaryStream(2,fis,(int)file.length());ps.executeUpdate();ps.close();

Page 189: Jdbc Faq From Jguru

fis.close();

How do I write Greek ( or other non-ASCII/8859-1 ) characters to a database? Location: http://www.jguru.com/faq/view.jsp?EID=742076 Created: Jan 31, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Devendar Naine (http://www.jguru.com/guru/viewbio.jsp?EID=735506

From the standard JDBC perspective, there is no difference between ASCII/8859-1 characters and those above 255 ( hex FF ). The reason for that is that all Java characters are in Unicode ( unless you perform/request special encoding ). Implicit in that statement is the presumption that the datastore can handle characters outside the hex FF range or interprets different character sets appropriately. That means either:

The OS, application and database use the same code page and character set. For example, a Greek version of NT with the DBMS set to the default OS encoding.

The DBMS has I18N support for Greek ( or other language ), regardless of OS encoding. This has been the most common for production quality databases, although support varies. Particular DBMSes may allow setting the encoding/code page/CCSID at the database, table or even column level. There is no particular standard for provided support or methods of setting the encoding. You have to check the DBMS documentation and set up the table properly.

The DBMS has I18N support in the form of Unicode capability. This would handle any Unicode characters and therefore any language defined in the Unicode standard. Again, set up is proprietary.

Note that a specific DBMS may provide some combination of all of these. Outside of those scenarios, you would, in general, have to handle encoding yourself. For all intents and purposes, you would have binary data in a character column. Aside from being error prone, you would lose virtually all benefits of a DBMS other than identity, structure, security and, presumably, reliability.

Driver memory problem I am using interclient driver to connect to interbase. My program does lots of inserts, updates, selects, etc.

The problem I found is that if I create a statement for each operation the memory used increases fast! I am closing each of the statements... and autocommit is true! Please help!Location: http://www.jguru.com/faq/view.jsp?EID=761133 Created: Feb 16, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Filipe Lima de Souza (http://www.jguru.com/guru/viewbio.jsp?EID=756154

Regardless of DBMS, there's no particular reason to close a Statement until you are done with your operations - assuming 1) a JDBC compliant driver works normally; 2) that there aren't extended periods when the Statement isn't used and 3) you aren't using a connection pool, which would mean closing the Statement before returning the connection to the pool.

Page 190: Jdbc Faq From Jguru

Depending on what you are doing, the memory usage may be completely normal; In the JVM, memory usage will rise until the garbage collector kicks in. It may well be that the driver has memory leaks - you should check their site/support/forums - but the factors above are still true.

Can you scroll a result set returned from a stored procedure? I am returning a result set from a stored procedure with type SQLRPGLE but once I reach the end of the result set it does not allow repositioning. Is it possible to scroll this result set?Location: http://www.jguru.com/faq/view.jsp?EID=761196 Created: Feb 16, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Shannon Clement (http://www.jguru.com/guru/viewbio.jsp?EID=754297

A CallableStatement is no different than other Statements in regard to whether related ResultSets are scrollable. You should create the CallableStatement using Connection.prepareCall(String sql, int resultSetType, int resultSetConcurrency).

For more information, see 7.1.1 Creating a CallableStatement Object, Can a stored procedure return an updatable ResultSet?, and How do I receive a ResultSet from a stored procedure?.

Comments and alternative answers

Statements works different than CallableStatement Author: Auro Martinez (http://www.jguru.com/guru/viewbio.jsp?EID=877577), May 23, 2002Hi, I can use scrollable ResultSets for Statements, but I can not for CallableStatements... I use Store Procedures in PL-SQL, I use procedures with a REF CURSOR as the OUT parameter. I can take the type of the callableStatement and I verify that it is scrollable, but the resultset I obtain is forward only. Can anybody help me?? Thanks, Auro

Re: Statements works different than CallableStatement Author: LuisCarlos Martinez (http://www.jguru.com/guru/viewbio.jsp?EID=935041), Jul 2, 2002Hi, i have the same problem. It's very urgent for me to find it out. somebody knows how to solve this problem ? thanks in advance.

Re: Statements works different than CallableStatement Author: Bogdan Paulon (http://www.jguru.com/guru/viewbio.jsp?EID=947730), Sep 27, 2002Hi, I've tried in many ways to get a scrollable result set from a PL/SQL stored procedure. The resultset I obtain is always forward only. Is it really possible

Page 191: Jdbc Faq From Jguru

with PL/SQL stored procedures? Thanks, Bogdan

Re[2]: Statements works different than CallableStatement Author: Emerson Cargnin (http://www.jguru.com/guru/viewbio.jsp?EID=851345), Dec 10, 2002a related question, may I pass a resultset through a out parameter?

Re: Statements works different than CallableStatement Author: sharan yadrami (http://www.jguru.com/guru/viewbio.jsp?EID=1045060), Sep 12, 2003

Hai Auro I have the same problem.Can u help me out if u have got the answer.It is very urgent.my code goes like this my code goes like this import oracle.jdbc.*;

import java.sql.*; import javax.sql.*; class TestProcedure { public static void main(String args[]) { TestProcedure test = new TestProcedure(); test.Test(); } public void Test() { java.sql.CallableStatement cstmtObject = null; java.sql.ResultSet rulesObject = null; try{ String conStr = "jdbc:oracle:thin:@172.20.10.7:1521:BAS"; String user = "test"; String pass = "test123"; DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); java.sql.Connection conn = (java.sql.Connection)DriverManager.getConnection(conStr,user,pass); System.out.println("connected"); String sqlquery = "{call test.COMPUTATION(?,?,?,?)}"; cstmtObject = conn.prepareCall(sqlquery,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); cstmtObject.setString(1,"BSD"); cstmtObject.setString(2,"BG"); cstmtObject.setString(3,"monthly"); cstmtObject.registerOutParameter(4,OracleTypes.CURSOR); rulesObject = (java.sql.ResultSet)cstmtObject.getObject(4);

Page 192: Jdbc Faq From Jguru

System.out.println("resultset type="+rulesObject.getType()); while(rulesObject.next()) { int ruleid = rulesObject.getInt("rule_id"); String rulename = rulesObject.getString("rule_name"); String expression = rulesObject.getString("expression"); } rulesObject.first(); //Error here conn.close(); }catch(SQLException e){System.out.println(e);} } } When I give rulesObject.first(); it gives SQL Exception of forwardly only resultset. How can I scroll through the resultset. thanks in advance.

Re[2]: Statements works different than CallableStatement Author: deepak kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1227958), Feb 18, 2005Can yu pls help me asap I will be grateful

What driver should I use for scalable Oracle JDBC applications?Location: http://www.jguru.com/faq/view.jsp?EID=761197 Created: Feb 16, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Sun recommends using the thin ( type 4 ) driver. On single processor machines to avoid JNI overhead. On multiple processor machines, especially running Solaris, to avoid

synchronization bottlenecks.

For more information, see My application uses a database and doesn't seem to scale well. What could be going on? on the FREQUENTLY ASKED QUESTIONS ABOUT THE JAVA HOTSPOT VIRTUAL MACHINE page.

Detecting Duplicate Keys I have a program that inserts rows in a table. My table has a column 'Name' that has a unique constraint. If the user attempts to insert a duplicate name into the table, I want to display an error message by processing the error code from the database. How can I capture this error code in a Java program? Location: http://www.jguru.com/faq/view.jsp?EID=772838 Created: Feb 26, 2002 Author: JIA Java Italian Association (http://www.jguru.com/guru/viewbio.jsp?EID=414973) Question originally posed by sabu vs PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=476248

A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.

Page 193: Jdbc Faq From Jguru

Joe Sam Shirah adds: You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000. For more information, see Where can I find a list of the possible SQLStates returned by SQLException.getSQLState()? and my JDBC 2.0 Fundamentals Short Course at the Java Developer Connection.

Comments and alternative answers

executing a query for checking if the unique value is present Author: Radu Chiriac (http://www.jguru.com/guru/viewbio.jsp?EID=985677), Aug 20, 2002The problem with executing a query for checking if the unique value is present is that between your select and insert someone else could insert a record that contains the value that you are trying to insert. In this case you'll get a constraint violation even though your select told you that it's ok to insert your record.

How can I protect my database password ? I'm writing a client-side java application that will access a database over the internet. I have concerns about the security of the database passwords. The client will have access in one way or another to the class files, where the connection string to the database, including user and password, is stored in as plain text. What can I do to protect my passwords?Location: http://www.jguru.com/faq/view.jsp?EID=773509 Created: Feb 26, 2002 Author: Jay Meyer (http://www.jguru.com/guru/viewbio.jsp?EID=708650) Question originally posed by Francois Vander Linden (http://www.jguru.com/guru/viewbio.jsp?EID=717776

This is a very common question. I answered a similiar question at Remote database over internet + Java Swing app with JDBC != secure?

Conclusion: JAD decompiles things easily and obfuscation would not help you. But you'd have the same problem with C/C++ because the connect string would still be visible in the executable.

SSL JDBC network drivers fix the password sniffing problem (in MySQL 4.0), but not the decompile problem. If you have a servlet container on the web server, I would go that route (see other discussion above) then you could at least keep people from reading/destroying your mysql database.

Make sure you use database security to limit that app user to the minimum tables that they need, then at least hackers will not be able to reconfigure your DBMS engine.

Joe Sam Shirah adds: Aside from encryption issues over the internet, it seems to me that it is bad practise to embed user ID and password into program code. One could generally see the text even without decompilation in almost any language. This would be appropriate only to a read-only database meant to be open to the world.

Page 194: Jdbc Faq From Jguru

Normally one would either force the user to enter the information or keep it in a properties file.

A production quality database will support security and user rights. Also, for more information regarding JDBC and SSL, see: Are there any JDBC drivers available that support using SSL to communicate between the Java program and the database server?

Can I set up a conection pool with multiple user IDs? The single ID we are forced to use causes probelems when debugging the DBMS. Location: http://www.jguru.com/faq/view.jsp?EID=773655 Created: Feb 26, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by John Murphy (http://www.jguru.com/guru/viewbio.jsp?EID=749811

Since the Connection interface ( and the underlying DBMS ) requires a specific user and password, there's not much of a way around this in a pool. While you could create a different Connection for each user, most of the rationale for a pool would then be gone. Debugging is only one of several issues that arise when using pools.

However, for debugging, at least a couple of other methods come to mind. One is to log executed statements and times, which should allow you to backtrack to the user. Another method that also maintains a trail of modifications is to include user and timestamp as standard columns in your tables. In this last case, you would collect a separate user value in your program.

How can I instantiate and load a new CachedRowSet object from a non-JDBC source? Location: http://www.jguru.com/faq/view.jsp?EID=776543 Created: Feb 28, 2002 Modified: 2002-02-28 10:15:29.257Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Covenant apoptygma (http://www.jguru.com/guru/viewbio.jsp?EID=747571

The basics are: Create an object that implements javax.sql.RowSetReader, which loads

the data. Instantiate a CachedRowset object. Set the CachedRowset's reader to the reader object previously created. Invoke CachedRowset.execute().

Note that a RowSetMetaData object must be created, set up with a description of the data, and attached to the CachedRowset before loading the actual data.

The following code works with the Early Access JDBC RowSet download available from the Java Developer Connection and is an expansion of one of the examples:

// Independent data source CachedRowSet Exampleimport java.sql.*;import javax.sql.*;import sun.jdbc.rowset.*;

Page 195: Jdbc Faq From Jguru

public class RowSetEx1 implements RowSetReader{ CachedRowSet crs; int iCol2; RowSetMetaDataImpl rsmdi; String sCol1, sCol3;

public RowSetEx1() { try { crs = new CachedRowSet(); crs.setReader(this); crs.execute(); // load from reader

System.out.println( "Fetching from RowSet..."); while(crs.next()) { showTheData(); } // end while next if(crs.isAfterLast() == true) { System.out.println( "We have reached the end"); System.out.println("crs row: " + crs.getRow()); } System.out.println( "And now backwards..."); while(crs.previous()) { showTheData(); } // end while previous if(crs.isBeforeFirst() == true) { System.out.println( "We have reached the start"); } crs.first(); if(crs.isFirst() == true) { System.out.println( "We have moved to first"); }

System.out.println("crs row: " + crs.getRow());

if(crs.isBeforeFirst() == false) { System.out.println(

Page 196: Jdbc Faq From Jguru

"We aren't before the first row."); }

crs.last(); if(crs.isLast() == true) { System.out.println( "...and now we have moved to the last"); }

System.out.println("crs row: " + crs.getRow());

if(crs.isAfterLast() == false) { System.out.println( "we aren't after the last."); }

} // end try catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } } // end constructor

public void showTheData() throws SQLException { sCol1 = crs.getString(1); if(crs.wasNull() == false) { System.out.println("sCol1: " + sCol1); } else { System.out.println("sCol1 is null"); } iCol2 = crs.getInt(2); if (crs.wasNull() == false) { System.out.println("iCol2: " + iCol2); } else { System.out.println("iCol2 is null"); }

sCol3 = crs.getString(3); if (crs.wasNull() == false) { System.out.println("sCol3: " + sCol3 + "\n" ); } else { System.out.println("sCol3 is null\n"); }

} // end showTheData

// RowSetReader implementation public void readData(RowSetInternal caller) throws SQLException {

Page 197: Jdbc Faq From Jguru

rsmdi = new RowSetMetaDataImpl(); rsmdi.setColumnCount(3); rsmdi.setColumnType(1, Types.VARCHAR); rsmdi.setColumnType(2, Types.INTEGER); rsmdi.setColumnType(3, Types.VARCHAR); crs.setMetaData( rsmdi ); crs.moveToInsertRow(); crs.updateString( 1, "StringCol11" ); crs.updateInt( 2, 1 ); crs.updateString( 3, "StringCol31" ); crs.insertRow();

crs.updateString( 1, "StringCol12" ); crs.updateInt( 2, 2 ); crs.updateString( 3, "StringCol32" ); crs.insertRow();

crs.moveToCurrentRow(); crs.beforeFirst();

} // end readData

public static void main(String args[]) { new RowSetEx1(); }

} // end class RowSetEx1

Comments and alternative answers

Modification of Joe Sam Shirah's example of populating a CachedRowSet form a non-JDBC source. Author: Andrey Grischuk (http://www.jguru.com/guru/viewbio.jsp?EID=974243), Aug 2, 2002Firs of all, thanks to Joe Sam Shirah for his example - I've found it quite useful. But because his implementation of RowSetReader includes the CachedRowSet object to be populated as a field, I decided to modify the example to avoid such dependence. It's possible because for the method aRowSetReader.readData(RowSetInternal caller) caller is the CachedRowSet object to modify. // Independent data source CachedRowSet Example

import java.sql.*;import javax.sql.*;

import sun.jdbc.rowset.*;

Page 198: Jdbc Faq From Jguru

public class RowSetEx2 implements RowSetReader {

// RowSetReader implementation public void readData(RowSetInternal caller) throws SQLException {

CachedRowSet crs = (CachedRowSet) caller;

RowSetMetaDataImpl rsmdi; rsmdi = new RowSetMetaDataImpl(); rsmdi.setColumnCount(3); rsmdi.setColumnType(1, Types.VARCHAR); rsmdi.setColumnType(2, Types.INTEGER); rsmdi.setColumnType(3, Types.VARCHAR); crs.setMetaData(rsmdi);

crs.moveToInsertRow();

crs.updateString(1, "StringCol11"); crs.updateInt(2, 1); crs.updateString(3, "StringCol31"); crs.insertRow();

crs.updateString(1, "StringCol12"); crs.updateInt(2, 2); crs.updateString(3, "StringCol32"); crs.insertRow();

crs.moveToCurrentRow(); crs.beforeFirst();

} // end readData

public static void showTheData(CachedRowSet crs) throws SQLException { String sCol1, sCol3; sCol1 = crs.getString(1); int iCol2;

if (crs.wasNull() == false) { System.out.println("sCol1: " + sCol1); } else { System.out.println("sCol1 is null"); }

iCol2 = crs.getInt(2); if (crs.wasNull() == false) { System.out.println("iCol2: " + iCol2); } else { System.out.println("iCol2 is null"); }

sCol3 = crs.getString(3); if (crs.wasNull() == false) { System.out.println("sCol3: " +

Page 199: Jdbc Faq From Jguru

sCol3 + "\n"); } else { System.out.println("sCol3 is null\n"); }

} // end showTheData

public static void main(String args[]) { try { CachedRowSet crs = new CachedRowSet(); crs.setReader(new RowSetEx2()); crs.execute(); // load from reader

System.out.println( "Fetching from RowSet..."); while (crs.next()) { showTheData(crs); } // end while next

if (crs.isAfterLast() == true) { System.out.println( "We have reached the end"); System.out.println("crs row: " + crs.getRow()); }

System.out.println( "And now backwards...");

while (crs.previous()) { showTheData(crs); } // end while previous

if (crs.isBeforeFirst() == true) { System.out.println( "We have reached the start"); }

crs.first(); if (crs.isFirst() == true) { System.out.println( "We have moved to first"); }

System.out.println("crs row: " + crs.getRow());

if (crs.isBeforeFirst() == false) { System.out.println( "We aren't before the first row."); }

crs.last(); if (crs.isLast() == true) { System.out.println( "...and now we have moved to the last");

Page 200: Jdbc Faq From Jguru

}

System.out.println("crs row: " + crs.getRow());

if (crs.isAfterLast() == false) { System.out.println( "we aren't after the last."); }

} // end try catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }

} // end class RowSetEx2

Re: Modification of Joe Sam Shirah's example of populating a CachedRowSet form a non-JDBC source. Author: Ken Ricci (http://www.jguru.com/guru/viewbio.jsp?EID=1122085), Oct 16, 2003Your example is exactly what I'm looking for. However, I cannot seem to get it to work. Something about instantiating. I monkeyed around with the code to get rid of most of the errors. However, the method crs.setReader does not exist. Can you please help me to get this to work? Thanks in advance, Ken Ricci

How do I implement a RowSetReader? I want to populate a CachedRowSet myself and the documents specify that a RowSetReader should be used. The single method accepts a RowSetInternal caller and returns void. What can I do in the readData method?Location: http://www.jguru.com/faq/view.jsp?EID=776878 Created: Feb 28, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

The documentation says "It can be implemented in a wide variety of ways..." and is pretty vague about what can actually be done. In general, readData() would obtain or create the data to be loaded, then use CachedRowSet methods to do the actual loading. This would usually mean inserting rows, so the code would move to the insert row, set the column data and insert rows. Then the cursor must be set to to the appropriate position.

For a working code example, see How can I instantiate and load a new CachedRowSet object from a non-JDBC source?

How does a custom RowSetReader get called from a CachedRowSet?Location: http://www.jguru.com/faq/view.jsp?EID=776879 Created: Feb 28, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

Page 201: Jdbc Faq From Jguru

The Reader must be registered with the CachedRowSet using CachedRowSet.setReader(javax.sql.RowSetReader reader). Once that is done, a call to CachedRowSet.execute() will, among other things, invoke the readData method. See How can I instantiate and load a new CachedRowSet object from a non-JDBC source? for a code example.

How can I create a custom RowSetMetaData object from scratch?Location: http://www.jguru.com/faq/view.jsp?EID=776880 Created: Feb 28, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

One unfortunate aspect of RowSetMetaData for custom versions is that it is an interface. This means that implementations almost have to be proprietary. The JDBC RowSet package is the most commonly available and offers the sun.jdbc.rowset.RowSetMetaDataImpl class.

After instantiation, any of the RowSetMetaData setter methods may be used. The bare minimum needed for a RowSet to function is to set the Column Count for a row and the Column Types for each column in the row. For a working code example that includes a custom RowSetMetaData, See How can I instantiate and load a new CachedRowSet object from a non-JDBC source?

Is any JDBC driver available that can access EDI messages?Location: http://www.jguru.com/faq/view.jsp?EID=809255 Created: Mar 23, 2002 Author: Laurent Mihalkovic (http://www.jguru.com/guru/viewbio.jsp?EID=407112) Question originally posed by Sudha L (http://www.jguru.com/guru/viewbio.jsp?EID=794500

I don't know about existing drivers, but JavaPro had a good article on writing your own driver. The example was a driver to access XML files. check it out at JavaPro December, 2001.

Joe Sam Shirah adds: There are also a number of resources for EDI <----> XML conversion. We don't make recommendations, but m-e-c eagle is an open source integrattion suite with such converters you can review. A good search engine will probably show more.

Where can I find info, frameworks and example source for writing a JDBC driver?Location: http://www.jguru.com/faq/view.jsp?EID=809257 Created: Mar 23, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100)

There a several drivers with source available, like MM.MySQL, SimpleText Database, FreeTDS, and RmiJdbc. There is at least one free framework, the jxDBCon-Open Source JDBC driver framework. Any driver writer should also review For Driver Writers.

How can I correctly parse CSV ( comma separated values ) files? StringTokenizer doesn't seem to fit many conditions. Location: http://www.jguru.com/faq/view.jsp?EID=809266 Created: Mar 23, 2002

Page 202: Jdbc Faq From Jguru

Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by steven mccartey (http://www.jguru.com/guru/viewbio.jsp?EID=792888

Ian Darwin has two classes ( CSV.java and CSVRE.java ) to handle CSV files in his Java Cookbook, including a way with regular expressions. You can download the code from his site, probably best to do so from the examples by chapter ( see Chapter 3, "Strings and Things" ) page. Not a bad idea to buy the book, either.Comments and alternative answers

use this class Author: Amardeep Singh (http://www.jguru.com/guru/viewbio.jsp?EID=811616), Mar 25, 2002import java.util.*;

public class WStringTokenizer extends StringTokenizer{

private String tbt;private String d;private int startpos=0;

public WStringTokenizer(String str,String delim){

super(str,delim);tbt=new String(str);d=new String(delim);

}public int countTokens(){

int tokens=0;int temp=startpos;

while(true){

try{nextToken();tokens++;}catch(NoSuchElementException e) {break;}

}startpos=temp;return tokens;}

public boolean hasMoreElements() {return hasMoreTokens();}

public boolean hasMoreTokens() {if(countTokens()>0) return true;else return false;}

public Object nextElement() {

Page 203: Jdbc Faq From Jguru

return (Object) d;}

public String nextToken() throws NoSuchElementException {int result=0;String s;

if(startpos>tbt.length()) throw(new NoSuchElementException ());

result=tbt.indexOf(d,startpos);if(result<0) result=tbt.length();s=new String(tbt.substring(startpos,result));startpos=result+d.length();return s;}

public String nextToken (String delim) throws NoSuchElementException {

d=delim;return nextToken();}

}

Another CSVReader Author: Roshan Shrestha (http://www.jguru.com/guru/viewbio.jsp?EID=130068), Mar 26, 2002Ian Darwin's class parses the file one line at a time. Many times, a field may span multiple lines. I think a better class is the CSVReader described in http://www.objectmentor.com/resources/articles/tfd.pdf. As an added bonus, it also desscribes unit testing with JUnit!

CSV Libraries Author: Stephen Ostermiller (http://www.jguru.com/guru/viewbio.jsp?EID=576685), Apr 17, 2002There are free open source libraries for parsing and printing CSV files available here: http://ostermiller.org/utils/CSVLexer.html

Re: CSV Libraries Author: Anjan Bacchu (http://www.jguru.com/guru/viewbio.jsp?EID=283891), Jun 1, 2004FYI,The library from ostermiller.org is licensed with GPL. This prevents usage of this library in commercial products (unless they are themselves GPL compatible). So, effectively you cannot use them unless your open source product is also GPL compatible.

BR,~A

Page 204: Jdbc Faq From Jguru

CSV Libraries for commercial use Author: Richard Rodger (http://www.jguru.com/guru/viewbio.jsp?EID=1220174), Jan 7, 2005There are commercial CSV parsers available, including:StelsCSV (a JDBC driver for CSV), andRicebridge Java CSV Parser (my own).

I am not currently aware of any open source CSV Java parsers that are under BSD or similar licenses that allow commercial use, but I could be wrong.

Library Author: davide consonni (http://www.jguru.com/guru/viewbio.jsp?EID=1190420), Aug 3, 2004can use csvToSql (http://sourceforge.net/projects/csvtosql/)

Re: Library Author: azad kans (http://www.jguru.com/guru/viewbio.jsp?EID=1249830), Jun 22, 2005using WStringTokenizer

as an implementation of StringTokenizer(String,deleimter)

is a good implementation and we have used it successfully in our projects .Another approach is to use String[] values = String.split(delimiter,no. Of Fields)

.This is effective when you know that each row will have fixed no. of columns(delimter separated values). The value returned is an array and each field can be retrieved by values[i]

which is very handy compared to StringTokenizer.I think this was introduced in 1.4 version of java

CSVFile classes Author: Fabrizio Fazzino (http://www.jguru.com/guru/viewbio.jsp?EID=1255529), Jul 28, 2005I've modified Ian Darwin's classes (preserving the copyright message) and created a new project on SourceForge:

SF Project Summary is at http://sourceforge.net/projects/csvfileand the documentation is at http://csvfile.sourceforge.net/.

There are 3 classes, CSVFile (abstract), CSVFileReader (that makes use of Ian's code) and CSVFileWriter; they are very easy to use since the fields are handles as Vector<String> variables.

Page 205: Jdbc Faq From Jguru

I also made it possible to customize the text qualifier (e.g. can be a tick or backtick rather than double quote) and the filed separator (e.g. can be a dot rather than a comma or semicolon).

Re: CSVFile classes Author: Paul Zepernick (http://www.jguru.com/guru/viewbio.jsp?EID=1032221), Aug 5, 2005I have a java project for parsing delimited and fixed length txt files. It is licensed under the apache 2 license. It can be downloaded from:

http://sourceforge.net/projects/pzfilereader

Paul Zepernick

Problem with getDouble() We use the Java method getDouble() to get numeric values. Up to now it worked properly but suddenly we got false values, like 49066.429000000004 for the true value 49066.429. Is this a bug?Location: http://www.jguru.com/faq/view.jsp?EID=809335 Created: Mar 23, 2002 Author: Joe Sam Shirah (http://www.jguru.com/guru/viewbio.jsp?EID=42100) Question originally posed by Robert Hares (http://www.jguru.com/guru/viewbio.jsp?EID=780629

First, let me assure you that something has changed, whether driver, database column definition, or database update. Even so, you were just lucky in the past. Some numbers can't be properly represented in binary and using floats/doubles for fixed decimal values is a classic trap for programmers.

While it doesn't help much at this point, it does highlight the value of proper planning for database definition and manipulation. The column should be defined as NUMERIC or DECIMAL, with the expected scale ( decimal point digits ) and get/setBigDecimal() should be used for retrieval and update.

Comments and alternative answers

Trick to handle it in the Java source if DB modification is not available Author: Yilmaz Mete (http://www.jguru.com/guru/viewbio.jsp?EID=1256251), Aug 2, 2005Floating Point arithmetic is always tricky, this is due to the nature of not being able to represent fp's using binary arithmetic. One may (NOT NECESSARILY) lose the precision, so Comparing fp's one must have extra guards.

Here is how I usually handle, 1st multiply the fp by the 10 to the power precision, 2nd round the number from the previous multiplication 3rd divide by integer 10 to the power precision

Page 206: Jdbc Faq From Jguru

double getDoubleInDesiredFormat(double fp, int precision_required){

int power_of_ten = 10^(precision_required)return Math.round(fp*power_of_ten) / power_of_ten;}

How can I know when I reach the last record in a table, since JDBC doesn't provide an EOF method?Location: http://www.jguru.com/faq/view.jsp?EID=809342 Created: Mar 23, 2002 Author: Yusuf Dönmez (http://www.jguru.com/guru/viewbio.jsp?EID=758654) Question originally posed by Juan José Gonzalez (http://www.jguru.com/guru/viewbio.jsp?EID=762739

You can use last() method of java.sql.ResultSet, if you make it scrollable.

Joe Sam Shirah adds: You can also use isLast() as you are reading the ResultSet.

One thing to keep in mind, though, is that both methods tell you that you have reached the end of the current ResultSet, not necessarily the end of the table. SQL and RDBMSes make no guarantees about the order of rows, even from sequential SELECTs, unless you specifically use ORDER BY. Even then, that doesn't necessarily tell you the order of data in the table.

If you are really looking for something that tells you the last ( in this case, latest ) data, you probably need something in a key ( or sequence, date/time, etc ) that provides that information on an ORDER BY basis.

Comments and alternative answers

next() Author: Terry Laurenzo (http://www.jguru.com/guru/viewbio.jsp?EID=706411), Mar 25, 2002Assuming you mean ResultSet instead of Table, the usual idiom for iterating over a forward only resultset is: ResultSet rs=statement.executeQuery(...);while (rs.next()) { // Manipulate row here}

Whan happens when I close a Connection application obtained from a connection Pool? How does a connection pool maintain the Connections that I had closed through the application? Location: http://www.jguru.com/faq/view.jsp?EID=837869 Created: Apr 14, 2002 Author: Christopher Koenigsberg (http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by Pankaj Johri (http://www.jguru.com/guru/viewbio.jsp?EID=731309

Page 207: Jdbc Faq From Jguru

It is the magic of polymorphism, and of Java interface vs. implementation types. Two objects can both be "instanceof" the same interface type, even though they are not of the same implementation type.

When you call "getConnection()" on a pooled connection cache manager object, you get a "logical" connection, something which implements the java.sql.Connection interface.

But it is not the same implementation type as you would get for your Connection, if you directly called getConnection() from a (non-pooled/non-cached) datasource.

So the "close()" that you invoke on the "logical" Connection is not the same "close()" method as the one on the actual underlying "physical" connection hidden by the pool cache manager.

The close() method of the "logical" connection object, while it satisfies the method signature of close() in the java.sql.Connection interface, does not actually close the underlying physical connection.

Comments and alternative answers

In addition Author: Steven Martin (http://www.jguru.com/guru/viewbio.jsp?EID=430104), Apr 15, 2002Typically a connection pool keeps the active/in-use connections in a hashtable or other Collection mechanism. I've seen some that use one stack for ready-for-use, one stack for in-use.

When close() is called, whatever the mechanism for indicating inuse/ready-for-use, that connection is either returned to the pool for ready-for-use or else physically closed. Connections pools should have a minimum number of connections open. Any that are closing where the minimum are already available should be physically closed.

Some connection pools periodically test their connections to see if queries work on the ready-for-use connections or they may test that on the close() method before returning to the ready-for-use pool.

Re: A question Author: Roberto Surdich (http://www.jguru.com/guru/viewbio.jsp?EID=1028690), Feb 20, 2003How many active connections should a databade see once a connection pool has been opened?I mean, only one connection (the pool itself) at any time, or the number of "logical" active connections in that moment?

Re[2]: A question

Page 208: Jdbc Faq From Jguru

Author: Steven Martin (http://www.jguru.com/guru/viewbio.jsp?EID=430104), Feb 20, 2003The database would see the number of active physical connections. It has no acknowledgement that a connection comes from a raw connection or through a connection pool. The only difference I've seen is you often need to increase the statement cache on Oracle since you are reusing the same connection.

What is the best way to generate a universally unique object ID? Do I need to use an external resource like a file or database, or can I do it all in memory? Location: http://www.jguru.com/faq/view.jsp?EID=1030397 Created: Nov 25, 2002 Modified: 2003-02-28 08:01:34.258Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by Andy Brown (http://www.jguru.com/guru/viewbio.jsp?EID=1027054

[I need to generate unique id's that will be used for node 'ID' attribute values within XML documents. This id must be unique system-wide. The generator must be available to a number of servlets that add various node structures to my XML docs as a service. What is the best way to tackle this? The 'possible' ways I can see:

Keep the maximum ID value in a flat-file where the service would read it upon start-up and increment it. Upon shutdown or failure, it would write the latest max id to the file.

Calculate the max id by searching the XML itself. This will be tougher since XML requires an alpha-numeric value (not strictly numeric).

Use a database (MySQL) with a two-field table where one field is the incremental counter.

I just have this feeling that none of the above are the most efficient ways of doing this.

Regards, -Andy]

There is an additional way to do that that doesn't rely on an external file (or database) like the one you have presentred. If has been presented in the EJB Design Patterns book, written by Floyd Marinescu, and available in a pdf format for free from the given link.

The suggested solution is based on the UUID for EJB pattern, that comes out from this question:

How can universally unique primary keys can be generated in menory without requiring a database or a singleton?

Without enetring in the specifics (you can fully check out the pattern by reading the appropriate chapter), the solution is to generate a 32 digit key, encoded in hexadecimal composed as follows:

1: Unique down to the millisecond. Digits 1-8 are are the hex encoded lower 32 bits of the System.currentTimeMillis() call.

Page 209: Jdbc Faq From Jguru

2: Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit integer of the underlying IP address.

3: Unique down to the object in a JVM. Digits 17-24 are the hex representation of the call to System.identityHashCode(), which is guaranteed to return distinct integers for distinct objects within a JVM.

4: Unique within an object within a millisecond. Finally digits 25-32 represent a random 32 bit integer generated on every method call using the cryptographically strong java.security.SecureRandom class.

[See also the following FAQs:

I need to generate a GUID and have seen suggestions about using an RMI server but nothing about how to actually generate the GUID itself.

What is the best way to provide a unique identifier as a primary key that will work in a database independent manner? I'm looking for functionality similar to Oracle's proprietary MY_SEQ.NEXTVAL.

How do I automatically generate primary keys? and the original thread: What is the best way to implement a system-

wide object ID generator?

- Alex Chaffee] Comments and alternative answers

Random class Author: P Manchanda (http://www.jguru.com/guru/viewbio.jsp?EID=344357), Feb 28, 2003Hi,Try using the java.util.Random class to generate random numbers that can be used as IDs.

Re: Random class Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727), Feb 28, 2003Hi,java.util.Random will generate random numbers, not unique numbers.

Re[2]: Random class Author: Prashanth Nandavanam (http://www.jguru.com/guru/viewbio.jsp?EID=818802), Apr 24, 2003Look at the JUG class by Tatu Saloranta: http://www.doomdark.org/doomdark/proj/jug/index.html It is based on the IETF UUID drafts, and works wonderfully.

Re: Random class Author: Nathan Ciliberto (http://www.jguru.com/guru/viewbio.jsp?EID=1139136), Jan 14, 2004You can also use some built-in java classes:

Page 210: Jdbc Faq From Jguru

java.rmi.server.UID or java.rmi.dgc.VMID

I'm guessing the UID class is the one you want though.

(BTW,you don't need to use rmi nor know anything about rmi to use these classes)

-Nathan

Making it Faster Author: Kimbo Mundy (http://www.jguru.com/guru/viewbio.jsp?EID=1120338), Oct 8, 2003It seems to me that you could speed up the algorithm above by modifying step #4. Instead of computing the random number every time, just compute it the first time, and then increment it after that. 2 different JVMs should still just have a 1 in 4 billion chance of overlap.

Re: Making it Faster Author: Scott Carlson (http://www.jguru.com/guru/viewbio.jsp?EID=1085622), Oct 8, 2003There are two reasons to use the random number instead of incrementing your last. 1. The number would be predictable and, depending on what this is used for, you could be opening up a potential security issue. This is why ProcessIDs are randomized on some OSes (AIX for one). 2. You must synchronize on that counter to guarantee that your number isn't reused. Your random number generator need not be synchronized, (though its implementation may be).

There are Three possible ways Author: Narayana Prasad (http://www.jguru.com/guru/viewbio.jsp?EID=1142103), Jan 29, 20041) If ur using Oracle You can create a sequence ,by which u can generate unique primary key or universal primary key. 2) U can generate by using random nunmbers but u may have to check the range and check for unique id. ie random number generate 0.0 to 1.0 u may have to make some logic which suits ur unique id 3) Set the maximum value into an XML file and read that file at the time of loding ur application from xml . thanks and regards prasad

UUID and Random IDs Author: Wesley Theobalds (http://www.jguru.com/guru/viewbio.jsp?EID=1165144), Apr 22, 2004Hi, I've just finished implementing the Sequence Block pattern a la Marinescu using a Session bean and an entity bean representing the sequence, and its working well. Using a UUID makes life harder for any Data analysis further down the line, having to enter a 32 bit number for the key for any ad hoc SQL queries you may need to write, and I've often found it helpful to have an incremental key as it indicates when the record was created in the absence of a timestamp.

Page 211: Jdbc Faq From Jguru

hashcode isn't unique Author: x x (http://www.jguru.com/guru/viewbio.jsp?EID=1174058), May 27, 2004> System.identityHashCode(), which is guaranteed to return > distinct integers for distinct objects within a JVM. Sorry, but it isn't true. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4990451 Tomas

Millisecond overlap Author: Thomas Paré (http://www.jguru.com/guru/viewbio.jsp?EID=1238395), Apr 14, 2005

Thanks for the very interesting pointer on 'Ejb design patterns'. I've read the implementation details and found something troublesome.

In step 1 : "Unique down to the millisecond. Digits 1-8 are are the hex encoded lower 32 bits of the System.currentTimeMillis() call". Only the lower 32 bits of time are considered, which makes the uniqueness of that part only valuable for a period of 50 days. Looks like a serious issue.