首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java Sqlite数据库返回空指针异常,返回数据除外

Java Sqlite数据库返回空指针异常,返回数据除外
EN

Stack Overflow用户
提问于 2018-10-05 01:43:05
回答 1查看 133关注 0票数 0

我正在用Java编写一个桌面应用程序,并且我正在使用一个SQLite数据库。我正在从SQLite studio获取数据,它被获取了,但是当我在应用程序中获取它时,我得到了一个空指针。

下面是连接数据库并调用与db相关的函数的数据库管理器类:

DB类:

代码语言:javascript
复制
public class DBManager {
Connection con=null;//build connection
Statement stmt=null;//execute query
static PreparedStatement pst= null;
public DBManager(){
    try {
        Class.forName("org.sqlite.JDBC");
        String url="jdbc:sqlite:mobileDB.db";
        con=DriverManager.getConnection(url);
        stmt=con.createStatement();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}
public void insertUpdateDelete(String query){
    try{
        stmt.execute(query);
    }catch(Exception ex){
        System.out.print(ex.toString());
    }
}
public ResultSet select(String query){
    try{
        ResultSet rs= stmt.executeQuery(query);
        return rs;
    }catch(Exception ex){
        ex.printStackTrace();
        return null;
    }
}
public ResultSet getLogInRecord(String user,String pass, String role) throws SQLException {
    String query="select * from Users where Username=? and Password=? and Role=?";
    pst.setString(0, user);
    pst.setString(1, pass);
    pst.setString(2, role);
    pst=con.prepareStatement(query);
    ResultSet rs=pst.executeQuery();
    return rs;

}

函数调用:

代码语言:javascript
复制
btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                String username=txtUsername.getText(),password=txtPass.getText(),role=cmbRole.getSelectedItem().toString();
                if(username.equals("")||password.equals("")||role.equals("Select")) {
                    JOptionPane.showMessageDialog(frame, "Please input all the data. No empty data allowed.","Empty Fields",JOptionPane.ERROR_MESSAGE);
                }else {
                    DBManager dbm= new DBManager();
                    //ResultSet rs= dbm.getLogInRecord(username, password, role);
                    ResultSet rs=dbm.select("select * from Users where Username='admin' and Password='admin' and Role='Admin'");
                    if(rs.next()) {
                        JOptionPane.showMessageDialog(frame, "True","Error",JOptionPane.ERROR_MESSAGE);
                    }else {
                        JOptionPane.showMessageDialog(frame, "False","Error",JOptionPane.ERROR_MESSAGE);
                    }
                }
            }catch (Exception e) {
                JOptionPane.showMessageDialog(frame, e,"Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    });
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52652602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档