public static Connection getConnection(String url,String user,String password)
jdbc:subprotocol:subname
public static Connection getConnection(String url)
jdbc:subprotocol:subname
private Connection con = null;
....
try{
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;");
//
}
catch(SQLException sqle) {
System.out.println("Sql
Exception :"+sqle.getMessage());
}
catch(ClassNotFoundException e) {
System.out.println("Class Not Found Exception :" +
e.getMessage());
}
ResultSet rs = prep.executeQuery();
int n = prep.executeUpdate();
while(rs.next()) {
sqlStatement.close(); // release the statement resources
.....
con.close(); // close and release the database (do this before the program exits)
protected void finalize()
{
try{
con.close();
}
catch(Exception e)
{
}
}
<!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>
<%--
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>
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
Connection
object's database is able to provide
information describing its tables, its supported SQL grammar, its
stored procedures, the capabilities of this connection, and so on. This
information is obtained with the getMetaData
method.Connection
object is in auto-commit
mode, which means that it automatically commits changes after
executing each statement. If auto-commit mode has been disabled, the
method commit
must be called explicitly in order to
commit changes; otherwise, database changes will not be saved.sqlStatement = con.createStatement(); // create a statement object
//
// add three new orders as part of a transaction
//
try{
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 methodrollback
. 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 theResultSet
object has been retrieved or theResultSet
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 thisConnection
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 thisConnection
object is in auto-commit modeReleases this
public void close()
throws SQLExceptionConnection
object's database and JDBC resources immediately instead of waiting for them to be automatically released. Calling the methodclose
on aConnection
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 aConnection
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 thisConnection
object is in auto-commit modepublic Statement createStatement()
throws SQLException
- Creates a
Statement
object for sending SQL statements to the database. SQL statements without parameters are normally executed usingStatement
objects. If the same SQL statement is executed many times, it may be more efficient to use aPreparedStatement
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 thePreparedStatement
object is executed. This has no direct effect on users; however, it does affect which methods throw certainSQLException
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
The object used for executing a static SQL statement and
returning the results it produces.Only one ResultSet
object per Statement
object can be open at the same time.
All execution methods in the Statement
interface
implicitly close a statment's current ResultSet
object if
an open one exists.
Methods:
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 SQLSELECT
statement- Returns:
- a
ResultSet
object that contains the data produced by the given query; nevernull
- Throws:
SQLException
- if a database access error occurs or the given SQL statement produces anything other than a singleResultSet
object
public int executeUpdate(String sql)
throws SQLException
- Executes the given SQL statement, which may be an
INSERT
,UPDATE
, orDELETE
statement or an SQL statement that returns nothing, such as an SQL DDL statement.
- Parameters:
sql
- an SQLINSERT
,UPDATE
orDELETE
statement or an SQL statement that returns nothing- Returns:
- either the row count for
INSERT
,UPDATE
orDELETE
statements, or0
for SQL statements that return nothing- Throws:
SQLException
- if a database access error occurs or the given SQL statement produces aResultSet
objectpublic 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 aStatement
object that is already closed has no effect.Note: A
Statement
object is automatically closed when it is garbage collected. When aStatement
object is closed, its currentResultSet
object, if one exists, is also closed.
- Throws:
SQLException
- if a database access error occurs
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
object maintains a cursor pointing to
its current row of data. Initially the cursor is positioned before
the first row. The next
method moves the cursor to
the next row, and because it returns false
when there are
no more rows in the ResultSet
object, it can be used in
a while
loop to iterate through the result set. E.g.ResultSet
object is not updatable and
has a cursor that moves forward only. Thus, you can iterate through it
only once and only from the first row to the last row.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 |
ResultSet
objects that
are scrollable and/or updatable. To do this you need to create a
Statement object specifying the result set type and the concurrency
type. At this time, this function is not supported by Windows MS
Access drivers.