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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28265482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:18:06  来源:igfitidea点击:

How to call method from a database connection class

javadatabaseoopucanaccess

提问by Anynomous Khan

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

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

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

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

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

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

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

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

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

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

Next I've made a Logerclass 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 DBConnectionClass?This is the code for Logerclass

接下来我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!";

}                   }

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

简而言之,我被卡住了,请帮忙,因为我必须创建更多类(OOP基于)并且只在这些类中创建方法来执行不同的查询。

回答by codechefvaibhavkashyap

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

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

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 linkHope this helps.

阅读中间的评论以进行解释。对于完整的教程,请点击链接希望这会有所帮助。

回答by Minar Mahmud

The way u are designingthe classes, u can do:

你设计课程的方式,你可以做到:

Omit these 2 lines from DBconnection()to use the connection:

省略这 2 行 fromDBconnection()以使用连接:

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

And make st, connetc member variable of DBConnection so u can use them from outside the class.

做优做强stconnDBConnection进行的等成员变量,这样你们可以从类外使用它们。

In the Loggerclass do:

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

But I would design the classes in a bit different manner.

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

I would create a login method in DBConnection. Like

我会在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;
}

Then in login()of Logger:

然后在login()Logger

DBConnection d1 = new DBConnection(); // no connections in constructor
boolean logged = d1.login(this.lname, this.lpassword);