//
you're reading...
JDBC

JDBC Code with Oracle – select

1) Install Oracle Database Client

2) set classpath

3) Java code for SelectTest03.java

import java.sql.*;

public class SelectTest03 {

	public static void main(String[] args) {
		if (args.length == 0) {
			throw new IllegalArgumentException("Invalided Parameter:" +
		"java SelectTest03 job");
		}

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			//load the database driver, in this case use 'Oracle'
			//new OracleDriver();
			Class.forName("oracle.jdbc.driver.OracleDriver");

			//Get the database connection
			String dbUrl = "jdbc:oracle:thin:@192.168.1.10:1521:TESTDB";
			String username = "tester";
			String password = "test";
			conn = DriverManager.getConnection(dbUrl, username, password);

			//Get the PreparedStatement, execute the sql
			//Using PreparedStatement is not recommended way to fight string
			//Because the SQL statement string each fight is different, 
                        //so there is no use of the advantages PreparedStatement
			//Still every compiler and what difference per Statement

			//Recommended way placeholders
			//So each SQL statement is the same, 
                        //the database will not compile again
			//This takes advantage of the PreparedStatement, 
                        //significantly improve performance
			//Learn the difference between the Statement and PreparedStatement?
			String sql = "select * from emp where job=?";
			pstmt = conn.prepareStatement(sql);
			//In this case do not add a single quotation mark
			pstmt.setString(1, args[0]);
			rs = pstmt.executeQuery();
			//Get the result set
			while(rs.next()) {
				int empno = rs.getInt("empno");
				String ename = rs.getString("ename");
				System.out.println(empno + ", " + ename);
			}
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {

			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			}catch(SQLException e){}
		}
	}
}
Advertisements

About daviewning

I am an Oracle DBA

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: