JDBC Sample Code


JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment.

The following code is a sample to connect the course Oracle database:

...

String jdbcURL = "jdbc:oracle:thin:@orca.csc.ncsu.edu:1521:ORCL";
Connection conn = null;
Statement stmt = null;
ResultSet rs =null;
String user ="yzhang12" ;
String passwd ="guest";

try {

 Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
 conn = DriverManager.getConnection(jdbcURL,user,passwd);

 stmt = conn.createStatement();
 rs = stmt.executeQuery("SELECT * FROM yzhang12.student);

} catch ...

The above fragment of code connects the course Oracle database under the account 'yzhang12', and selects all tuples from the table 'student', a sample table I created before hand. Here is the result:

NAME UNITYID ADDRESS STATUS
Yi Zhang yzhang12 Suite 243, Venture III Ph.D. Student
Student1 stu1 Suite 150, Venture II Master Student

 

You could replace 'yzhang12' in the above code with your own UnityID, and replace 'guest' with your course database password. 

 

A tip for the programming assignment: 

 

In the first programming assignment, you are required to take over the input from users about their usernames and password, and check these against the registered user table in your database. One way to do this is to using the PreparedStatement class in the JDBC API. A sample for this is:

String loginID = request.getParameter("LoginID");  // the loginID is the user name from the input
String password = request.getParameter("pwd"); // the pwd is the password from the input
String jdbcURL = "jdbc:oracle:thin:@orca.csc.ncsu.edu:1521:ORCL";
Connection conn = null;
Statement stmt = null;
ResultSet rs =null;
String user ="XXX" ;
String passwd ="YYY";
try{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
conn = DriverManager.getConnection(jdbcURL,user,passwd);

String template = new String();
template = "SELECT * FROM XXX.registeredUser WHERE NAME = ? AND PASSWORD= ?"; 

                                        // registeredUser is the table you created in the databasefor registered users.
PreparedStatement pstmt = conn.prepareStatement(template);
pstmt.setString(1, loginID);
pstmt.setString(2, password);
rs = pstmt.executeQuery();

...

} catch ...

For how to incorporate JSP, JDBC and Tomcate, please click here to view the example. (Reminder you should download appropriate version of JDBC drive to make Tomcat recognize the JDBC API you call in your code.)  For more information about JDBC and API, please visit JDBC Tutorial.

 

 

 

Go Back to TA Page

 


Course Webpage | JSP | Servlet | Apache Ant | Apache Jakarta Tomcat | FAQ | Contact Us