of 22 /22
Advanced Java Class Java Database Connectivity (JDBC)

Advanced Java Class

  • Author

  • View

  • Download

Embed Size (px)


Advanced Java Class. Java Database Connectivity (JDBC). Question from yesterday. Please talk a little about “security.policy” java –Djava.security.policy=policyfilename It will look for a default file in java.home/lib/security/java.policy Or you can supply your own: - PowerPoint PPT Presentation

Text of Advanced Java Class

  • Advanced Java ClassJava Database Connectivity(JDBC)

  • Question from yesterdayPlease talk a little about security.policyjava Djava.security.policy=policyfilenameIt will look for a default file in java.home/lib/security/java.policyOr you can supply your own:java Djava.security.policy=policyfilenameExample: my RMISecurity.policy file:grant { permission java.net.SocketPermission "*:1024-65535","connect,accept";};Also, you can use the policytool program that comes with the JDK to write your own security file.See java.security.Permissions class for more documentation

  • Policy for Assignment 1aAs written in an email yesterday, your WebCrawler will only be tested on html pages that are xhtml pages. In other words, you may assume that the links will be well-formed.

  • PostGresQL SyntaxYou need to know a little PostGresQL syntax to set up your DB and use JDBCTypes: see p. 623, figure 9-6Also in postgresQL: money, text (among others)Documentation: http://www.postgresql.orgLook at \h and \? for command syntaxAt the command line:psqlpg_dump man psql

  • Common Table CommandsCREATE TABLE table_name (column_name1 column_type1, column_name2 column_type2, etc.);

    Can also specify a DEFAULT value, or other constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, etc.

    \dt (shows tables)

    \d table_name (describes that table)

    DROP TABLE table_name;

    ALTER TABLE table_name RENAME TO new_table_name;

  • Common Column CommandsALTER TABLE table_name

    ADD column_name column_type [constraints];

    ALTER column_name SET DEFAULT value;

    ALTER column_name DROP DEFAULT;

    RENAME old_column_name TO new_column_name;

  • Common Row CommandsINSERT INTO table_name values (42, 3, foo)

    INSERT INTO table_name (col2_name, col3_name) values (3, foo);

    UPDATE table_name SET col = expression [WHERE condition];

    DELETE FROM table_name [WHERE condition];

  • Common \ Commands\? Shows all \ commands\h shows help menu \h COMMAND_NAME shows help for a specific command\q quits psql program

  • Driver TypesJDBC-ODBC bridge (inefficient)Most efficient driver if all classes using db are on the db hostMost efficient driver if not all classes using db are on the db hostpure Java, and therefore platform independent

    A driver for your first project is linked from the assignment page.For many databases, there may be only one choice, not all four.

  • Basic use of java.sqlLoad driver classGet connection Get statementAsk statement to execute sql stringProcess results if needed Close Statement and Connection

  • Optional arguments for getting StatementScrollable? TYPE_FORWARD_ONLY [Default] (note error in text: TYPE_READ_ONLY)TYPE_SCROLL_INSENSITIVE [ignores changes made to ResultSet by other code]TYPE_SCROLL_SENSITIVE Concurrency?CONCUR_READ_ONLY [rs cant change while processing it]CONCUR_UPDATABLE [not allowed by some DB drivers]

  • Execution of SQL by Statementint Statement.executeUpdate(String sql);Returns number rows affectedGood for INSERT, UPDATE, and DELETE

    ResultSet Statement.executeQuery(String sql);Good for SELECTGood if only one ResultSet is returned

    boolean execute(String sql);Returns true if a ResultSet(s) was returnedGood if more than one ResultSet might be returnedVery rare to do this.

  • Processing Result SetsMove to appropriate row beforeFirst(), next())

    Process values at that rowget values (methods are named by type) update values [local], then updateRow() [db]deleteRow()insertRow()

  • Advanced Efficiency OptionsPrepared Statements [use if many sql statements vary only in the literal values] SEE NEXT SLIDE

    Stored ProceduresCreating them varies from db to db not covered in this classCan use them in Java via CallableStatementCan produce more than one ResultSet

    Use fewer ConnectionsIf single threaded program, open a Connection and keep it, rather than closing it and opening a new one constantlyConnection Pooling is provided by DataSource objects for J2EE

  • Prepared Statements Very Useful!PreparedStatement ps = Connection.prepareStatement(INSERT INTO my_table (col_a, col_b) VALUES (?, ?));ps.setString(1, foo); ps.setInt(2, 512);ps.executeUpdate() or ps.executeQuery();(note: indexing starts from 1)

  • Good Database ProgrammingProgram layers (i.e. Model-View-Persistence)Define mapping between Java Objects and Data ElementsUtilize optimizations and special powers of dbProgram transactions

  • Program Layers (and not just in JDBC)See p. 613, figure 9-1

    Conceptually clearer

    Layers of security


    Abstraction of implementations

  • Define mapping between Java Objects and Data ElementsRelationships between Relational Database Concepts and Object Oriented Programming ConceptsSee figure 9-2Mappings (see 9-4 and 9-5)One-to-one (use same ids)One-to-many (give each of the many a reference to the one, using a foreign key)Many-to-many (make another table just for the mappings this table will have 2 foreign keys)

  • Utilize optimizations and special powers of DBserial types DB can check for uniqueness of primary keyForeign key constraints signal error for impossible valuesSet up dependency rules for deletes and modifications (i.e. DB will automatically nix employee records when a department is deleted if the foreign key is defined with cascade deleteWARNING: if you depend on these too much, you may have difficulty switching Databases.

  • Program For TransactionsGoal:

    Atomic [all or nothing]

    Consistent [same each time you run it under same conditions]

    Isolated [independent of other transactions](several possible levels of isolation)

    Durable [permanent once commited]

  • Program For TransactionsImplementation

    Connection.setAutoCommit(false) [true by default]

    Connection.commit() or Connection.rollback()

    Note: can also rollback to Savepoints within a transaction, as of Java 1.4

  • Group Database TaskDraw and Entity Relationship diagram (see example on board) to show the structure of a DB for an online shopping application.Show Foreign and Primary KeysShow column names, SQL types, any restraints

    Classes in Application:Customer: Has name and address. Has one or more accounts.Account: has owner, balance, credit rating, value of last statement, and date of last payment.Order: Knows what account its owned by. Also has date opened, date closed, status, and total value. Has one or more Items, and associates them with the quantity ordered.Item: Has a part number, picture (image file), unit cost.Inventory: list of the items available for sale. Associates each Item with a quantity in stock.