25
Data Base Connectivity From JAVA Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate easy Your Java program must can a number of functions to facilitate easy access to an external database. They include: access to an external database. They include: Importing the correct packages that deal with SQL. Importing the correct packages that deal with SQL. Creating a connection to the database. Creating a connection to the database. Creating an initialization file, so that it is easy to point to another Creating an initialization file, so that it is easy to point to another database. database. Closing the connection to the database when you are complete. Closing the connection to the database when you are complete. Writing code to perform: inserts, updates, deletes and selects from the Writing code to perform: inserts, updates, deletes and selects from the database. database. Programming in java with databases is simpler if you create objects to Programming in java with databases is simpler if you create objects to perform the actions and allow programs to call those objects. This allows perform the actions and allow programs to call those objects. This allows the database to be changed without requiring the main programs to be the database to be changed without requiring the main programs to be modified. modified.

Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Embed Size (px)

Citation preview

Page 1: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVACreating a Java program that access mySQL is not difficult.Creating a Java program that access mySQL is not difficult.

Your Java program must can a number of functions to facilitate easy access to an Your Java program must can a number of functions to facilitate easy access to an external database. They include:external database. They include:

Importing the correct packages that deal with SQL.Importing the correct packages that deal with SQL. Creating a connection to the database.Creating a connection to the database. Creating an initialization file, so that it is easy to point to another 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.Closing the connection to the database when you are complete. Writing code to perform: inserts, updates, deletes and selects from the database.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 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 actions and allow programs to call those objects. This allows the database to be changed without requiring the main programs to be modified.changed without requiring the main programs to be modified.

Page 2: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVACreating a Java program that access mySQL is not difficult.Creating a Java program that access mySQL is not difficult.

Importing the correct packages that deal with SQL.Importing the correct packages that deal with SQL.

The following are the packages you need to include:The following are the packages you need to include:

import java.sql.Connection; // Java’s interface to SQLimport java.sql.Connection; // Java’s interface to SQL

import java.sql.DriverManager; // Loads the appropriate SQL driverimport java.sql.DriverManager; // Loads the appropriate SQL driver

import java.sql.SQLException; // Handles errors from the databaseimport java.sql.SQLException; // Handles errors from the database

import java.util.Properties; // Configuration file to load the db.properties fileimport java.util.Properties; // Configuration file to load the db.properties file

import java.util.logging.Level; // Logs informationimport java.util.logging.Level; // Logs information

import java.util.logging.Logger; // Logs informationimport java.util.logging.Logger; // Logs information

Page 3: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVACreating a Java program that access mySQL is not difficult.Creating a Java program that access mySQL is not difficult.

Creating a connection to the databaseCreating a connection to the database

public DatabaseConnection() throws SchedulerExceptionpublic DatabaseConnection() throws SchedulerException{{

logger = Logger.getLogger(this.getClass().getName());logger = Logger.getLogger(this.getClass().getName());

//Properties contains all the attributes in the file//Properties contains all the attributes in the file//load them into an object and the copy out the attributes//load them into an object and the copy out the attributesProperties props = new Properties();Properties props = new Properties();try {try {props.load(getClass().getResourceAsStream("db.properties"));props.load(getClass().getResourceAsStream("db.properties"));final String driver = props.getProperty("driver");final String driver = props.getProperty("driver");final String url = props.getProperty("url");final String url = props.getProperty("url");final String user = props.getProperty("user");final String user = props.getProperty("user");final String pass = props.getProperty("pass");final String pass = props.getProperty("pass");Class.forName(driver).newInstance();Class.forName(driver).newInstance();

//connect to the database//connect to the databaseconnect = DriverManager.getConnection(url, user, pass);connect = DriverManager.getConnection(url, user, pass);}}catch (Exception ex) {catch (Exception ex) {

logger.log(Level.SEVERE, "Unable to create database connection",logger.log(Level.SEVERE, "Unable to create database connection",ex);ex);

throw new SchedulerException("Unable to create database connection",throw new SchedulerException("Unable to create database connection",ex);ex);

}}}}

