Download LESSON: Java DataBase Connectivity (JDBC)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

DBase wikipedia , lookup

Global serializability wikipedia , lookup

Commitment ordering wikipedia , lookup

Microsoft Access wikipedia , lookup

SQL wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Serializability wikipedia , lookup

IMDb wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Oracle Database wikipedia , lookup

Functional Database Model wikipedia , lookup

PL/SQL wikipedia , lookup

Ingres (database) wikipedia , lookup

Database wikipedia , lookup

Concurrency control wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Versant Object Database wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Clusterpoint wikipedia , lookup

Open Database Connectivity wikipedia , lookup

ContactPoint wikipedia , lookup

Transcript
Table of Contents
LESSON: Java DataBase Connectivity (JDBC).............................................................................................1
Concepts...............................................................................................................................................................2
Connecting to the Database................................................................................................................................3
JDBC URL...........................................................................................................................................................4
Example: Connecting to a Postgres DB............................................................................................................5
Example: Connecting to a DB with ODBC.......................................................................................................6
About Select and Update....................................................................................................................................7
Making a Statement............................................................................................................................................8
Prepared Statements...........................................................................................................................................9
PreparedStatement −example−.......................................................................................................................10
Callable Statement............................................................................................................................................11
The Result Set....................................................................................................................................................12
The Result Set − Fetching Data.......................................................................................................................13
Metadata............................................................................................................................................................14
Metadata − Example.........................................................................................................................................15
Transactions......................................................................................................................................................16
Three−valued Logic: the Story of NULL........................................................................................................17
Was NULL ?......................................................................................................................................................18
labs......................................................................................................................................................................19
LABS.....................................................................................................................................................19
1. Setting up a Database..................................................................................................................19
2. Populating the Database..............................................................................................................19
3. Accessing the Database...............................................................................................................19
RESOURCES....................................................................................................................................................21
i
LESSON: Java DataBase Connectivity (JDBC)
author: Jacco Kok − [email protected]
organization: 0xCAFEBABE − www.0xCAFEBABE.nl
Slides
1. Concepts
2. Connecting to the Database
3. JDBC URL
4. Example: Connecting to a Postgres DB
5. Example: Connecting to a DB with ODBC
6. About Select and Update
7. Making a Statement
8. Prepared Statements
9. PreparedStatement −example−
10. Callable Statement
11. The Result Set
12. The Result Set − Fetching Data
13. Metadata
14. Metadata − Example
15. Transactions
16. Three−valued Logic: the Story of NULL
17. Was NULL ?
18. labs
Labs
1. Setting up a Database
2. Populating the Database
3. Accessing the Database
Resources
1
Concepts
• JDBC = Java DataBase Connectivity
• Query/update a database from within a Java program
• Receive query−results as Java objects
• JDBC implementation is often called a driver
Java DataBase Connectivity (JDBC)
1
The way the connection to the Db is setup determines the type of a JDBC driver. The most convenient type
goes straight to the Db server via the network. A jdbc driver can also use a locally installed Db client. Or a
third possibility is the use of a JDBC/ODBC bridge.
2
Connecting to the Database
Two−step process
1. Load the JDBC driver class specific to the database
♦ Using Class.forName(<driver class name>)
2. Connect to the database using a JDBC URL and optionally a username/password.
♦ Using DriverManager.getConnection(<URL>, [username], [password])
Java DataBase Connectivity (JDBC)
2
Often people will create a number of connections to the database. These connections can be shared by all
classes using the database. An often used technique for sharing is called pooling. Some jdbc vendors have a
connection pool class available, and some app servers offer this capability. You can of course also write your
own pool.
3
JDBC URL
• When connecting the JDBC URL tells the driver:
♦ the (remote) location and name of the database
♦ the protocol(s) to be used
• General form: jdbc:<protocol>:<location>
• Example: jdbc:postgresql://localhost:5432/motorcycle
♦ postgresql the sub−protocol for Postgresql
♦ localhost:5432 the hostname and portnumber
♦ motorcycle the database to use
Java DataBase Connectivity (JDBC)
3
4
Example: Connecting to a Postgres DB
28:
29:
30:
31:
32:
33:
try
{
Class.forName("postgresql.Driver");
String dburl="jdbc:postgresql://localhost:5432/motorcycle";
connection = DriverManager.getConnection(dburl,"alex","criville");
}
Java DataBase Connectivity (JDBC)
4
Rather than hard−coding Db url and user/passwd in your class you are advised to use a property file. See
core/neturl and exercises/DBSetup.java.
5
Example: Connecting to a DB with ODBC
24:
25:
26:
27:
28:
29:
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dburl="jdbc:odbc:motorcycle";
connection = DriverManager.getConnection(dburl,"alex","criville");
}
Java DataBase Connectivity (JDBC)
5
6
About Select and Update
In JDBC the following distinction is used.
• update: any statement that changes the content of the database
• query: any statement that only extracts information
Java DataBase Connectivity (JDBC)
6
7
Making a Statement
The most straight forward way of using a connection is by way of java.sql.Statement
50:
51:
Statement select = connection.createStatement();
ResultSet result = select.executeQuery("select name from cycles");
Java DataBase Connectivity (JDBC)
7
8
Prepared Statements
If a certain query/update will be executed a number of times only with different parameters in
the where clause, you can use a java.sql.PreparedStatement.
• A prepared statement is more efficient
• allows other data types than strings to be used as parameter (In Statement the statement
is passed to the database as a string)
Java DataBase Connectivity (JDBC)
8
9
PreparedStatement −example−
83:
84:
85:
86:
87:
PreparedStatement select = connection.prepareStatement("select manufacturer, power f
for(int walk = 0; walk < theNames.length; walk++)
{
select.setString(1, theNames[walk]);
ResultSet result = select.executeQuery();
Java DataBase Connectivity (JDBC)
9
10
Callable Statement
If you are using stored procedures in your database then java.sql.CallableStatement is the thing
for you.
Java DataBase Connectivity (JDBC)
10
To store large objects in the database, so called blobs, all statement types have methods to attach streams to a
statement.
11
The Result Set
• A statement.executeUpdate(updatestring) will return an int, the number of rows
affected.
• A statement.executeQuery(querystring) on the other hand will return a ResultSet.
In JDBC 1 this is a list of all rows returned by the query. In JDBC 2 a ResultSet is a more
elaborate object capable of fetching a limited number of rows at a time. In JDBC 2 you can also
modify the rows retrieved and have them modified in the database too.
Java DataBase Connectivity (JDBC)
11
12
The Result Set − Fetching Data
• with ResultSet.next() you can loop through the result set
• with ResultSet.getXXX(<column name>) you can get the data out for a column in the
current row. (XXX is the datatype of the column eg String)
• alternatively you can use ResultSet.getXXX(<column number>) where the left most
column is 1
55:
56:
57:
58:
while(result.next())
{
resList.addElement(result.getString("name"));
}
Java DataBase Connectivity (JDBC)
12
13
Metadata
If you do not beforehand know what your database or resultset looks like, JDBC allows you to
query the database or resultset to find out how it looks. The information about the database is
usually called metadata. See
• java.sql.ResultSetMetaData
• java.sql.DataBaseMetaData
Java DataBase Connectivity (JDBC)
13
14
Metadata − Example
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
String[] types = {"TABLE"};
String[] tables = {"parts", "partdescription", "cycles"};
DatabaseMetaData metaData = connection.getMetaData();
ResultSet result = null;
for(int walk = 0; walk < tables.length; walk++)
{
result = metaData.getTables(null, null, tables[walk], types);
if(result.next())
{
System.out.println("dropping "+tables[walk]);
statement.executeUpdate("DROP TABLE "+tables[walk]);
}
}
Java DataBase Connectivity (JDBC)
14
15
Transactions
To make a number of statements part of a transaction use the setAutoCommit method in
Connection
connection.setAutoCommit(false);
...executeUpdate()
...excuteQuery()
connection.commit();
Java DataBase Connectivity (JDBC)
15
In JDBC 2 you can set the transaction isolation level too.
16
Three−valued Logic: the Story of NULL
The value NULL has a special place in SQL. Logic expressions in the where clause are
three−valued: true, false or NULL. Therefore you would use
WHERE column IS NULL
rather than
WHERE column = NULL
.
Java DataBase Connectivity (JDBC)
16
17
Was NULL ?
ResultSet has a special method to establish if the latest column retrieved was NULL or not.
93:
94:
95:
96:
97:
98:
99:
100:
101:
Java DataBase Connectivity (JDBC)
int power = result.getInt("power");
if(result.wasNull())
{
System.out.println(" −not specified−");
}
else
{
System.out.println(" "+power);
}
17
18
labs
Click here for labs
Java DataBase Connectivity (JDBC)
18
LABS
1. Setting up a Database
In this first exercise you will setup a database that will be further accessed from Java with JDBC. This step
will be very specific to the database that is used and may be provided by the teacher. The setup for several
standard databases is provided here below.
Microsoft Access (MSAccess)
Here you will setup an MS Access (.mdb) file as the database and make it available as an ODBC Data Source.
This is probably the easiest way to get started with JDBC since no database process needs to be running and
you can use the standard sun.jdbc.odbc.JdbcOdbcDriver included in the JDK.
1. Start MSAccess
2. Create a blank database (use no wizards!)
3. Save it in the exercises dir as 'motorcycles'. A file mototrcycles.mdb should have been created.
4. Exit MSAccess. Your database is now created. In the next steps you make this database available
through ODBC.
5. Start the control panel and open the icon "32−bit ODBC" (usually the first icon)
6. In the "User DSN"−tab click "Add..." and select "MicroSoft Access Driver". An ODBC setup window
appears.
7. Fill in 'motorcycle' in the "Data Source Name" field.
8. Click "Select..." and select the mototrcycles.mdb file.
9. Click "Ok". You should see 'motorcycles' in the list of User Data Sources
10. In dbConnect.props if not already filled in add:
driver = sun.jdbc.odbc.JdbcOdbcDriver
url = jdbc:odbc:motorcycle
No "user" and "password" entries are required.
11. Run DBConnectTest.java and watch messages printed. Troubleshoot possible failures.
2. Populating the Database
Here you will populate the database with motorcycle data. Three tables will be created and populated: cycles,
partdescription and parts.
1. Run DBSetup.java. This will populate your motorcycles database.
2. You may view the contents in your database access program. For example MS Access users may open
MSAcccess and open the motorcycles.mdb file and view the three tables.
3. Accessing the Database
A skeleton file Solution.java is provided, in which you fill in the empty methods. Solution.java contains a
main() that let's you execute any of the methods you will implement. You may verify your changes to the
database though your database access program (e.g. MSAccess).
19
1. Implement the connect() method (you may reuse the connect() code from DBSetup.java) and verify
you can connect to the motorcycles database
2. Implement the listParts() method that prints out all rows in the parts table. The SQL is "SELECT *
FROM parts". You may do the same for listCycles(). The latter may have records with a NULL
'power' field in the Result. Handle this case by printing 'not−specified'.
3. Implement the addDucati() method that adds a "Ducati" record to the cycles table. The SQL is
"INSERT INTO cycles VALUES ('monster', 'Ducati', 80, 170)"
4. Implement the deleteDucati() method that removes the Ducati record again. The SQL is "DELETE
FROM cycles WHERE manufacturer = 'Ducati'"
5. Advanced: Implement the listPartsAndDescription() method that prints the description for each part.
Use a prepared statement to get each description separately. (yes, yes a join is easier, but I want you to
use a prepared statement)
20
RESOURCES
[baldwin−660]
Richard G. Baldwin ; JDBC, Introduction to JDBC and Database Access ; online
Java/Javascript tutorials
http://www.dickbaldwin.com/java/Java660.htm
21