A very standard sample code for connecting Java to the Oracle database, oracle sample code
The most basic Oracle database connection code (only for Oracle11g ):
1. Right-click Project-> build path-> Configure build path, select the third item "library", click "add external Jar", and select "D: \ Oracle \ app \ oracle \ product \ 11.2.0 \ server \ jdbc \ lib \ ojdbc6_g.jar "(Note: D: \ Oracle is the database installation path ).
2. The following code is a very standard example of Oracle Database Connection code:
/**
* A Very standard sample code for connecting to the Oracle database
*/
Public void testOracle ()
{
Connection con = null; // create a database Connection
PreparedStatement pre = null; // creates a pre-compiled Statement object. This is generally used instead of Statement.
ResultSet result = null; // creates a result set object.
Try
{
Class. forName ("oracle. jdbc. driver. OracleDriver"); // load the Oracle driver
System. out. println ("start trying to connect to the database! ");
String url = "jdbc: oracle:" + "thin: @ 127.0.0.1: 1521: XE"; // 127.0.0.1 is the local address, and XE is the default database name of lite version Oracle.
String user = "system"; // user name, default account name of the system
String password = "147"; // select the password you set during installation
Con = DriverManager. getConnection (url, user, password); // get the connection
System. out. println ("connection successful! ");
String SQL = "select * from student where name =? "; // Pre-compiled statement,"?" Parameter
Pre = con. prepareStatement (SQL); // instantiate a pre-compiled statement
Pre. setString (1, "Liu xianan"); // sets the parameter. The first 1 indicates the index of the parameter, not the index of the column name in the table.
Result = pre.exe cuteQuery (); // execute the query. Note that no parameters need to be added to the brackets.
While (result. next ())
// When the result set is not empty
System. out. println ("student id:" + result. getInt ("id") + "name :"
+ Result. getString ("name "));
}
Catch (Exception e)
{
E. printStackTrace ();
}
Finally
{
Try
{
// Close the above objects one by one, because not closing will affect performance and occupy Resources
// Pay attention to the order of close, and close it first
If (result! = Null)
Result. close ();
If (pre! = Null)
Pre. close ();
If (con! = Null)
Con. close ();
System. out. println ("the database connection is closed! ");
}
Catch (Exception e)
{
E. printStackTrace ();
}
}
}