The jdbc class that establishes a connection between java and Oracle database

Due to a new requirement of the work, it is necessary to call the java code through the ETL data collection tool, and the java code needs to find out the data from another database. First of all, I thought of finding out the data in the database through jdbc , and then performing logical operations.

So I thought of sorting out the next common jdbc connection class by the way, so that it can be used directly in the future.

 

1. Download an Oracle jar package from Oracle 's official website or elsewhere :



 

2. Write the code:

public static void main(String[] args) {
		Connection con = null; //Create a database connection
		PreparedStatement pre = null; //Create a precompiled statement object and precompile the sql statement
		ResultSet res = null; //Create a query result object

		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");// 加载驱动
			System.out.println("Start trying to connect to the database");
			String url = "jdbc:oracle:" + "thin:@127.0.0.1:1521:orcl";// Note @, 127.0.0.1 is the local address, 1521 port number, orcl database name
			String user = "shopping";//Username
			String psw = "123456";//Password
			con = DriverManager.getConnection(url, user, psw);// Get the connection
			System.out.println("Connection succeeded");
			String sql = "select * from person where name=?";//"?" represents the parameter
			pre = con.prepareStatement(sql);// precompiled sql statement
                        pre.setString(1, "Zhang San");//1 represents the first "?", parameter index
			res = pre.executeQuery();// Execute the query
			while (res.next()) {// The judgment result is not empty
				System.out.println(res.getString("name"));
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} finally {

			try {//Close the objects one by one, and close the ones used later to avoid occupying resources
				if (res != null) {
					res.close();
				}
				if (pre != null) {
					pre.close();
				}
				if (con != null) {
					con.close();
				}
				System.out.println("Database connection closed");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
	}

 

Note: Running the code at this point gives the following error,

 



 

 

This is a very common error. The program is not finished here. Don't forget the Oracle jar package you just downloaded , which needs to be imported.

 

Right-click on the project ---->build path---->Add External JARs …-- --> Add the jar package you just downloaded , and re-run the program .

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326801503&siteId=291194637