Page 4: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVACreating an initialization file, so that it is easy to point to another database.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 passwordThe initialization file must contain the: driver, url, user name, and password

db.properties filedb.properties file

driver = com.mysql.jdbc.Driverdriver = com.mysql.jdbc.Driver

url = jdbc:mysql://landsend.cs.drexel.edu/schedulerurl = jdbc:mysql://landsend.cs.drexel.edu/scheduler

user = jsalvageuser = jsalvage

pass = dbwizpass = dbwiz

Page 5: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVAWhen an object goes out of scope it is important to close the connection.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 First check if the database connection is still valid, if so close it and set it to null, if not throw an error.throw an error.

protected void finalize()protected void finalize()

{{

if (connect != null) {if (connect != null) {

try {try {

connect.close();connect.close();

connect = null;connect = null;

}}

catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, logger.log(Level.SEVERE,

"Unable to close database connection","Unable to close database connection",

ex);ex);

}}

}}

}}

}}

Page 6: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

ADDING A RECORD TO THE DATABASEADDING A RECORD TO THE DATABASE

Inserting data into a database uses an SQL INSERT statement, but requires some additional Inserting data into a database uses an SQL INSERT statement, but requires some additional formatting.formatting.

A PerparedStatement is an object that allows the execution of SQL statements from java.A PerparedStatement 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 SetString or SetInt It allows the SQL to be written with arguments that can then be set via a SetString or SetInt method.method.

Observe declaring a PreparedStatement stm that inserts 5 values into the Course table:Observe declaring a PreparedStatement stm that inserts 5 values into the Course table:

final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement("INSERT INTO Course VALUES(?, ?, ?, ?, ?)");"INSERT INTO Course VALUES(?, ?, ?, ?, ?)");

To set each argument, call the appropriate method setString or setInt with two To set each argument, call the appropriate method setString or setInt with two parameters. The first is the argument you wish to set in the PreparedStatement and parameters. The first is the argument you wish to set in the PreparedStatement and the second is the value of that argument.the second is the value of that argument.

Therefore, if you wish to set the first argument to “Computer Science”, use the Therefore, if you wish to set the first argument to “Computer Science”, use the following method call:following method call: stm.setString(1, “Computer Science”);stm.setString(1, “Computer Science”);

Similairly, to set the third argument to the 3 credits, use the following method call:Similairly, to set the third argument to the 3 credits, use the following method call: stm.setInt(3, 3);stm.setInt(3, 3);

int n = stm.executeUpdate();int n = stm.executeUpdate();stm.close();stm.close();if (n != 1)if (n != 1)

throw new SchedulerException("Unable to add throw new SchedulerException("Unable to add course");course");

}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, "addStudent", ex);logger.log(Level.SEVERE, "addStudent", ex);throw new SchedulerException("Unable to add course", throw new SchedulerException("Unable to add course",

ex);ex);}}

}}

Executing the SQL command is simply a matter of calling the Executing the SQL command is simply a matter of calling the executeUpdateexecuteUpdate method of the method of the PreparedStatementPreparedStatement object. object.

Example: AddCourseExample: AddCourse

A course contains:A course contains:

Department NameDepartment Name Department NumberDepartment Number Number of CreditsNumber of Credits NameName DescriptionDescription

Therefore, the insert statement will contain five values. In it’s most basic form, a SQL INSERT Therefore, the insert statement will contain five values. In it’s most basic form, a SQL INSERT statement has the following syntax:statement has the following syntax:

INSERT INTO TableName VALUES (list of values)INSERT INTO TableName VALUES (list of values)

This form of SQL INSERT requires the knowledge of the order of the fields in the table. The SQL 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 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.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 Java allows this to be done without a lot of fancy string manipulation if you use the PreparedStatement object. Observe the following code which associates each value to be PreparedStatement object. Observe the following code which associates each value to be inserted with the proper question mark.inserted with the proper question mark.

One huge benefit to using the PreparedStatement instead of building the string manually, is it One huge benefit to using the PreparedStatement 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 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. will prevent SQL code from inadvertently being executed, but that is an advanced topic.

