JDBC  «Prev  Next »

Lesson 7Connecting to a data source
Objective Write code to connect to a JDBC data source

Connecting to Data Source

JDBC Connection Code
open JDBC Connection
  1. import the IO classes
  2. import the servlet classes
  3. import the SQL classes
  4. define the HelloDatabase class
  5. declare the member variable to hold the connection reference
  6. this begins our override of init()
  7. delegate the work to the super class
  8. start a try/catch block
  9. load and register the JDBC/ODBC bridge as our JDBC driver
  10. open a connection to the DSN
  11. this exception might be thrown by the Class.forName() call
  12. this message will appear on the console where you started the Web server
  13. this exception might be thrown by the getConnection() call
  14. the exception might be thrown by the getConnection() call
  15. this message will appear on the console where you started the Web server"
  16. begins our override of destroy()
  17. start a try/catch block
  18. close the database connection
  19. the exception might be thrown by the close() call
  20. this message will appear on the console where you started the Web server"
  21. the remainder of the servlet was omitted for space reasons

The four key points in this code are:

  1. Import the SQL classes so you can use Connection easily.
  2. Make the connection reference a member variable of the servlet class.
  3. Load the driver by creating the class. The name is always "sun.jdbc.odbc.JdbcOdbcDriver" if you are using the bridge.
  4. Open the database connection by calling getConnection. The first parameter is always
    "jdbc:odbc:YOURDSN" with YOURDSN replaced by the DSN to which you want to connect. The second and third parameters specify an id and password.
Code and DSN tab
Code and DSN tab

In the next lesson, you will learn how to read from a data source.