Java & Database

42
Java & Database Advance Java Programming II Nacha Chondamrongkul School of Information Technology Mah Fah Luang University

description

Java & Database. Advance Java Programming II . Nacha Chondamrongkul School of Information Technology Mah Fah Luang University. Agenda. Architecture Overview SQL on MySQL JDBC Development Connection Management Building Statement Object Using ResultSet Object Batches - PowerPoint PPT Presentation

Transcript of Java & Database

PowerPoint Presentation

Java & DatabaseAdvance Java Programming II

Nacha ChondamrongkulSchool of Information TechnologyMah Fah Luang UniversityAgendaArchitecture OverviewSQL on MySQLJDBC DevelopmentConnection ManagementBuilding Statement ObjectUsing ResultSet ObjectBatchesLimit the resultTransaction

2JDBC OverviewAcronym stands for Java Database ConnectivityJDBC is simply Application Programming Interface (API) that allow you to manipulate the database

JDBC is middleware or intermediary between Java language and database

Can be used from Different type of executable such as applications, applet, Servlet, JSP

What about ODBCOpen Database Connectivity, is an API developed by Microsoft to allow access to databases.

There are drawbacks to using ODBC in the process of accessing a database through Java.

The primary drawback is that the code that implements ODBC is based on the C language and uses a large number of generic pointers. A number of problems occur with interfacing Java to C code, as well as the performance issues.ArchitectureClientJava ApplicationJava AppletServerMySQL DatabaseJDBCTwo-Tier Deployment Model: Client-serverArchitecture [2]ClientJava ApplicationJava AppletServerMySQL DatabaseJDBCThree-Tier Deployment ModelBusinessServlet, EJBJDBC DriverEach Database server require a specific JDBC driverClientJava ApplicationJava AppletMySQL DatabaseOracleDatabaseConnector/JOracle JDBC DriverNeed to compliable with JDBC SpecificationJDBC DriverThe JDBC are consisted of

Core API all classes/interfaces in package java.sqlOptional API - all classes/interfaces in package javax.sql

JDBC InterfaceMySQLConnector/JDriverManagerThese interface are in java.sql packageConnectionStatementPreparedStatementCallableStatementResultSetResultSetResultSetJava.sql Packagejava.sql.DriverManager: The DriverManager class is used to manage all Driver objects.

java.sql.Driver: The Driver interface is implemented by all vendor drivers so that they can be loaded by a static class called DriverManager. The Driver object will automatically create an instance of itself and register with DriverManager.

java.sql.Connection: The Connection interface provides a method for creating a connection to a specific database. All SQL is executed in the context of a Connection object.

Java.sql Package [2]java.sql.Statement: The Statement interface is probably one of the most important interfaces in the JDBC specification. All SQL statements are executed through a Statement object. Each Statement object returns single ResultSet objects.

java.sql.PreparedStatement: The PreparedStatement interface provides an object for executing precompiled SQL statements against the connected database.

java.sql.CallableStatement: The CallableStatement interface is used to execute stored procedures if supported on the database. Parameters are allowed with the interface as well as escape syntax.

Java.sql Package [3]java.sql.ResultSet: A ResultSet interface is designed to represent a Result-Set produced from a query of the database. An internal cursor points to the current row of data, and it can be pointed before and after the data. Methods are used to move the cursor to different rows in the ResultSet.

By default, the ResultSet isn't updatable, but can be made both scrollable and updatable.Interface linkConnectionStatementPreparedStatementCallableStatementResultSetcreateStatementexecuteQueryWhere to get Mysqlhttp://dev.mysql.com/downloads/

Where to get JDBC Driver

Google MySQL JDBC DriverSQL on mySQLJava & DatabaseCreate TableThe table is where all of the data is stored in a particular database. Because we are working with a relational database system, the data is stored in rows and columns.create table employee (emp_id int primary key,firstname varchar(64),lastname varchar(64),ts timestamp);Table nameColumn nameData typeIndicate this column is primary keyInsertWith our database and table defined, we need to populate it with sample data.Heres the data that we would like to get into the table:emp_idfirstnamelastname1001JohnSmith1002TimothyNew1003MartinGrosINSERT INTO employee VALUES(1001, John', Smith', now());INSERT INTO employee VALUES(1002, Timothy', New', now());INSERT INTO employee VALUES(1003, Martin', Gros', now());Table name to insertValues to insertSelectOnce youve inserted your data into a database, You can pull data from the database by using the SELECT command

SELECT * FROM employee;SELECT firstname,lastname FROM employee;SELECT firstname,lastname FROM employee WHERE firstname=John;SELECT * FROM employee ORDER BY firstname;SELECT firstname,lastname FROM employee WHERE firstname LIKE T%;Specify columnsWhere clause conditionSort the result by specified column19Updateif you want to change the data within a row, you can do this with the UPDATE commandUPDATE employee SET lastname='Neumann' WHERE emp_id='1002';

SELECT * FROM employee WHERE emp_id='1002';Specify columns and value to updateSpecify which row to be updatedDeleteWhen data is no longer needed in a database, you can use the DELETE command to remove a row.

DELETE FROM employee WHERE emp_id = 1003';Specify which row to be deletedShowSHOW Tables - list all tables name in the connected database

