Java Database Programming

Databases and JAVA

Basic Steps

public static Connection getConnection(String url,String user,String password)

public static Connection getConnection(String url)





                                  Statement sqlStatement = con.createStatement(); // create a statement object                                   PreparedStatement prep = con.prepareStatement("Select * from Products where name like ? and price <= ?");
                                  prep.setString(1,input1);  // replace ? 1 with a value
                                  prep.setDouble(2,input2); // replace ? 2 with a value
                             ResultSet rs = sqlStatement.executeQuery("select * from products where price <= 100");
                             int n = sqlStatement.executeUpdate("Delete from products where name='Hammers'");

protected void finalize()
{
   try{
        con.close();
    }
    catch(Exception e)
  {
   }
}

SearchForm.html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<SCRIPT TYPE="text/javascript">
<!--
  function checkForm()
  {
    var valid = true;
    var message = "Errors: \n";

    with(document.ClassSearch)
    {
     if(title.value == "")
     {
       valid = false;
       message = message + "title field is blank\n";
       title.style.borderColor = "red"; // red border
     }
     else
        title.style.borderColor = "gray"; // gray border
    
    }

    if(!valid)
      alert(message);
    return valid;

  }

// -->
</SCRIPT>
    </head>
    <body>
        <div>Search Form</div>
        <form name="ClassSearch" method="get" action="SearchCourse.jsp" onSubmit ="return checkForm();">
            Enter part or all of the title : <input type="text" name="title" size="30"><br/>
             Enter part or all of the instructors name: <input type="text" name="instructor" size="30"><br/>
            <input type ="submit" value="search"><br/>
            <input type ="reset" value="clear"><br />
        </form>
    </body>
</html>


SearchCourse.jsp

