Sunday, 15 February 2015

ACCESSING DATABASE.

      Working with data is important thing. We might need the knowledge of data base and the command for reading the data from the database such as DML and DDL commands. Here we are not going discuss the DML and DDL command, for the time being we are discussing about connecting to database using a java program and working with result, by knowing this basic you get basic idea of database testing and verifying the data in database. Consider the below given sample program.

import java.sql.*;
public class Database
 {
    public static void main(String[] args)
      {
         try
            {
               Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
               String accessFileName = "C:/Users/RAHUL/Desktop/workspace2/Database1";
               final String connURL="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb,         *.accdb)};DBQ="+accessFileName+".accdb;";

               Connection con = DriverManager.getConnection(connURL, "","")
               Statement stmt = con.createStatement();
               stmt.execute("select * from test where Name='Das'");
               ResultSet rs = stmt.getResultSet();
               if (rs != null)
                   while ( rs.next() )
                     {
                       System.out.println("Name: " + rs.getString("ID") + " ID: "+rs.getString("Name"));
                      }
                   stmt.close();
                   con.close();
             }
         catch (Exception err)
            {
                  System.out.println("ERROR: " + err);
             }
     }
}
       Consider the above given java program for accessing a data base. We are importing the java sql package for accessing the database. We are storing the path of the database string, in this example am using Microsoft’s access database. The next thing we do is connecting to the database connection string, and we get the connection

    Connection con = DriverManager.getConnection (connURL, "","")

    Now we execute the query
    stmt.execute("select * from test where Name=Joe");

    And we can retrieve the result
    ResultSet rs = stmt.getResultSet();

    Where the result is store in “rs “, and we can use the retrieved data in the program.

No comments:

Post a Comment