Sunday 18 September 2011

JDBC CONNECTIVITY


JAVA TO DATABASE CONNECTIVITY USING JDBC


AIM:
To implement database connectivity from java to database using JDBC.

ALGORITHM:

STEP 1: Start the program
STEP 2: Register the JdbcOdbc driver using Register API function
STEP 3: Connect the database through the data source name using the username and password using the getConnection API function.
STEP 4: Create a statement object.
STEP 5: Access the database using the Execute Query function.
STEP 6: Display the result set.
STEP 7: Close all the connections.


PROGRAM

import java.sql.*;
import java.io.*;
class JdbcTest
{
public static void main(String args[])throws SQLException, IOException
{
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

System.out.println("Please enter information to test connection to the database");
String user;
String password;
user=readEntry("user:");
int slash_index=user.indexOf('/');
if(slash_index!=-1)
{
password=user.substring(slash_index+1);
user=user.substring(0,slash_index);
}
else
password=readEntry("password:");

System.out.print("connecting to the database...");
System.out.flush();
System.out.println("Connecting...");
Connection conn= DriverManager.getConnection("jdbc:odbc:jasu",user,password);

System.out.println("connected");
Statement stmt=conn.createStatement();
ResultSet rset=stmt.executeQuery("select empno, ename,job from emp");

while(rset.next())
{
System.out.print(rset.getInt(1)+"\t");
System.out.print(rset.getString(2)+"\t");
System.out.println(rset.getString(3));
}

rset.close();
stmt.close();
conn.close();
System.out.println("Your JDBC installation is correct");
}

static String readEntry(String prompt)
{
try
{
StringBuffer buffer=new StringBuffer();
System.out.println(prompt);
System.out.flush();

int c=System.in.read();

while(c!='\n'&&c!=-1)
{
buffer.append((char)c);
c=System.in.read();
}
return buffer.toString().trim();
}
catch(IOException e){return"";}
}
}

0 comments:

Post a Comment