JDBCTM
Programming
The JDBCTM application
programming interface (API)
makes it possible to connect to a database, send SQL commands
to
that database, and process the returned results set. JDBC
provides
uniform access to a wide range of relational databases and
serves
as a common base on which database tools can be built.
Establish Connection
This code establishes a connection to an Oracle database.
To load the driver and connect to the database, the
application
needs a Connection
object and
Strings
to prepresent the _driver
and _url
.
The _url
string is in the form of a Uniform
Resource
Locator (URL). It consists of the URL, Oracle subprotocol, and
Oracle data source in the form jdbc:oracle:thin
,
the database username login, password, plus port, and
protocol information.
final static private String _driver =
"oracle.jdbc.driver.OracleDriver";
final static private String _url =
"jdbc:oracle:thin:username/password@developer:1521:jdcsid";
try{
// Load the Driver
Class.forName (_driver);
// Make Connection
c = DriverManager.getConnection(_url);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
Write to Database
This code constructs a SQL INSERT
statement to write a simple text sting to a table
named StringTable
.
Statement stmt = null;
String text = new String ("some text");
try
{
stmt = c.createStatement();
int count = stmt.executeUpdate ("insert into StringTable
(text) values
('"+text+"')");
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
stmt.close();
}
catch (Exception e)
{
}
}
Read From Database
This code constructs a SQL SELECT
statment to return the rows of data in the
StringTable
table in a ResultsSet
object.
Statement stmt = null;
ResultSet results = null;
try
{
smt = c.createStatement();
results = stmt.executeQuery ("select text from SringTable");
while ( results.next())
{
System.out.println (results.getString ("text"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
results.close();
}
catch (Exception e)
{
}
try
{
stmt.close();
}
catch (Exception e)
{
}
}

Reader Feedback
Tell us if you find the New-to-Java Programming Center
helpful. We welcome your feedback.