Saturday, November 1, 2008

JDBC Simple example

1. I used here postgresSQL database to run this example. You can use any database, only you have to put database driver in your system environment classPath
(As my PC, path of database drive c:\jar\postgresql-8.1dev-403.jdbc2ee.jar)
2. Create database table

CREATE TABLE users(
username varchar(15) NOT NULL,
name varchar(255) NOT NULL,
pass varchar(15) NOT NULL,
CONSTRAINT users_pkey PRIMARY KEY (username))
WITHOUT OIDS;

3. Insert data into this table
insert into users values ('Binod','Binod Kumar Suman','satyam');
insert into users values ('Pramod','Pramod Kumar','Patni');
commit;

4. Write java code (Say DatabaseTest.java)

import java.sql.* ;
class DatabaseTest{
public static void main( String args[] ) {
try {
System.out.println("********** USER INFORMATION ************"); System.out.println("\n");
Class.forName( "org.postgresql.Driver" ) ;
Connection conn = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/postgres","postgres","suman") ;
Statement stmt = conn.createStatement() ;
ResultSet rs = stmt.executeQuery( "SELECT * FROM users" ) ;
while( rs.next() ){
System.out.print("USERNAME :: "+rs.getString(1) +" ") ;
System.out.print("NAME :: "+rs.getString(2) +" ") ;
System.out.println("PASSWORD ::"+rs.getString(3) ) ;
}
rs.close() ;
stmt.close() ;
conn.close() ;
} catch( SQLException se )
{ System.out.println( "SQL Exception :: "+se ) ; }
catch( Exception e ) { System.out.println( e ) ; } }
}

5. Compile the code and run the code.
C:\>javac DatabaseTest.java
C:\>java DatabaseTest
********** USER INFORMATION ************
USERNAME :: Pramod NAME :: Pramod Kumar PASSWORD ::Patni
USERNAME :: Binod NAME :: Binod Kumar Suman PASSWORD ::satyam

No comments:

Post a Comment

You can put your comments here (Either feedback or your Question related to blog)