Your SlideShare is downloading. ×
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Jdbc
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Jdbc

175

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
175
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Java II--Copyright © 2001-2004 Tom Hunter
  • 2. Java II--Copyright © 2001-2004 Tom HunterChapter 18JDBC
  • 3. Java II--Copyright © 2001-2004 Tom HunterBackground: databases
  • 4. Java II--Copyright © 2001-2004 Tom Hunter• Types of databases--Hierarchical--Relational--Object RelationalBackground: databases
  • 5. Java II--Copyright © 2001-2004 Tom Hunter• Types of databases--Hierarchical-the first database, invented by IBM,called IMS.Background: databases
  • 6. Java II--Copyright © 2001-2004 Tom Hunter• Types of databases--Relational-the most common, invented by IBM butfirst marketed by Oracle. Examples:OracleDB2SybaseAccess*Background: databases
  • 7. Java II--Copyright © 2001-2004 Tom Hunter• Types of databases--Object Relational-uncommon, attempts to placeobjects in the database.Background: databases
  • 8. Java II--Copyright © 2001-2004 Tom HunterRelational Databases
  • 9. Java II--Copyright © 2001-2004 Tom HunterRelational Databases: Entity Integrity• Unit of the Table, smallest unit in a relational database• For a table to be useful, it must enforce Entity Integrity.Entity Integrity—each row in a table can be locatedby using its Primary Key.1stLaw of Relational DatabasesEach row in a table must have an attribute(s) thatuniquely locates one row. Values in this attribute must beunique.2ndLaw of Relational DatabasesThe primary key attribute(s) cannot contain a nullvalue
  • 10. Java II--Copyright © 2001-2004 Tom HunterRelational Databases: Entity Integrity• Here is a sampletable, USERID LastName FirstName Age1 Jones Sam 322 Jones Angela 273 Smith Ann 224 Doe Jack 44Primary Key—must uniquelyidentify a row. No nulls allowed.
  • 11. Java II--Copyright © 2001-2004 Tom HunterRelational Databases: Entity Integrity• Here is another sampletable, CODECode MessageA Bill PaidB Bill OverdueC Account written offD Account closedPrimary Key—must uniquelyidentify a row. No nulls.
  • 12. Java II--Copyright © 2001-2004 Tom HunterRelational Databases: Referential Integrity• A “foreign key” is when the primary key of one table isrepeated in a second table as a non primary key.• Using foreign keys, or “referential integrity” allows us tolink tables.3rdLaw of Relational DatabasesIf you link two tables with a foreign key, any valuespresent in the foreign-key attribute column must link backto existing primary-key values.4thLaw of Relational DatabasesIt is okay for a foreign key column to contain nulls.
  • 13. Java II--Copyright © 2001-2004 Tom HunterID LastName FirstName Age1 Jones Sam 322 Jones Angela 273 Smith Ann 224 Doe Jack 44Relational Databases: Referential IntegrityID LastName FirstName Age Code1 Jones Sam 32 A2 Jones Angela 27 B3 Smith Ann 22 A4 Doe Jack 44This is the primary key for another table. This column cancontain nulls. However, any values present must exist in thetable that is referred to. This is a “foreign key”.
  • 14. Java II--Copyright © 2001-2004 Tom HunterSQL Basics
  • 15. Java II--Copyright © 2001-2004 Tom HunterSQL Basics: Structure of a SQL Statement• When accessing a relational database, you must use the“Structured Query Language” (SQL)• Several types of SQL:queries—for asking questionsupdates—for making changesinsert—for adding new dataDDL—for creating tables
  • 16. Java II--Copyright © 2001-2004 Tom HunterSQL Basics: Structure of a SQL Statement• Queries: SELECT statementsSELECT columns FROM table;Or if we wish not to select all columns:SELECT columnsFROM tableWHERE expression
  • 17. Java II--Copyright © 2001-2004 Tom HunterSQL Basics: Structure of a SQL Statement• Queries: SELECT statementsSELECT FirstName, LastNameFROM USERWHERE ID = 2;
  • 18. Java II--Copyright © 2001-2004 Tom HunterSQL Basics: Structure of a SQL Statement• Updates: UPDATE statementsUPDATE table SET column = value;Example:UPDATE tableSET LastName = ‘Jones’WHERE ID = 2;
  • 19. Java II--Copyright © 2001-2004 Tom HunterSQL Basics: Structure of a SQL Statement• Insert: INSERT statementsINSERT INTO table VALUES(values);Example:INSERT INTO USERVALUES( ‘6’, ‘Anderson’, ‘Joe’, 44, ‘A’)
  • 20. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics:Connection
  • 21. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: Connection• The first step toward connecting to a database is getting adatabase connection.• Before you can get a connection, you need a databasedriver.• The driver makes the connection between a particulardatabase and our Java program.• These drivers are individual to each vendor’s database.
  • 22. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: Connection• To make sure your driver is available, you use thefollowing:Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );• The above statement will merely ensure that the Java classcontaining the driver is available to our program.
  • 23. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: Connection• The statement below results in a connection to the database.import java.sql.Connection;…Connection con = DriverManager.getConnection( url, user, pass );• To create a connection using this method, it is necessary topass three arguments to the method:usernamepasswordurl
  • 24. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: url• The Url is a special string of characters that finds thedatabase.• Here is a sample Url:url = jdbc:oracle:thin:@myhostname:1521:OurDBjdbc:oracle:thin:@ —This is database specificmyhostname —This is the name of the host where the database is located.1521 —This is the port on the host where the database is listening.OurDB —This is the name of the database.
  • 25. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: Connection• The DriverManager is convenient but not scalable.import java.sql.Connection;…Connection con = DriverManager.getConnection( url, user, pass );• Once you have opened a connection to the database, youmust realize this is a resource.• You mustYou must closeclose the connection you opened.the connection you opened.
  • 26. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: Statements• After you have a connection, you need to create a statement.• There are three alternatives, each with plusses and minuses.Statement—used for a query that will be executed once.PreparedStatement—used for a query that will be executed multiple timesCallableStatement—used for a query that executes a stored procedure.
  • 27. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: Statement• The Statement object is the easiest to work with.• The Statement object is the least efficient.String query = “SELECT * FROM MYTABLE WHERE ID = 2”;Connection con = DriverManager.getConnection( url, user, pass );Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery( query );
  • 28. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: PreparedStatement• The PreparedStatement object requires more work.• The PreparedStatement object is the most efficient.• The query contains a question mark that is replaced.String query = “SELECT * FROM MYTABLE WHERE ID = ?”;Connection con = DriverManager.getConnection( url, user, pass );PreparedStatement pstmt = con.prepareStatement( query );pstmt.setString( 1, 494 );ResultSet rs = pstmt.executeQuery();This line substitutes 494 for thefirst question mark in the query.
  • 29. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: CallableStatement• The CallableStatement object is only appropriatefor calling a stored procedure.• The syntax of how you call the stored procedure isdatabase specific.String call = “{ call myProcdure }”;Connection con = DriverManager.getConnection( url, user, pass );CallableStatement cstmt = con.prepareCall( call );ResultSet rs = cstmt.executeQuery();
  • 30. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: ResultSet• The ResultSet object receives the results of the query.String query = “SELECT COL1, COL2 FROM MYTABLE WHERE ID = 2”;Connection con = DriverManager.getConnection( url, user, pass );Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery( query );while( rs.next() ){String myCol1 = rs.getString( “COL1” );String myCol2 = rs.getString( “COL2” );}next() returns true while there are resultsThese correspond tocolumns in the originalquery.
  • 31. Java II--Copyright © 2001-2004 Tom HunterJDBC Basics: ResultSet• No matter which kind of statement you choose, theResultSet object is used the same way.• As with the Connection object, you must closeclose yourResultSet!
  • 32. Java II--Copyright © 2001-2004 Tom Huntertry{String output = null;String query = “SELECT username from MYTABLE where pass=‘foo’ ”;Connection con = DriverManager.getConnection( url, us, pass);Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery( query );while( rs.next() ){output = rs.getString( “username” );}rs.close();stmt.close();con.close();}catch( SQLException sql ){System.out.println( “Uh oh…” );}You must close thesethree items, in the reverseorder that you openedthem!
  • 33. Java II--Copyright © 2001-2004 Tom HunterDataSource
  • 34. Java II--Copyright © 2001-2004 Tom HunterDataSource• As I said, the DriverManager is not the best choice fora production system. It doesn’t scale well.• A better alternative is using a DataSource.• A DataSource offers connection poolingconnection pooling, where newconnections are not thrown away but are instead set aside forthe next time someone needs a connection.
  • 35. Java II--Copyright © 2001-2004 Tom HunterDataSource: Need to Lookup in JNDI• To use a DataSource, it is necessary to perform a lookup ofthe resource in something called JNDI[ JNDI = Java Naming and Directory Interface ]• JNDI stores a list of namesnames that associate with resourcesresources
  • 36. Java II--Copyright © 2001-2004 Tom HunterDataSource: Need to Lookup in JNDI• First we need to create an InitialContext so we canlookup that DataSourceContext ctx = new InitialContext();String dbJNDI = "java:comp/env/OracleJDBC";DataSource ds = (DataSource) ctx.lookup( dbJNDI );Connection con = ds.getConnection();This is the name Iassigned to theDataSource when Icreated it. Here, I’m justlooking it up under thename I stored it
  • 37. Java II--Copyright © 2001-2004 Tom HunterDataSource:Complexity of setup• Using a DataSource is very valuable because it allowsconnection pooling.• The downside of using a DataSource is the complexity of itssetup. Also, each Application Server vendor has its ownunique setup. You will need to learn these*.

×