Page 7: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

ADDING A RECORD TO THE DATABASEADDING A RECORD TO THE DATABASE

To execute the statement, close it, and check to see it executed properly, use the To execute the statement, close it, and check to see it executed properly, use the following sequence of calls:following sequence of calls:

int n = stm.executeUpdate();int n = stm.executeUpdate();stm.close();stm.close();if (n != 1)if (n != 1)

throw new SchedulerException("Unable to add course");throw new SchedulerException("Unable to add course");}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, "addStudent", ex);logger.log(Level.SEVERE, "addStudent", ex);throw new SchedulerException("Unable to add course", throw new SchedulerException("Unable to add course",

ex);ex);}}

}}

Executing the SQL command is simply a matter of calling the Executing the SQL command is simply a matter of calling the executeUpdateexecuteUpdate method of the method of the PreparedStatementPreparedStatement object. object.

Page 8: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

RETRIEVING RECORDS FROM A DATABASERETRIEVING RECORDS FROM A DATABASE

Retrieving data from a database uses an SQL SELECT statement, but requires some Retrieving data from a database uses an SQL SELECT statement, but requires some additional formatting.additional formatting.

Again we will use the Again we will use the PreparedStatementPreparedStatement to hold the SQL command. to hold the SQL command.

The results of the query will be stored in a ResultSet object and then each record is The results of the query will be stored in a ResultSet object and then each record is copied to an array list object in Java.copied to an array list object in Java.

The PreparedStatement is assigned the SQL Select statement to execute. Unlike the The PreparedStatement is assigned the SQL Select statement to execute. Unlike the insert, no arguments are needed. While the SELECT is hardcoded here, it could just 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.as easily been built in a string variable and passed dynamically.

See the following example:See the following example:

final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"SELECT * FROM Course ORDER BY dept, num");"SELECT * FROM Course ORDER BY dept, num");

Page 9: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVATo execute the SELECT statement a similar call as with INSERT, except here we need to store To execute the SELECT statement a similar call as with INSERT, except here we need to store the result of the query in a ResultSet Object. Observer the following code:the result of the query in a ResultSet Object. Observer the following code:

final ResultSet result = stm.executeQuery();final ResultSet result = stm.executeQuery();

Once the ResultSet is populated, we want to move the values from the result set to an Once the ResultSet is populated, we want to move the values from the result set to an ArrayList. This can be done a number of ways, observe an example:ArrayList. This can be done a number of ways, observe an example:

final List<Course> courses = new ArrayList<Course>();final List<Course> courses = new ArrayList<Course>();while (result.next())while (result.next())

courses.add(toCourse(result));courses.add(toCourse(result));

Finally, once all the rows are copied, close the ResultSet and close the database statement.Finally, once all the rows are copied, close the ResultSet and close the database statement.

result.close();result.close();stm.close();stm.close();

Page 10: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVARETRIEVING RECORDS FROM A DATABASE WITH A CONDITIONRETRIEVING RECORDS FROM A DATABASE WITH A CONDITION

Just as we could set parameters in an INSERT statement, a SELECT statement can be 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.set up to use parameters for the values to limit the predicate with.

Again we will use the PreparedStatement to hold the SQL command.Again we will use the PreparedStatement to hold the SQL command.

The results of the query will be stored in a ResultSet object and the single record will be The results of the query will be stored in a ResultSet object and the single record will be added to our course object.added to our course object.

The only real difference is using ? in the WHERE clause of the SELECT statement where The only real difference is using ? in the WHERE clause of the SELECT statement where the parameters will be placed.the parameters will be placed.

Observe the following statement which creates a SELECT statement Observe the following statement which creates a SELECT statement

final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement("SELECT * FROM Course WHERE dept = ? AND num = ?");"SELECT * FROM Course WHERE dept = ? AND num = ?");

The parameters are set with the following statements:The parameters are set with the following statements:

stm.setString(1, dept);stm.setString(1, dept);stm.setInt(2, num);stm.setInt(2, num);

And then executed with the following statement:And then executed with the following statement:

