|
|
JDBCTM ProgrammingThe 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 ConnectionThis code establishes a connection to an Oracle database. To load the driver and connect to the database, the application needs aConnection object and
Strings
to prepresent the _driver and _url.
The
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 DatabaseThis code constructs a SQLINSERT
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 DatabaseThis code constructs a SQLSELECT
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 FeedbackTell us if you find the New-to-Java Programming Center helpful. We welcome your feedback.
|