Data Base Connectivity From JAVA Creating a Java
Data Base Connectivity From JAVA Creating a Java program that access my. SQL is not difficult. Your Java program must can a number of functions to facilitate easy access to an external database. They include: u u u Importing the correct packages that deal with SQL. Creating a connection to the database. Creating an initialization file, so that it is easy to point to another database. Closing the connection to the database when you are complete. Writing code to perform: inserts, updates, deletes and selects from the database. Programming in java with databases is simpler if you create objects to perform the actions and allow programs to call those objects. This allows the database to be changed without requiring the main programs to be modified.
Data Base Connectivity From JAVA Creating a Java program that access my. SQL is not difficult. Importing the correct packages that deal with SQL. The following are the packages you need to include: import import java. sql. Connection; // Java’s interface to SQL java. sql. Driver. Manager; // Loads the appropriate SQL driver java. sql. SQLException; // Handles errors from the database java. util. Properties; // Configuration file to load the db. properties file java. util. logging. Level; // Logs information java. util. logging. Logger; // Logs information
Data Base Connectivity From JAVA Creating a Java program that access my. SQL is not difficult. Creating a connection to the database public Database. Connection () throws Scheduler. Exception { logger = Logger. get. Logger(this. get. Class(). get. Name ()); //Properties contains all the attributes in the file //load them into an object and the copy out the attributes Properties props = new Properties(); try { props. load(get. Class(). get. Resource. As. Stream("db. properties ")); final String driver = props. get. Property("driver "); final String url = props. get. Property("url "); final String user = props. get. Property("user "); final String pass = props. get. Property("pass "); Class. for. Name(driver). new. Instance (); connection", //connect to the database connect = Driver. Manager. get. Connection(url , user, pass); } catch (Exception ex) { logger. log(Level. SEVERE , "Unable to create database connection", ex); throw new Scheduler. Exception("Unable to create database ex); } }
Data Base Connectivity From JAVA Creating an initialization file, so that it is easy to point to another database. The initialization file must contain the: driver, url, user name, and password db. properties file driver = com. mysql. jdbc. Driver url = jdbc: mysql: //landsend. cs. drexel. edu/scheduler user = jsalvage pass = dbwiz
Data Base Connectivity From JAVA When an object goes out of scope it is important to close the connection. First check if the database connection is still valid, if so close it and set it to null, if not throw an error. protected void finalize() { if (connect != null) { try { connect. close(); connect = null; } catch (SQLException ex) { logger. log(Level. SEVERE, "Unable to close database connection", ex); } }
Data Base Connectivity From JAVA ADDING A RECORD TO THE DATABASE Inserting data into a database uses an SQL INSERT statement, but requires some additional formatting. A Perpared. Statement is an object that allows the execution of SQL statements from java. It allows the SQL to be written with arguments that can then be set via a Set. String or Set. Int method. Observe declaring a Prepared. Statement stm that inserts 5 values into the Course table: final Prepared. Statement stm = connect. prepare. Statement( "INSERT INTO Course VALUES(? , ? , ? )"); To set each argument, call the appropriate method set. String or set. Int with two parameters. The first is the argument you wish to set in the Prepared. Statement and the second is the value of that argument. Therefore, if you wish to set the first argument to “Computer Science”, use the following method call: stm. set. String(1, “Computer Science”); Similairly, to set the third argument to the 3 credits, use the following method call: stm. set. Int(3, 3);
Data Base Connectivity From JAVA ADDING A RECORD TO THE DATABASE To execute the statement, close it, and check to see it executed properly, use the following sequence of calls: int n = stm. execute. Update(); stm. close(); if (n != 1) throw new Scheduler. Exception("Unable to add course"); } catch (SQLException ex) { logger. log(Level. SEVERE, "add. Student", ex); throw new Scheduler. Exception("Unable to add course", ex); } } Executing the SQL command is simply a matter of calling the execute. Update method of the Prepared. Statement object.
Data Base Connectivity From JAVA RETRIEVING RECORDS FROM A DATABASE Retrieving data from a database uses an SQL SELECT statement, but requires some additional formatting. Again we will use the Prepared. Statement to hold the SQL command. The results of the query will be stored in a Result. Set object and then each record is copied to an array list object in Java. The Prepared. Statement is assigned the SQL Select statement to execute. Unlike the insert, no arguments are needed. While the SELECT is hardcoded here, it could just as easily been built in a string variable and passed dynamically. See the following example: final Prepared. Statement stm = connect. prepare. Statement( "SELECT * FROM Course ORDER BY dept, num");
Data Base Connectivity From JAVA To execute the SELECT statement a similar call as with INSERT, except here we need to store the result of the query in a Result. Set Object. Observer the following code: final Result. Set result = stm. execute. Query (); Once the Result. Set is populated, we want to move the values from the result set to an Array. List. This can be done a number of ways, observe an example: final List<Course> courses = new Array. List<Course>(); while (result. next ()) (result. next()) courses. add(to. Course(result )); Finally, once all the rows are copied, close the Result. Set and close the database statement. result. close(); stm. close();
Data Base Connectivity From JAVA RETRIEVING RECORDS FROM A DATABASE WITH A CONDITION Just as we could set parameters in an INSERT statement, a SELECT statement can be set up to use parameters for the values to limit the predicate with. Again we will use the Prepared. Statement to hold the SQL command. The results of the query will be stored in a Result. Set object and the single record will be added to our course object. The only real difference is using ? in the WHERE clause of the SELECT statement where the parameters will be placed. Observe the following statement which creates a SELECT statement final Prepared. Statement stm = connect. prepare. Statement( "SELECT * FROM Course WHERE dept = ? AND num = ? "); The parameters are set with the following statements: stm. set. String(1, dept); stm. set. Int(2, num); And then executed with the following statement: final Result. Set result = stm. execute. Query ();
Data Base Connectivity From JAVA DELETING RECORDS FROM A DATABASE WITH A CONDITION Deleting records from a SQL database isn’t very different in form than selecting data from a database. You must prepare the statement in the same manner, just instead of creating a SQL SELECT in the prepare. Statement object, you create a SQL DELETE Statement. Observe the following code which declares a DELETE statement that deletes course that match a department and course number: final Prepared. Statement stm = connect. prepare. Statement( "DELETE FROM Course WHERE dept = ? AND num = ? "); stm. set. String(1, dept); stm. set. Int(2, num); stm. execute. Update(); stm. close();
Data Base Connectivity From JAVA UPDATING RECORDS FROM A DATABASE WITH A CONDITION The updating of records in a database follows the same pattern as SELECT and DELETE. Observe the following code that sets the credits and name field of a course that matches the department and name: final Prepared. Statement stm = connect. prepare. Statement( "UPDATE Course SET credits = ? , name = ? , description = ? " + " WHERE dept = ? AND name = ? "); stm. set. Int(1, course. get. Credits()); stm. set. String(2, course. get. Name()); stm. set. String(3, course. get. Description()); stm. set. String(4, course. get. Department()); stm. set. Int(5, course. get. Number()); stm. execute. Update(); stm. close();
Data Base Connectivity From JAVA package edu. drexel. cs 350; import import java. sql. Connection; // Java’s interface to SQL java. sql. Driver. Manager; // Loads the appropriate SQL driver java. sql. SQLException; // Handles errors from the database java. util. Properties; // Configuration file to load the db. properties file java. util. logging. Level; // Logs information java. util. logging. Logger; // Logs information /** * Base class for those that use a database connection * * @author Sunny Huynh * @version 1. 0 * @since 1. 0 */ public abstract class Database. Connection { protected final Logger logger; protected Connection connect = null;
Data Base Connectivity From JAVA public Database. Connection () throws Scheduler. Exception { logger = Logger. get. Logger(this. get. Class(). get. Name ()); connection", Properties props = new Properties(); try { props. load(get. Class(). get. Resource. As. Stream("db. properties ")); final String driver = props. get. Property("driver "); final String url = props. get. Property("url "); final String user = props. get. Property("user "); final String pass = props. get. Property("pass "); Class. for. Name(driver). new. Instance (); connect = Driver. Manager. get. Connection(url , user, pass); } catch (Exception ex) { logger. log(Level. SEVERE , "Unable to create database connection", ex); throw new Scheduler. Exception("Unable to create database ex); } }
Data Base Connectivity From JAVA Driver specifies which backend database system to use In this case, we need a my. SQL driver since the database is my. SQL The URL specifies the location of the database as well as which database within my. SQL to use db. properties file driver = com. mysql. jdbc. Driver url = jdbc: mysql: //landsend. cs. drexel. edu/scheduler user = jsalvage pass = dbwiz
Data Base Connectivity From JAVA When an object goes out of scope it is important to close the connection. protected void finalize() { if (connect != null) { try { connect. close(); connect = null; } catch (SQLException ex) { logger. log(Level. SEVERE, "Unable to close database connection", ex); } }
Data Base Connectivity From JAVA /* * Database. Course. Manager. java * Copyright (c) 2007 Drexel University. All rights reserved. */ package edu. drexel. cs 350; import import java. sql. Prepared. Statement; //Executes a SQL statement java. sql. Result. Set; //Stores the rows returned from the query java. sql. SQLException; //Handles errors java. util. Array. List; //Dynamic structure java. util. List; //Interface to an Array. List java. util. logging. Level; Used to log errors /** * Database backed course manager * * @author Sunny Huynh * @version 1. 0 * @since 1. 0 */ public class Database. Course. Manager extends Database. Connection implements Course. Manager {
Data Base Connectivity From JAVA Example: Add. Course A course contains: u u u Department Name Department Number of Credits Name Description Therefore, the insert statement will contain five values. In it’s most basic form, a SQL INSERT statement has the following syntax: INSERT INTO Table. Name VALUES (list of values) This form of SQL INSERT requires the knowledge of the order of the fields in the table. The SQL table was created in the order the fields are listed above. Therefore, we can perform a SQL insert by listing the values in their proper place. Java allows this to be done without a lot of fancy string manipulation if you use the Prepared. Statement object. Observe the following code which associates each value to be inserted with the proper question mark. One huge benefit to using the Prepared. Statement instead of building the string manually, is it handles any special characters that would need to be escaped. i. e. double quote. In addition, it will prevent SQL code from inadvertently being executed, but that is an advanced topic.
Data Base Connectivity From JAVA /* * @see edu. drexel. cs 350. Course. Manager#add. Course(edu. drexel. cs 350. Course) */ public void add. Course(final Course course) throws Scheduler. Exception { try { final Prepared. Statement stm = connect. prepare. Statement ( "INSERT INTO Course VALUES(? , ? , ? )"); stm. set. String(1, course. get. Department ()); stm. set. Int(2, course. get. Number ()); stm. set. Int(3, course. get. Credits ()); stm. set. String(4, course. get. Name()); stm. set. String(5, course. get. Description ()); int n = stm. execute. Update (); stm. close(); if (n != 1) throw new Scheduler. Exception("Unable to add course"); } catch (SQLException ex) { logger. log(Level. SEVERE , "add. Student ", ex); "add. Student", throw new Scheduler. Exception("Unable to add course", ex); } } Executing the SQL command is simply a matter of calling the execute. Update method of the Prepared. Statement object.
Data Base Connectivity From JAVA RETRIEVING RECORDS FROM A DATABASE Example: get. All. Courses We need to select data from the database and return it into a structure Java can understand. In it’s most basic form, a SQL SELECT statement has the following syntax: SELECT * FROM Table. Name ORDER BY List. Of. Fields The ORDER BY clause is optional, but will allow the results to be sorted by the fields we list after the keywords ORDER BY. Again we will use the Prepared. Statement to hold the SQL command. The results of the query will be stored in a Result. Set object and then each record will be added to our courses object.
Data Base Connectivity From JAVA /* * @see edu. drexel. cs 350. Course. Manager#get. All. Courses() */ public Course[] get. All. Courses() { try { final Prepared. Statement stm = connect. prepare. Statement ( "SELECT * FROM Course ORDER BY dept, num"); final Result. Set result = stm. execute. Query (); final List<Course> courses = new Array. List<Course>(); while (result. next ()) (result. next()) courses. add(to. Course(result )); result. close(); stm. close(); return courses. to. Array(new Course[0]); } catch (SQLException ex) { logger. log(Level. SEVERE , "get. All. Courses ", ex); "get. All. Courses", return new Course[0]; } }
Data Base Connectivity From JAVA RETRIEVING RECORDS FROM A DATABASE WITH A CONDITION Example: get. Course We need to add a selection criteria to our SQL statement so only a specific of courses is returned. In it’s most complex form, a SQL SELECT statement has the following syntax: SELECT * FROM Table. Name WHERE Field 1 = value 1 and Field 2 = value 2 The WHERE clause is optional, and allows the results to filtered based upon the selection criteria you list. Again we will use the Prepared. Statement to hold the SQL command. The results of the query will be stored in a Result. Set object and the single record will be added to our course object.
Data Base Connectivity From JAVA /* * @see edu. drexel. cs 350. Course. Manager#get. Course(java. lang. String, int) */ public Course get. Course(final String dept, int num) { Course course = null; try { final Prepared. Statement stm = connect. prepare. Statement ( "SELECT * FROM Course WHERE dept = ? AND num = ? "); stm. set. String(1, dept); stm. set. Int(2, num); final Result. Set result = stm. execute. Query (); if (result. next ()) (result. next()) course = to. Course(result ); result. close(); stm. close(); } catch (SQLException ex) { logger. log(Level. SEVERE , "get. Course ", ex); "get. Course", } return course; }
Data Base Connectivity From JAVA ? "); /* * @see edu. drexel. cs 350. Course. Manager#remove. Course(java. lang. String, int) */ public void remove. Course(final String dept, int num) throws Scheduler. Exception { try { final Prepared. Statement stm = connect. prepare. Statement ( "DELETE FROM Course WHERE dept = ? AND num = stm. set. String(1, dept); stm. set. Int(2, num); stm. execute. Update (); stm. close(); } catch (SQLException ex) { logger. log(Level. SEVERE , "remove. Course ", ex); "remove. Course", throw new Scheduler. Exception(ex ); } }
Data Base Connectivity From JAVA /* * @see edu. drexel. cs 350. Course. Manager#update. Course(edu. drexel. cs 350. Course) */ public void update. Course(final Course course) throws Scheduler. Exception { try { final Prepared. Statement stm = connect. prepare. Statement ( "UPDATE Course SET credits = ? , name = ? , description = ? " + " WHERE dept = ? AND name = ? "); stm. set. Int(1, course. get. Credits ()); stm. set. String(2, course. get. Name()); stm. set. String(3, course. get. Description ()); stm. set. String(4, course. get. Department ()); stm. set. Int(5, course. get. Number ()); stm. execute. Update (); stm. close(); } catch (SQLException ex) { logger. log(Level. SEVERE , "update. Course ", ex); "update. Course", throw new Scheduler. Exception(ex ); } } private Course to. Course(final Result. Set result) throws SQLException { final String dept = result. get. String("dept "); final int num = result. get. Int("num "); final Course course = new Course(dept, num); course. set. Credits(result. get. Int("credits ")); course. set. Name(result. get. String("name ")); course. set. Description(result. get. String("description ")); return course; }
- Slides: 25