final ResultSet result = stm.executeQuery();final ResultSet result = stm.executeQuery();

Page 11: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

DELETING RECORDS FROM A DATABASE WITH A CONDITIONDELETING RECORDS FROM A DATABASE WITH A CONDITION

Deleting records from a SQL database isn’t very different in form than selecting data 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 from a database. You must prepare the statement in the same manner, just instead of creating a SQL SELECT in the prepareStatement object, you create a SQL DELETE creating a SQL SELECT in the prepareStatement object, you create a SQL DELETE Statement.Statement.

Observe the following code which declares a DELETE statement that deletes course Observe the following code which declares a DELETE statement that deletes course that match a department and course number:that match a department and course number:

final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"DELETE FROM Course WHERE dept = ? AND num = ?");"DELETE FROM Course WHERE dept = ? AND num = ?");

stm.setString(1, dept);stm.setString(1, dept);

stm.setInt(2, num);stm.setInt(2, num);

stm.executeUpdate();stm.executeUpdate();

stm.close();stm.close();

Page 12: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

UPDATING RECORDS FROM A DATABASE WITH A CONDITIONUPDATING RECORDS FROM A DATABASE WITH A CONDITION

The updating of records in a database follows the same pattern as SELECT and DELETE. 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 Observe the following code that sets the credits and name field of a course that matches the department and name:matches the department and name:

final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"UPDATE Course SET credits = ?, name = ?, description = ?" +"UPDATE Course SET credits = ?, name = ?, description = ?" +

" WHERE dept = ? AND name = ?");" WHERE dept = ? AND name = ?");

stm.setInt(1, course.getCredits());stm.setInt(1, course.getCredits());

stm.setString(2, course.getName());stm.setString(2, course.getName());

stm.setString(3, course.getDescription());stm.setString(3, course.getDescription());

stm.setString(4, course.getDepartment());stm.setString(4, course.getDepartment());

stm.setInt(5, course.getNumber());stm.setInt(5, course.getNumber());

stm.executeUpdate();stm.executeUpdate();

stm.close();stm.close();

Page 13: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

package edu.drexel.cs350;package edu.drexel.cs350;

import java.sql.Connection; // Java’s interface to SQLimport java.sql.Connection; // Java’s interface to SQL

import java.sql.DriverManager; // Loads the appropriate SQL driverimport java.sql.DriverManager; // Loads the appropriate SQL driver

import java.sql.SQLException; // Handles errors from the databaseimport java.sql.SQLException; // Handles errors from the database

import java.util.Properties; // Configuration file to load the db.properties import java.util.Properties; // Configuration file to load the db.properties filefile

import java.util.logging.Level; // Logs informationimport java.util.logging.Level; // Logs information

import java.util.logging.Logger; // Logs informationimport java.util.logging.Logger; // Logs information

/**/**

* Base class for those that use a database connection* Base class for those that use a database connection

**

* @author Sunny Huynh* @author Sunny Huynh

* @version 1.0* @version 1.0

* @since 1.0* @since 1.0

