如何从数据库连接类调用方法

时间:2015-02-01 17:20:25

标签: java database oop ucanaccess

最近,我正在制作一个小型系统,其中我使用Ms Access作为数据库的3个软件包

1)类---->基于OOP概念

2)GUI ------> Jform + .java文件

3)图像---->我做的一些图标

我在Classes包中创建了一个DBConnection类(使用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);
}
}                    }

接下来,我已经创建了一个Loger类来在同一个包中创建登录和注销方法。问题是如何使用DBConnection在此类中执行查询Class?这是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!";

}                   }

总之,我被困了请求帮助,因为我必须制作更多的类(基于OOP)并且只在这些类中创建方法来执行不同的查询。

2 个答案:

答案 0 :(得分:1)

您需要通过项目属性在项目中导入的mysql-connector-java API - >图书馆 - >添加jar。

按照示例代码:

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);
    }
}

阅读其中的评论以获得解释。有关完整教程,请按照link进行操作 希望这会有所帮助。

答案 1 :(得分:0)

  

您正在设计类的方式,您可以这样做:

忽略DBconnection()中的这两行以使用连接:

ResultSet rsObject = st.executeQuery(dbPath);
con.close();

并创建DBConnection的stconn等成员变量,以便您可以在课外使用它们。

Logger班级中执行:

public String Login()throws ClassNotFoundException,SQLException
{
    try {
        DBConnection d1 = new DBConnection();
        String query1 = "SELECT * FROM Admintable WHERE Admin_ID = ' "+this.lname+" AND Admin_Password = '"+this.lpassword+"'" ;
        Resultset rs = d1.st.executeQuery(query1);  // assuming st is "default". 
                                                    // or u can make st private and use a get method (better) 
        // Check login, set to a "stringObject" //declare outside the scope of try-catch        
    } catch(Exception ex) {
        //
    }
    return stringObject; 
}   
  

但我会以不同的方式设计课程。

我会在DBConnection中创建一个登录方法。像

public boolean login(String id, String pass) {
    boolean loggedin = false;
    try {
        // Connect to db
        // execute SQL
        // modify loggedin if necessary
    } catch (...) {
    } finally {
        try {
            // close connections
        } catch(...) {
        }
    }
    return loggedin;
}

然后在login()的{​​{1}}中:

Logger