How to call method from a database connection class

Zujaj Misbah Khan picture Zujaj Misbah Khan · Feb 1, 2015 · Viewed 16.6k times · Source

Recently I am making a small system in which I've 3 packages using Ms Access as database

1)Classes----> Based on OOP concepts

2)GUI------> The Jform + .java files

3)Images---->Just some icons i made

I've made a DBConnection class in the Classes package(using UCanAccess).

import java.sql.*;
public class DBConnection {
public DBConnection() {

    try {
        String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
        Class.forName(driver);
        String dbPath = "jdbc:ucanaccess://E:\\University Docs\\BSCS 3A\\Object Oriented Programming\\LibraryManagementSystem\\LMSDatabase.accdb";
        Connection con = DriverManager.getConnection(dbPath);
        Statement st = con.createStatement();
        System.out.println("Connection Succesful");
        ResultSet rsObject = st.executeQuery(dbPath);
        con.close();
    } catch (Exception sqlEx) {
        System.out.println(sqlEx);
}
}                    }

Next I've made a Loger class for creating a login and logout methods in the same package.The problem is that how do I execute my query in this class by using the DBConnection Class?This is the code for Loger class

public class Loger { 

private String lname, lpassword;

public Loger(String lname, String lpassword) {
    this.lname = lname;
    this.lpassword = lpassword;
    //Login();
}


public String Login()throws ClassNotFoundException,SQLException
{
    DBConnection d1 = new DBConnection();
    String query1 = "SELECT * FROM Admintable WHERE Admin_ID = ' "+this.lname+" AND Admin_Password = '"+this.lpassword+"'" ;

    return "Success!";

}                   }

In short I am stuck please help because I have to make more classes (OOP based)and just make methods in such classes to execute different queries.

Answer

codechefvaibhavkashyap picture codechefvaibhavkashyap · Feb 1, 2015

You need mysql-connector-java API which is to be imported in your project through project properties -> Libraries -> add jar.

Follow the sample code:

public class Database {
    Connection conObj;
    Statement stObj;

    public Database() throws SQLException , ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver"); /*Loading Driver class for JDBC*/

 conObj = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytestdb","root",""); /*Creating Connection class's Object which consist of database url , username and password*/

stObj = conObj.createStatement();/*Creating Statement Class's object which is responsible for performing all db tasks*/
    }

    public void fetchData() throws Exception
    {
        String query = "select * from user";
        ResultSet rs = stObj.executeQuery(query);

        while(rs.next())
        {
            System.out.println("Name : "+rs.getString("name"));
            System.out.println("age : "+rs.getInt("age"));
        }
    }

    public void insertData(String name, int age) throws SQLException 
    {
        if(name!=null && age!=0)
        {
            String query = "insert into user values(\""+name+"\","+age+")";
            int a = stObj.executeUpdate(query);

            if(a == 1)
            {
                System.out.println("Update Successful");
            }
            else
            {
                System.out.println("Update Failed");
            }
        }
    }

    void deleteData() {
    }

    void deleteData(String name) throws Exception 
    {
        String query = "delete from user where name = \""+name+"\"";
        int a = stObj.executeUpdate(query);

        if(a == 1)
        {
                System.out.println("delete Successful");
        }
        else
        {
                System.out.println("deletion Failed");
        }
    }
}

public class main {

    public static Database d;
    public static Scanner sc;

    static 
    {
        try{
            sc = new Scanner(System.in); 
            d = new Database();
        }
        catch(Exception e)
        {
            throw new RuntimeException(e);
        }
    }

  public static void main(String... q)
  {
      main mn = new main();
      try{
          System.out.println("Enter your option");
          System.out.println("1) fetch data");
          System.out.println("2) insert data");
          System.out.println("3) delete data");
          System.out.println("\n /////////////////////////// \n");
          int a = sc.nextInt();
          switch(a)
          {
              case 1 :
                  mn.fetchData();
                  break;
              case 2 :
                  mn.takeDetails();
                  break;
              case 3 :
                  mn.deleteData();
                  break;
              default:
                  System.out.println("Try Again");
                  break;
          }
      }
      catch(Exception e)
      {
          e.printStackTrace();
      }
  }

  public void takeDetails() throws Exception
  {
     System.out.println("Enter name");
     String name = sc.next();
     System.out.println("Enter age");
     int age = sc.nextInt();
     d.insertData(name, age);
  }

  public void fetchData() throws Exception
  {
      d.fetchData();
  }

  private void deleteData() throws Exception {
        System.out.println("Enter name of the user whose record is to be deleted");
        String name = sc.next();
        d.deleteData(name);
    }
}

Read the comments written in between for explanation.For Complete tutorial follow the link Hope this helps.