*/*/

public abstract class DatabaseConnectionpublic abstract class DatabaseConnection

{{

protected final Logger logger;protected final Logger logger;

protected Connection connect = null;protected Connection connect = null;

Page 14: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

public DatabaseConnection() throws SchedulerExceptionpublic DatabaseConnection() throws SchedulerException{{

logger = Logger.getLogger(this.getClass().getName());logger = Logger.getLogger(this.getClass().getName());

Properties props = new Properties();Properties props = new Properties();try {try {props.load(getClass().getResourceAsStream("db.properties"));props.load(getClass().getResourceAsStream("db.properties"));final String driver = props.getProperty("driver");final String driver = props.getProperty("driver");final String url = props.getProperty("url");final String url = props.getProperty("url");final String user = props.getProperty("user");final String user = props.getProperty("user");final String pass = props.getProperty("pass");final String pass = props.getProperty("pass");Class.forName(driver).newInstance();Class.forName(driver).newInstance();connect = DriverManager.getConnection(url, user, pass);connect = DriverManager.getConnection(url, user, pass);}}catch (Exception ex) {catch (Exception ex) {

logger.log(Level.SEVERE, "Unable to create database connection",logger.log(Level.SEVERE, "Unable to create database connection",ex);ex);

throw new SchedulerException("Unable to create database throw new SchedulerException("Unable to create database connection",connection",

ex);ex);}}

}}

Data Base Connectivity From JAVAData Base Connectivity From JAVA

Page 15: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

Driver specifies which backend database system to useDriver specifies which backend database system to use

In this case, we need a mySQL driver since the database is mySQLIn this case, we need a mySQL driver since the database is mySQL

The URL specifies the location of the database as well as which database within The URL specifies the location of the database as well as which database within mySQL to usemySQL to use

db.properties filedb.properties filedriver = com.mysql.jdbc.Driverdriver = com.mysql.jdbc.Driverurl = jdbc:mysql://landsend.cs.drexel.edu/schedulerurl = jdbc:mysql://landsend.cs.drexel.edu/scheduleruser = jsalvageuser = jsalvagepass = dbwizpass = dbwiz

Page 16: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

When an object goes out of scope it is important to close the connection.When an object goes out of scope it is important to close the connection.

protected void finalize()protected void finalize(){{

if (connect != null) {if (connect != null) {try {try {

connect.close();connect.close();connect = null;connect = null;

}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, logger.log(Level.SEVERE, "Unable to close database connection","Unable to close database connection",

ex);ex);}}

}}}}}}

Page 17: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

/*/* * DatabaseCourseManager.java* DatabaseCourseManager.java * Copyright (c) 2007 Drexel University. All rights reserved.* Copyright (c) 2007 Drexel University. All rights reserved. */*/package edu.drexel.cs350;package edu.drexel.cs350;

import java.sql.PreparedStatement; //Executes a SQL statementimport java.sql.PreparedStatement; //Executes a SQL statementimport java.sql.ResultSet; //Stores the rows returned from the queryimport java.sql.ResultSet; //Stores the rows returned from the queryimport java.sql.SQLException;//Handles errorsimport java.sql.SQLException;//Handles errorsimport java.util.ArrayList;//Dynamic structure import java.util.ArrayList;//Dynamic structure import java.util.List;//Interface to an ArrayListimport java.util.List;//Interface to an ArrayListimport java.util.logging.Level; Used to log errorsimport java.util.logging.Level; Used to log errors

/**/** * Database backed course manager* Database backed course manager ** * @author Sunny Huynh* @author Sunny Huynh * @version 1.0* @version 1.0 * @since 1.0* @since 1.0 */*/public class DatabaseCourseManager extends DatabaseConnectionpublic class DatabaseCourseManager extends DatabaseConnection

implements CourseManagerimplements CourseManager{{

Page 18: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

Example: AddCourseExample: AddCourse

A course contains:A course contains:

Department NameDepartment Name Department NumberDepartment Number Number of CreditsNumber of Credits NameName DescriptionDescription

Therefore, the insert statement will contain five values. In it’s most basic form, a SQL INSERT Therefore, the insert statement will contain five values. In it’s most basic form, a SQL INSERT statement has the following syntax:statement has the following syntax:

INSERT INTO TableName VALUES (list of values)INSERT INTO TableName VALUES (list of values)

This form of SQL INSERT requires the knowledge of the order of the fields in the table. The SQL 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 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.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 Java allows this to be done without a lot of fancy string manipulation if you use the PreparedStatement object. Observe the following code which associates each value to be PreparedStatement object. Observe the following code which associates each value to be inserted with the proper question mark.inserted with the proper question mark.

One huge benefit to using the PreparedStatement instead of building the string manually, is it One huge benefit to using the PreparedStatement 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 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. will prevent SQL code from inadvertently being executed, but that is an advanced topic.

Page 19: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

/*/* * @see edu.drexel.cs350.CourseManager#addCourse(edu.drexel.cs350.Course)* @see edu.drexel.cs350.CourseManager#addCourse(edu.drexel.cs350.Course) */*/public void addCourse(final Course course) throws SchedulerExceptionpublic void addCourse(final Course course) throws SchedulerException{{