<%--
    Document   : SearchCourse
    Created on : Mar 13, 2012, 1:28:27 PM
    Author     : mpenderg
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Courses</h1>
        <%
        try{
          // open a connection
          Connection con = null;
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  // load the driver
          con = DriverManager.getConnection(" jdbc:sqlserver://
rubble.student.ad.fgcu.edu:1433;databaseName=sp12ism3232x;user=s12ISM3232;password=s12ISM3232;");
           //
           // get the parameters from the html form
           String title = request.getParameter("title");
           String instructor = request.getParameter("instructor");
          
           if(title != null && instructor != null)
           {
            // create a prepared sql statement
            //
            PreparedStatement prep = con.prepareStatement("Select crn, course, title, instructor from CourseSchedule where title like ? and instructor like ?");
            prep.setString(1,"%"+title+"%");
            prep.setString(2,instructor+"%");
            // execute the query
            ResultSet rs = prep.executeQuery();
            // display the results in an html table
            out.println("<table border=1>");
            while(rs.next())
            {
             out.println("<tr>");
             out.println("<td>"+rs.getString(1)+"</td>");  // crn
             out.println("<td>"+rs.getString(2)+"</td>");  // course
             out.println("<td>"+rs.getString(3)+"</td>");  // title
              out.println("<td>"+rs.getString(4)+"</td>");  // instructor
             out.println("</tr>");                                      
            }
            out.println("</table>");
            prep.close();    // close the prepared statement                 
           }
           con.close(); // close the connection
          
          }
          catch(Exception ex)
          {
           out.println("Sorry, system is not currently available<br/>");
           out.println(ex.toString());
          }
       
        %>
    </body>
</html>






Connection

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");   // load the driver 
    Connection con = DriverManager.getConnection("jdbc:sqlserver://rubble.student.ad.fgcu.edu:1433;databaseName=sp12ism3232x;user=s12ISM3232;password=s12ISM3232"); // connect 
 

      //
      // add three new orders as part of a transaction
      //
try{
sqlStatement = con.createStatement(); // create a statement object
con.setAutoCommit(false); // turn off autocommit mode, updates will be held until commit is called
}
      catch(SQLException sqle) {
         System.out.println("Sql Exception :"+sqle.getMessage());
     }

      String addString1 = "INSERT INTO Orders (CustomerPhone, ProductName, Quantity, PriceEach, OrderDate)" +
" VALUES('555-1234','Nails',24,.13, #2004-02-03#);";
      try{
        result = sqlStatement.executeUpdate(addString1);
        System.out.println(result+" records added to products table");
      }
      catch(SQLException sqle) {
         System.out.println("Sql Exception :"+sqle.getMessage());
         con.rollback(); // operation failed, rollback to previous state
      }


      String addString2 = "INSERT INTO Orders (CustomerPhone, ProductName, Quantity, PriceEach, OrderDate)" +
" VALUES('555-1234','Nails',24,.13, #2004-02-03#);";
      try{
        result = sqlStatement.executeUpdate(addString2);
        System.out.println(result+" records added to products table");
      }
      catch(SQLException sqle) {
         System.out.println("Sql Exception :"+sqle.getMessage());
         con.rollback(); // operation failed, rollback to previous state
      }

      String addString3 = "INSERT INTO Orders (CustomerPhone, ProductName, Quantity, PriceEach, OrderDate)" +
" VALUES('555-1234','Nails',24, .13, #2004-02-03#);";
      try{
        result = sqlStatement.executeUpdate(addString3);
        System.out.println(result+" records added to products table");
      }
      catch(SQLException sqle) {
         System.out.println("Sql Exception :"+sqle.getMessage());
         con.rollback();// operation failed, rollback to previous state
      }

      try{
        con.commit();  // commit all three updates to the database
      }
      catch(SQLException sqle) {
         System.out.println("Sql Exception :"+sqle.getMessage());
         con.rollback();// operation failed, rollback to previous state
      }



public void setAutoCommit(boolean autoCommit)
throws SQLException
Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the method commit or the method rollback. By default, new connections are in auto-commit mode.

The commit occurs when the statement completes or the next execute occurs, whichever comes first. In the case of statements returning a ResultSet object, the statement completes when the last row of the ResultSet object has been retrieved or the ResultSet object has been closed. 

NOTE: If this method is called during a transaction, the transaction is committed.

Parameters:
autoCommit - true to enable auto-commit mode; false to disable it
Throws:
SQLException - if a database access error occurs

public void commit()
throws SQLException
Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object. This method should be used only when auto-commit mode has been disabled.
Throws:
SQLException - if a database access error occurs or this Connection object is in auto-commit mode

public void rollback()
throws SQLException
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object. This method should be used only when auto-commit mode has been disabled.

Throws:
SQLException - if a database access error occurs or this Connection object is in auto-commit mode


public void close()
throws SQLException
Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released. Calling the method close on a Connection object that is already closed is a no-op. 

Note: A Connection object is automatically closed when it is garbage collected. Certain fatal errors also close a Connection object. If autocommit mode is off, then you must commit or rollback all operations before calling close or an exception will be generated.  This includes queries.

Throws:
SQLException - if a database access error occurs or this Connection object is in auto-commit mode
public Statement createStatement()
throws SQLException
Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it may be more efficient to use a PreparedStatement object.

Returns:
a new default Statement object
Throws:
SQLException - if a database access error occurs

public PreparedStatement prepareStatement(String sql)
throws SQLException
Creates a PreparedStatement object for sending parameterized SQL statements to the database.

A SQL statement with or without IN parameters can be pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Note: This method is optimized for handling parametric SQL statements that benefit from precompilation. If the driver supports precompilation, the method prepareStatement will send the statement to the database for precompilation. Some drivers may not support precompilation. In this case, the statement may not be sent to the database until the PreparedStatement object is executed. This has no direct effect on users; however, it does affect which methods throw certain SQLException objects.

Parameters:
sql - an SQL statement that may contain one or more '?' IN parameter placeholders
Returns:
a new default PreparedStatement object containing the pre-compiled SQL statement
Throws:
SQLException - if a database access error occurs


Statement

public ResultSet  executeQuery(String sql)    
throws SQLException
Executes the given SQL statement, which returns a single ResultSet object.

Parameters:
sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
Returns:
a ResultSet object that contains the data produced by the given query; never null
Throws:
SQLException - if a database access error occurs or the given SQL statement produces anything other than a single ResultSet object
public int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.


Parameters:
sql - an SQL INSERT, UPDATE or DELETE statement or an SQL statement that returns nothing
Returns:
either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing
Throws:
SQLException - if a database access error occurs or the given SQL statement produces a ResultSet object
public void close()
throws SQLException
Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.

Calling the method close on a Statement object that is already closed has no effect.

Note: A Statement object is automatically closed when it is garbage collected. When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

Throws:
SQLException - if a database access error occurs



PreparedStatement

    try{
        PreparedStatement prep =
con.prepareStatement("INSERT INTO Orders(CustomerPhone, ProductName, Quantity, PriceEach, OrderDate)"+
" VALUES (?, ?, ?, ?, ?)");

        prep.setString(1,"555-7777");

        prep.setString(2,"Screws");

        prep.setInt(3,44);

        prep.setDouble(4,3.23);

        prep.setTimestamp(5,new Timestamp(System.currentTimeMillis()));

        prep.executeUpdate();

        con.commit();

    }
      catch(SQLException sqle) {
         System.out.println("Sql Exception :"+sqle.getMessage());

      }
Setter Method Name
SQL Data Type
MS Access-97 Data Type
value data type
setBoolean(int index, boolean value )
BIT
Yes/No
boolean
setByte(int index, byte value )
BYTE
Number-Byte
byte
setDate(int index, Date value)
DATETIME
Date/Time
java.sql.Date object
setDouble(int index, double value)
DOUBLE
Number-Double
double
setDouble(int index, double value)
CURRENCY
Currency
double
setFloat(int index, float value)
REAL
Number-Single
float
setInt(int index, int value)
INTEGER
Number-Long
int (32 bit integer)
setInt(int index, int value)
COUNTER
AutoNumber
int (32 bit integer)
setLong(int index, long value)
LONGNINT
not supported
long (64 bit integer)
setShort(int index, short value)
SMALLINT
Number-Integer
short (16 bit integer)
setString(int index, String value)
VARCHAR
Text
String object
setString(int index, String value)
LONGCHAR
Memo
String object
setTime(int index, Time value)
DATETIME
Date/Time
java.sql.Time object
setTimestamp(int index, Timestamp value)
DATETIME
Date/Time
java.sql.Timestamp object


ResultSet

        while(rs.next())
        {
          System.out.println("Name = " + rs.getString(1));
          System.out.println("Quantity on hand  = "+rs.getInt(2));
          System.out.println("Cost = "+rs.getDouble(3));
          System.out.println("");
        }
Getter Method Name
SQL Data Type
MS Access-97 Data Type
Java Return type
getBoolean(int column)
BIT
Yes/No
boolean
getByte(int column)
BYTE
Number-Byte
byte
getDate(int column)
DATETIME
Date/Time
java.sql.Date object
getDouble(int column)
DOUBLE
Number-Double
double
getDouble(int column)
CURRENCY
Currency
double
getFloat(int column)
REAL
Number-Single
float
getInt(int column)
INTEGER
Number-Long
int (32 bit integer)
getInt(int column)
COUNTER
AutoNumber
int (32 bit integer)
getLong(int column)
LONGNINT
not supported
long (64 bit integer)
getShort(int column)
SMALLINT
Number-Integer
short (16 bit integer)
getString(int column)
VARCHAR
Text
String object
getString(int column)
LONGCHAR
Memo
String object
getTime(int column)
DATETIME
Date/Time
java.sql.Time object
getTimestamp(int column)
DATETIME
Date/Time
java.sql.Timestamp object