SHOW COLUMNS FROM display information about columns of a table SHOW COLUMNS FROM employee;

JDBC DevelopmentJava & DatabaseLoading Connector/J DriverPut the jar file mysql-connector-java-xxxxx-bin.jar into JVM class path

Once it finds the file, the code executes the newInstance() method to instantiate a new object from the Driver class.

During the instantiation, the Driver will register itself with a static class called DriverManager, which is responsible for managing all JDBC drivers installed on the current systemConnection Making ApplicationMySQLDriverManagerConnector/JConnection can be obtain from DriverManager class using the following methods

Connection getConnection(String URL);Connection getConnection(String URL, Properties info);Connection getConnection(String URL, String user, String password);Sample URL: //[:][/]jdbc:mysql://localhostjdbc:mysql://localhost/accountsjdbc:mysql://192.156.44.3/db_devjdbc:mysql://database.company.com/prodjdbc:mysql://database.company.com:4533/prodSample Making ConnectionUsing Properties

Properties prop = new Properties(); prop.setProperty("user","testuser"); prop.setProperty("password", "123");Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", prop);

OR

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "testuser","123");

Wrap Try / Catch around these statement related to JDBC StatementThe first step in getting data from the MySQL database is to build a Statement object.

Statement Object can be created from connection object

Statement statement = connection.createStatement();

27Execute SQLThe Statement object includes several types of query methodsOne of that methods is executeQuery()The method return result as ResultSet object

ResultSet rs = statement.executeQuery( "SELECT * FROM employee");ResultSetThe ResultSet object is the primary storage mechanism for the rows returned from a query on the MySQL database.

Conceptually, the ResultSet object looks like an adjustable two-dimensional arrayemp_idfirstnamelastname1001JohnSmith1002TimothyNew1003MartinGrosInternal CursorPositioning CursorChecking the cursor position by the following method

boolean isBeforeFirst() - return true if the cursor is before the first row.

boolean isAfterLast() - return true if the cursor is after the last row.

You can use getRow() method to return the current row number from the ResultSetMoving CursorThe method moves the internal cursor to a specific row in the ResultSet.boolean absolute(int rows)

next() move the cursor to the next row, return true when next row existed, false when next row doesnt existed

prev() move the cursor to the previous row, return true when previous row existed, false when previous row doesnt existed

Getter MethodThe result set contains the number of getter method to retrieve the value of specified column of the row where the cursor is currently pointing at, such as

getString(String columnName)getInt(String columnName)getDouble(String columnName)getDate(String columnName)..

Display the query resultResultSet rs = statement.executeQuery("SELECT * FROM employee");

while(rs.next()){System.out.println(rs.getString("firstname"));}Execute Query w/o ResultThe operations of insert, delete, and update are considered no-result queries because they dont return a ResultSet object after being executed.

We use method executeUpdate()

statement.executeUpdate("INSERT INTO employee VALUES (1004, 'Michael', 'Miller', now())");

statement.executeUpdate("DELETE FROM Employee WHERE emp_id='1004'");Batching The idea is to provide a mechanism where a large number of updates can be performed in a group with the hopes of better performance from the driver and database server.

void clearBatch()Clears the current batch queue.void addBatch(String SQL)Adds the SQL string to the batch queue.int[] executeBatch()Executes the batch queue.

Sample Batchingstatement.addBatch("INSERT INTO employee VALUES( 1005, 'Michael', 'Miller', now())");statement.addBatch("INSERT INTO employee VALUES( 1006, 'Natasha', 'Smith', now())");

statement.addBatch("UPDATE employee SET lastname='Miller' WHERE emp_id='1002';");

int result[] = statement.executeBatch();Close everythingAlways close connection / statement / ResultSet after finishing using them, otherwise the application will run out of connection.

try{

.} catch (SQLException e) {e.printStackTrace();} finally {try {if(connection != null)connection.close();if(statement != null)statement.close();if(rs != null)rs.close();} catch (SQLException e) {e.printStackTrace();}}

Limit ResultIf you have massive amount of rows (such as2,000,000 rows) you should consider limit result in ResultSet for performance reason

setMaxRows() -specify the total number of rows that can bereturned from a single query against a databasesetFetchSize() allow application to process smaller subsets of data at a timeTransactionATOMIC - With Series of update statement, When one update statement need to be done along with other update statements , otherwise do not perform it at all.

connection.setAutoCommit(false);

statement = connection.createStatement();

statement.executeUpdate("UPDATE employee SET lastname='Gros' WHERE emp_id='1005'");

statement.executeUpdate("UPDATE employee SET lastname='Taylor' WHERE emp_id='1006'");

connection.commit();

All or NothingIf not call, the previous statement doesnt effect any changes on databaseExercise I Write the source code that

- get user input for a employeeIDFirstnameLastname

Insert a record to employee table

Query all rows from employee and show ID, firstname, lastname of each row to the user

40With Factory PatternFactory ClassEmployee ClassMain ProgramCreateReadUpdateDeletePerform CRUDAll SQL lives herePlain Old Java Object(POJO)Exercise IICreate command line program which that allow user toAdd new record of customerList all customerDelete customer by given idSearch customer by name

ColumnsData TypeIDintFirstnamevarchar(64)Lastname varchar(64)Addressvarchar(64)Cityvarchar(64)Countryvarchar(64)Student