try {try {final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"INSERT INTO Course VALUES(?, ?, ?, ?, ?)");"INSERT INTO Course VALUES(?, ?, ?, ?, ?)");stm.setString(1, course.getDepartment());stm.setString(1, course.getDepartment());stm.setInt(2, course.getNumber());stm.setInt(2, course.getNumber());stm.setInt(3, course.getCredits());stm.setInt(3, course.getCredits());stm.setString(4, course.getName());stm.setString(4, course.getName());stm.setString(5, course.getDescription());stm.setString(5, course.getDescription());

int n = stm.executeUpdate();int n = stm.executeUpdate();stm.close();stm.close();if (n != 1)if (n != 1)

throw new SchedulerException("Unable to add course");throw new SchedulerException("Unable to add course");}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, "addStudent", ex);logger.log(Level.SEVERE, "addStudent", ex);throw new SchedulerException("Unable to add course", ex);throw new SchedulerException("Unable to add course", ex);

}}}}

Executing the SQL command is simply a matter of calling the Executing the SQL command is simply a matter of calling the executeUpdateexecuteUpdate method of the method of the PreparedStatementPreparedStatement object. object.

Page 20: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

RETRIEVING RECORDS FROM A DATABASERETRIEVING RECORDS FROM A DATABASEExample: getAllCoursesExample: getAllCourses

We need to select data from the database and return it into a structure Java can understand.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:In it’s most basic form, a SQL SELECT statement has the following syntax:

SELECT * FROM TableName ORDER BY ListOfFieldsSELECT * FROM TableName ORDER BY ListOfFields

The The ORDER BYORDER BY clause is optional, but will allow the results to be sorted by the fields we list after clause is optional, but will allow the results to be sorted by the fields we list after the keywords the keywords ORDER BYORDER BY..

Again we will use the Again we will use the PreparedStatementPreparedStatement to hold the SQL command. to hold the SQL command.

The results of the query will be stored in a ResultSet object and then each record will be added The results of the query will be stored in a ResultSet object and then each record will be added to our to our coursescourses object. object.

Page 21: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

/*/* * @see edu.drexel.cs350.CourseManager#getAllCourses()* @see edu.drexel.cs350.CourseManager#getAllCourses() */*/public Course[] getAllCourses()public Course[] getAllCourses(){{

try {try {final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"SELECT * FROM Course ORDER BY dept, num");"SELECT * FROM Course ORDER BY dept, num");

final ResultSet result = stm.executeQuery();final ResultSet result = stm.executeQuery();final List<Course> courses = new ArrayList<Course>();final List<Course> courses = new ArrayList<Course>();while (result.next())while (result.next())

courses.add(toCourse(result));courses.add(toCourse(result));

result.close();result.close();stm.close();stm.close();

return courses.toArray(new Course[0]);return courses.toArray(new Course[0]);}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, "getAllCourses", ex);logger.log(Level.SEVERE, "getAllCourses", ex);return new Course[0];return new Course[0];

}}}}

Page 22: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

RETRIEVING RECORDS FROM A DATABASE WITH A CONDITIONRETRIEVING RECORDS FROM A DATABASE WITH A CONDITIONExample: getCourseExample: getCourse

We need to add a selection criteria to our SQL statement so only a specific of courses is We need to add a selection criteria to our SQL statement so only a specific of courses is returned.returned.

In it’s most complex form, a SQL SELECT statement has the following syntax:In it’s most complex form, a SQL SELECT statement has the following syntax:

SELECT * FROM TableName WHERE Field1 = value1 and Field2 = value2SELECT * FROM TableName WHERE Field1 = value1 and Field2 = value2

The The WHEREWHERE clause is optional, and allows the results to filtered based upon the selection criteria clause is optional, and allows the results to filtered based upon the selection criteria you list.you list.

Again we will use the Again we will use the PreparedStatementPreparedStatement to hold the SQL command. to hold the SQL command.

The results of the query will be stored in a ResultSet object and the single record will be added The results of the query will be stored in a ResultSet object and the single record will be added to our to our coursecourse object. object.

