我正在尝试对MS Access DB进行授权JFrame,但是查询似乎无法正常运行。想法是输入登录名和密码,如果其中之一不正确,则会显示一条消息。我的代码总是将我引向异常。这是我的代码,也许有人可以帮助我。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class First {
JFrame frame;
JPanel txt, but;
JButton log, ext;
JTextField login;
JLabel l, p;
JPasswordField pass;
PreparedStatement prepst;
ResultSet res;
public First() {
frame = new JFrame("Authorization");
txt = new JPanel();
but = new JPanel();
log = new JButton("Login");
ext = new JButton("Quit");
login = new JTextField(10);
l = new JLabel("Login:");
p = new JLabel("Password:");
pass = new JPasswordField(10);
frame.setSize(400,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt.add(l);
txt.add(login);
txt.add(p);
txt.add(pass);
frame.add(txt,BorderLayout.NORTH);
but.add(log);
but.add(ext);
frame.add(but,BorderLayout.SOUTH);
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String PathToDataBase = "D:/workspace2/MicrosoftAccessConnection/db";
String DataBase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
DataBase += PathToDataBase.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection(DataBase,"","");
prepst = con.prepareStatement("SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?");
String lll = login.getText();
String ppp = pass.getText();
prepst.setString(1,lll);
prepst.setString(2, ppp);
res = prepst.executeQuery();
if((test(con,lll,ppp)) == true) {
while(res.next()) {
if((lll.equals(res.getString("LOGIN"))) && (ppp.equals(res.getString("PASSWORD")))) {
lol();
} else {
JOptionPane.showMessageDialog(null, "Wrong data");
}
}
}
res.close();
prepst.close();
con.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error with connection");
}
}
});
ext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
frame.dispose();
}
});
frame.setVisible(true);
}
public void lol() {
JFrame f = new JFrame("SUCCESS");
f.setSize(200,200);
frame.dispose();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
boolean test(Connection con, String login, String pass) throws SQLException {
int rez = 0;
PreparedStatement st = con.prepareStatement("SELECT COUNT(*) FROM USERS WHERE LOGIN=? AND PASSWORD=?");
st.setString(1, login);
st.setString(2, pass);
ResultSet res = st.executeQuery();
while (res.next()) {
rez = res.getInt(1);
}
st.close();
return rez == 1;
}
public static void main(String[] args) {
new First();
}
}
最佳答案
您缺少PreparedStatement
中的SQL
占位符,请替换
SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?
与
SELECT * FROM USERS WHERE LOGIN=? AND PASSWORD=?
^
如果得到
Exception
,则始终最好显示异常内容。您可以将其添加到异常块:e.printStackTrace();