The most basic Oracle database connection code (only for Oracle11g):
1. Right-click the project->Build Path->Configure Build Path, select the third item "Library", then 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 installation path of the database).
2. The following code is a very standard Oracle database connection code example:
Copy the code code as follows:
/**
* A very standard sample code for connecting to Oracle database
*/
public void testOracle()
{
Connection con = null; // Create a database connection
PreparedStatement pre = null; // Create a precompiled statement object. This is generally used instead of Statement.
ResultSet result = null;//Create 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 the streamlined version of Oracle
String user = "system"; // User name, system default account name
String password = "147";//The password you chose during installation
con = DriverManager.getConnection(url, user, password);//Get the connection
System.out.println("Connection successful!");
String sql = "select * from student where name=?";//Precompiled statement, "?" represents parameters
pre = con.prepareStatement(sql); // Instantiate a precompiled statement
pre.setString(1, "Liu Xian'an");//Set parameters, the first 1 indicates the index of the parameter, not the index of the column name in the table
result = pre.executeQuery();//Execute the query, please note that no parameters are required in 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 if they are not closed, it will affect performance and occupy resources.
// Pay attention to the order of closing, the last used one is closed first
if (result != null)
result.close();
if (pre != null)
pre.close();
if (con != null)
con.close();
System.out.println("Database connection has been closed!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}