Upload
carl-barkley
View
243
Download
0
Embed Size (px)
Citation preview
8/13/2019 OOP - dfdf
1/26
1
IT 46 - OOP
JDBC
8/13/2019 OOP - dfdf
2/26
2
Environments, Connections, Queries
The database is, in many DB-accesslanguages, an environment.
Database servers maintain some numberof connections, so app servers can askqueries or perform modifications.
The app server issues statements:queries and modifications, usually.
8/13/2019 OOP - dfdf
3/26
3
Diagram to Remember
Environment
Connection
Statement
8/13/2019 OOP - dfdf
4/26
4
JDBC
Java Database Connectivity(JDBC) is alibrary similar to SQL/CLI, but with Java
as the host language.
8/13/2019 OOP - dfdf
5/26
5
Making a Connection
import java.sql.*;
Class.forName(com.mysql.jdbc.Driver);
Connection myCon =
DriverManager.getConnection();
The JDBC classes
The driverfor mySql;others exist
URL of the databaseyour name, and passwordgo here.
Loaded byforName
8/13/2019 OOP - dfdf
6/26
6
Statements
JDBC provides two classes:
1. Statement = an object that can accept a
string that is a SQL statement and canexecute such a string.
2. PreparedStatement = an object that hasan associated SQL statement ready toexecute.
8/13/2019 OOP - dfdf
7/26
7
Creating Statements
The Connection class has methods to createStatements and PreparedStatements.
Statement stat1 = myCon.createStatement();PreparedStatement stat2 =
myCon.createStatement(
SELECT beer, price FROM Sells +WHERE bar = Joe s Bar
); createStatementwith no argument returnsa Statement; with one argument it returns
a PreparedStatement.
8/13/2019 OOP - dfdf
8/26
8
Executing SQL Statements
JDBC distinguishes queries frommodifications, which it calls updates.
Statement and PreparedStatement eachhave methods executeQueryandexecuteUpdate.
For Statements: one argument: the query ormodification to be executed.
For PreparedStatements: no argument.
8/13/2019 OOP - dfdf
9/26
9
Example: Update
stat1 is a Statement.
We can use it to insert a tuple as:
stat1.executeUpdate(
INSERT INTO Sells +
VALUES(Brass Rail,Bud,3.00)
);
8/13/2019 OOP - dfdf
10/26
10
Example: Query
stat2 is a PreparedStatement holdingthe query SELECT beer, price FROM
Sells WHERE bar = JoesBar .executeQueryreturns an object of class
ResultSet
The query:
ResultSet menu = stat2.executeQuery();
8/13/2019 OOP - dfdf
11/26
11
Accessing the ResultSet
An object of type ResultSet issomething like a cursor.
Method next()advances the cursor tothe next tuple.
The first time next()is applied, it gets the
first tuple. If there are no more tuples, next()returns
the value false.
8/13/2019 OOP - dfdf
12/26
12
Accessing Components of Tuples
When a ResultSet is referring to atuple, we can get the components of
that tuple by applying certain methodsto the ResultSet.
Method getX (i), where X is some
type, and i is the component number,returns the value of that component.
The value must have type X.
8/13/2019 OOP - dfdf
13/26
13
Example: Accessing Components
Menu = ResultSet for query SELECT beer,price FROM Sells WHERE bar = Joe s Bar .
Access beer and price from each tuple by:
while ( menu.next() ) {
theBeer = Menu.getString(1);
thePrice = Menu.getFloat(2);/*something with theBeer and
thePrice*/
}
8/13/2019 OOP - dfdf
14/26
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //.newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test",
"root", "root");
if(!con.isClosed())
System.out.println("Successfully connected to " +
"MySQL server using TCP/IP...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
} 14
8/13/2019 OOP - dfdf
15/26
Critical steps in using
JDBCThere are five critical steps in using JDBC to manipulate adatabase:
Load and register the JDBC driver classes (programming
interface)for the database server that you intend to use. Get a Connectionobject that represents a connection to
the database server (analogous to logging onto theserver).
Get one or more Statementobjects for use inmanipulating the database.
Use the Statementobjects to manipulate the database.
Close the connection to the database.
15
8/13/2019 OOP - dfdf
16/26
Register the JDBC driverfor MySQL
Class.forName("com.mysql.jdbc.Driver");
shows the statement that implements the first critical steplisted
earlier (load and register the JDBC driver classes). This statementregisters the MySQL driver classes with the Java program, makingit possible for this program to manipulate data on the MySQLserver. The DriverManagerwill try to load as many drivers as it can find and then for
any given connection request, it will ask each driver in turn to try to connect tothe target URL. ...
When a Driverclass is loaded, it should create an instance of itself and registerit with the DriverManager. This means that a user can load and register adriver by calling
Class.forName("foo.bah.Driver")"
16
http://www.developer.com/java/data/article.php/3417381http://www.developer.com/java/data/article.php/34173818/13/2019 OOP - dfdf
17/26
Get a connection to thedatabase
con = DriverManager.getConnection("jdbc:mysql:///test","root", "root");
gets a connection to the database at the specified URL (mysql on
localhost)for a user named rootwith a root password. As you are alreadyaware, this user is the default administrator having full privileges to doanything, including creating new databases and registering new users onthose databases.
The getConnection method is a static method ofthe DriverManager class. When getConnection is invoked,the DriverManagerwill attempt to locate a suitable driver from amongthose loaded at initialization and those loaded explicitly using the sameclassloader as the current applet or application.
17
8/13/2019 OOP - dfdf
18/26
Get a Statement object
stmt = con.createStatement();
This code invokes thecreateStatementmethod of the Connectioninterface to get
an object of type Statement.
Recall that conis a reference to an object oftype Connection. A Connectionobject defines a connection (session)with aspecific database. SQL statements are executed and results are returned within
the context of a connection. According to Sun, a Statement object is:
"... used for executing a static SQL statement and returning the results it produces."
The results, if any, are returned in the form of a ResultSetobject.
18
8/13/2019 OOP - dfdf
19/26
use of a Statement object to
manipulate the databaseExample:
stmt.executeUpdate( "CREATE DATABASE JunkDB");
invokes the executeUpdatemethod on the Statementobject tocreate the new database named JunkDB.
19
8/13/2019 OOP - dfdf
20/26
Close the connection
con.close();
20
8/13/2019 OOP - dfdf
21/26
A ResultSet object
A ResultSetobject provides access to anencapsulated table of data. The object
maintains a cursor pointing to its current rowof data. Initially the cursor is positionedbefore the first row. The nextmethodmoves the cursor to the next row (similar to
an iterator or an enumerator in Java).Once the results are encapsulated in
a ResultSetobject, the ResultSetinterfaceprovides several methods that can be used toextract the information from the object. 21
8/13/2019 OOP - dfdf
22/26
Methods of a ResultSet object
The getmethods (such as getString)retrieve columnvalues for the current row. You can retrieve values usingeither the index number of the column or the name of the
column. I have read that using the column index is moreefficient but I can't give you a reference on that.
(Columns are numbered beginning with 1, not with 0.)
For the getmethods, the JDBC driver attempts to convert
the underlying data to the specified Java type and returnsa suitable Java value.
22
8/13/2019 OOP - dfdf
23/26
The life of a ResultSet Object
A ResultSetobject is automaticallyclosed by the Statementobject that
generated it whenthat Statementobject is closed, re-executed, or used to retrieve the next
result from a sequence of multipleresults.
23
8/13/2019 OOP - dfdf
24/26
Perform the query
rs = stmt.executeQuery("SELECT * " + "from myTable ORDER BY test_id");
invokes the executeQuerymethod to perform the queryon the database selecting all columns in all rows, andsorting the results in order by the values in the columnnamed test_id. The results are encapsulated in
the ResultSetobject referred to by the reference variablenamed rs.
24
8/13/2019 OOP - dfdf
25/26
Display all of the results in
the ResultSet objectSystem.out.println("Display all results:");
while(rs.next()){
int theInt= rs.getInt("test_id");
String str = rs.getString("test_val");
System.out.println("\ttest_id= " + theInt + "\tstr = " + str);}
Iterate on the ResultSetobject one row at a time.
Invoke the getIntmethod to get and save the value in the column
named test_idfor each row. Invoke the getStringmethod to get and save the value in the column
named test_valfor each row.
Display the two values on a new output line on the screen.
25
8/13/2019 OOP - dfdf
26/26
THANK YOU
26