Thursday, December 2, 2010

Calling SQL Statment Inside Java Code

One of the important way for developing is calling a sql statment inside your java code and I will explain how to do this:
1- call a select statment
asume we want to make a function take department Id and return its name so we will make this function
public String getDeptName(int deptId)
{
PreparedStatement stat = null;
ResultSet rs = null;
try
{
String sql = "select dept_name from departments where dept_id=" + deptId;
stat = getAm().getDBTransaction().createPreparedStatement(sql, 1);
rs = stat.executeQuery();
if (rs.next())
{
return rs.getString(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (rs != null)
try
{
rs.close();
}
catch (Exception e)
{
}

if (stat != null)
try
{
stat.close();
}
catch (Exception e)
{
}
}
return null;
}
2- Call an updatable statment as (Create, Insert, Update and Delete)asume we want to make a function take department id and delete it
public void deleteDepartment(int deptId)
{
PreparedStatement stat = null;
try
{
String sql = "DELETE FROM Dept WHERE dept_id=" + deptId;
stat = getAm().getDBTransaction().createPreparedStatement(sql, 1);
stat.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if(stat != null)
try
{
stat.close();
}
catch(Exception e) { }
}
return null;
}

where getAm() is a method return your Application Module as :
public AppModuleImpl getAm()
{
AppModuleImpl am =
(AppModuleImpl) ADFUtils.getApplicationModuleForDataControl("AppModuleDataControl");
return am;
}

3 comments:

  1. As in your post used getAm().getDbtConnection()
    how we can create and wht is it Can you expain.

    ReplyDelete
  2. Hi Suresh,
    getAm() is a method that return your Application Module. In getAm() method you should write your Data Control Name as "AppModuleDataControl" so the method will be
    public AppModuleImpl getAm()
    {
    AppModuleImpl am =
    (AppModuleImpl) ADFUtils.getApplicationModuleForDataControl("AppModuleDataControl");
    return am;
    }

    and about this line :
    stat = getAm().getDbtConnection().createPreparedStatement(sql, 1);

    I modified it to
    stat = getAm().getDBTransaction().createPreparedStatement(sql, 1);

    because Application Module has a DBTransaction Not DbtConnection.

    ReplyDelete