Page 23: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA

/*/* * @see edu.drexel.cs350.CourseManager#getCourse(java.lang.String, int)* @see edu.drexel.cs350.CourseManager#getCourse(java.lang.String, int) */*/public Course getCourse(final String dept, int num)public Course getCourse(final String dept, int num){{

Course course = null;Course course = null;

try {try {final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"SELECT * FROM Course WHERE dept = ? AND num "SELECT * FROM Course WHERE dept = ? AND num = ?");= ?");

stm.setString(1, dept);stm.setString(1, dept);stm.setInt(2, num);stm.setInt(2, num);

final ResultSet result = stm.executeQuery();final ResultSet result = stm.executeQuery();if (result.next())if (result.next())

course = toCourse(result);course = toCourse(result);

result.close();result.close();stm.close();stm.close();

}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, "getCourse", ex);logger.log(Level.SEVERE, "getCourse", ex);}}

return course;return course;}}

Page 24: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA/*/* * @see edu.drexel.cs350.CourseManager#removeCourse(java.lang.String, int)* @see edu.drexel.cs350.CourseManager#removeCourse(java.lang.String, int) */*/public void removeCourse(final String dept, int num) throws SchedulerExceptionpublic void removeCourse(final String dept, int num) throws SchedulerException{{

try {try {final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"DELETE FROM Course WHERE dept = ? AND num = "DELETE FROM Course WHERE dept = ? AND num = ?");?");

stm.setString(1, dept);stm.setString(1, dept);stm.setInt(2, num);stm.setInt(2, num);stm.executeUpdate();stm.executeUpdate();stm.close();stm.close();

}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, "removeCourse", ex);logger.log(Level.SEVERE, "removeCourse", ex);throw new SchedulerException(ex);throw new SchedulerException(ex);

}}}}

Page 25: Data Base Connectivity From JAVA Creating a Java program that access mySQL is not difficult. Your Java program must can a number of functions to facilitate

Data Base Connectivity From JAVAData Base Connectivity From JAVA/*/*

* @see edu.drexel.cs350.CourseManager#updateCourse(edu.drexel.cs350.Course)* @see edu.drexel.cs350.CourseManager#updateCourse(edu.drexel.cs350.Course) */*/public void updateCourse(final Course course) throws SchedulerExceptionpublic void updateCourse(final Course course) throws SchedulerException{{

try {try {final PreparedStatement stm = connect.prepareStatement(final PreparedStatement stm = connect.prepareStatement(

"UPDATE Course SET credits = ?, name = ?, "UPDATE Course SET credits = ?, name = ?, description = ?" +description = ?" +

" WHERE dept = ? AND name = ?");" WHERE dept = ? AND name = ?");stm.setInt(1, course.getCredits());stm.setInt(1, course.getCredits());stm.setString(2, course.getName());stm.setString(2, course.getName());stm.setString(3, course.getDescription());stm.setString(3, course.getDescription());stm.setString(4, course.getDepartment());stm.setString(4, course.getDepartment());stm.setInt(5, course.getNumber());stm.setInt(5, course.getNumber());

stm.executeUpdate();stm.executeUpdate();stm.close();stm.close();

}}catch (SQLException ex) {catch (SQLException ex) {

logger.log(Level.SEVERE, "updateCourse", ex);logger.log(Level.SEVERE, "updateCourse", ex);throw new SchedulerException(ex);throw new SchedulerException(ex);

}}}}

private Course toCourse(final ResultSet result) throws SQLExceptionprivate Course toCourse(final ResultSet result) throws SQLException{{

final String dept = result.getString("dept");final String dept = result.getString("dept");final int num = result.getInt("num");final int num = result.getInt("num");final Course course = new Course(dept, num);final Course course = new Course(dept, num);course.setCredits(result.getInt("credits"));course.setCredits(result.getInt("credits"));course.setName(result.getString("name"));course.setName(result.getString("name"));course.setDescription(result.getString("description"));course.setDescription(result.getString("description"));return course;return course;

}}}}