Pages

Monday, April 19, 2010

Fetch data from MS Access using java

Database

JDBCExample


import  java.sql.*;

public class JDBCExample
{

private String url,user,pwd;
private Connection conn;
private Statement stmt;
private PreparedStatement pstmt;
private ResultSet rs;

public JDBCExample()
{
}

public void testDatabase()
{
int i=0;
String sql;

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception sqe)
{
System.out.println("Error loading driver");
}
url="jdbc:odbc:emp";



pwd ="";
user="";

try
{
conn=DriverManager.getConnection(url,user,pwd);
}
catch(SQLException sqe)
{
System.out.println("Error getting connection to database");
}

try
{
stmt=conn.createStatement();
}
catch(SQLException sqee)
{
System.out.println("Error creating statement");
}

try
{
rs=stmt.executeQuery("select * from emp");
}
catch(SQLException qexe)
{
System.out.println("Error executing query");
}





/*try
{
while(rs.next())
{
int code=rs.getInt(1);
System.out.println("code="+code);
}
}

catch(SQLException e)
{
System.out.println("error to trversing");
}*/

try
{
while(rs.next())
{
String name=rs.getString(1);
int rollno=rs.getInt(2);
String add=rs.getString(3);
int phoneno=rs.getInt(4);
System.out.println("name="+name);
System.out.println("rollno="+rollno);
System.out.println("add="+add);
System.out.println("phoneno="+phoneno);
System.out.println("      ");

}


}

catch(SQLException es)
{
System.out.println("error to traversing");
}


try
{
rs.close();
conn.close();
}
catch(SQLException sqxe)
{
System.out.println("Error closing result set or connection");
}
}

public static void main(String args[])
{
JDBCExample jdbcex=new JDBCExample();
jdbcex.testDatabase();

}
}

No comments:

Post a Comment

Followers