将数据库连接到 GUI

我在让我的代码与 GUI 一起正常工作时遇到了一些困难。我创建了一个连接到数据库的简单登录程序,该程序在 GUI 中允许用户输入用户名和密码,然后提示数据库以查看用户名和密码是否存在。我创建了一个连接到数据库的类和一个执行 SQL 语句的 DAO 类。我还有两个类,其中一个是接口,另一个包含稍后未实现的方法。


现在,我遇到的问题是将 GUI 连接到我的数据库,这应该通过 DAO 类来完成。我的 GUI 有两个文本字段,应该用来比较用户名和密码,但我不知道该怎么做。另外,我的 DAO 类并未完全实现它,因为它采用 int 作为参数。


如果你能帮助我,我将不胜感激。


UserDAO 类:


public class UserDAO implements IDao<User> {


    DemoDB DemoDBSingleton = null;


    public UserDAO() {

        DemoDBSingleton = DemoDB.getInstance();

    }


    @Override


    public User get(int id) throws NoSuchElementException {

        User user = null;

        try {

            ResultSet resultSet = DemoDBSingleton

                    .excecuteQuery("SELECT user_name, password FROM users WHERE id=" + id);

            if (!resultSet.next())

                throw new NoSuchElementException("The user " + id + " doesn't exist in database");

            else

                DemoDBSingleton.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }


        return user;

    }

}


守候你守候我
浏览 93回答 1
1回答

梵蒂冈之花

也许如果你这样做public class UserDAO implements IDao<User> {&nbsp; &nbsp; DemoDB DemoDBSingleton = null;&nbsp; &nbsp; public UserDAO() {&nbsp; &nbsp; &nbsp; &nbsp; DemoDBSingleton = DemoDB.getInstance();&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean login(String userName, String password) throws NoSuchElementException {&nbsp; &nbsp; &nbsp; &nbsp; boolean login = false;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ResultSet resultSet = DemoDBSingleton&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .excecuteQuery("SELECT user_name, password FROM users WHERE user_name='" + userName + "' AND password = '" + password + "'");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (resultSet.next())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; login = true;&nbsp; &nbsp; &nbsp; &nbsp; } catch (SQLException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; DemoDBSingleton.close();&nbsp; &nbsp; &nbsp; &nbsp; return login;&nbsp; &nbsp; }}并更正您的文本字段JTextField txtUserName = new JTextField(10);JPasswordField txtPassword = new JPasswordField(10);和点击事件private class ClickListener implements ActionListener {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void actionPerformed(ActionEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; UserDAO userDao = new UserDAO();&nbsp; &nbsp; &nbsp; &nbsp; if (userDao.login(txtUserName.getText(), txtPassword.getText())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // here you redirect to your main window&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JOptionPane.showMessageDialog(null, "Incorrect user or password!!!");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java