3

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

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

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

3)图像---->只是我制作的一些图标

DBConnection在 Classes 包中创建了一个类(使用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?这是Loger类的代码

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基于)并且只在这些类中创建方法来执行不同的查询。

4

2 回答 2

2

您需要通过项目属性 -> 库 -> 添加 jar 将 mysql-connector-java API 导入到您的项目中。

按照示例代码:

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

阅读中间写的评论以获得解释。完整的教程请点击链接 希望这会有所帮助。

于 2015-02-01T17:29:31.860 回答
0

您设计课程的方式,您可以:

省略这两行DBconnection()以使用连接:

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

并 makestconnDBConnection 的成员变量,以便您可以从类外使用它们。

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()Logger

DBConnection d1 = new DBConnection(); // no connections in constructor
boolean logged = d1.login(this.lname, this.lpassword);
于 2015-02-01T18:04:21.397 回答