Sunday, September 18, 2011

Simple JDBC

package main.java.concepts;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo {

	//	Just an extra TIP - Signature of main
	
	//	public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
	//	static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
	//	void: main does not return anything so the return type must be void
	//	The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		
		Connection con = null;
		Statement st = null;
		ResultSet rs = null;

		try {

			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			con = DriverManager.getConnection("localhost:3403", "ashish", "ashish");
			st = con.createStatement();
			rs = st.executeQuery("select * from emp");

			while (rs.next()) {
				System.out.println(rs.getString(1));
				System.out.println(rs.getInt(2));
				System.out.println(rs.getString(3));
			}
		} catch (SQLException se) {
			se.printStackTrace();
		} finally {
			if (con != null)
				con.close();
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
		}
	}

}

1 comment: