我正在使用java应用程序在登录页面上工作,尝试将其连接到我创建的访问数据库,只是想要一个简单的选择查询来检查输入的用户名和密码是否有效,我没有得到任何错误执行,但按钮不起作用,任何想法?
以下是代码:
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class Login {
Connection con;
Statement st;
ResultSet rs;
JFrame f = new JFrame("User Login");
JLabel l = new JLabel("Username");
JLabel ll= new JLabel("Password");
JTextField t = new JTextField(10);
JTextField t1 = new JTextField(10);
JButton b = new JButton("Login");
public Login()
{
connect();
frame();
}
public void connect()
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:db1";
con = DriverManager.getConnection(db);
st = con.createStatement();
}
catch (Exception ex)
{
}
}
public void frame()
{
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
JPanel p = new JPanel();
p.add(l);
p.add(t);
p.add(ll);
p.add(t1);
p.add(b);
f.add(p);
b.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
try{
String user = t.getText().trim();
String pass = t1.getText().trim();
String sql = "select username, password from Users where username =
'"+user+"' and password= '"+pass+"'";
rs = st.executeQuery(sql);
int count = 0;
while(rs.next())
{
count = count +1;
}
if (count == 1)
{
JOptionPane.showMessageDialog(null, "User Found, Access
Granted!");
}
else if (count > 1)
{
JOptionPane.showMessageDialog(null, "Duplicate User,
Access Denied!");
}
else {
JOptionPane.showMessageDialog(null, "User not Found!");
}
}
catch(Exception ex)
{}
}
});
}
public static void main(String [] args)
{
new Login ();
}
}
答案 0 :(得分:0)
你究竟是什么意思"按钮不起作用"?事件永远不会被触发,或者事件中的代码对您没有产生任何结果这一事实?
如果您打算使用记录计数来确定是否存在特定的用户/密码,那么我建议您这样做:
int count = 0;
conn.setAutoCommit(false);
PreparedStatement stmt = conn.prepareStatement("SELECT COUNT(*) AS rCount FROM Users WHERE username = '" + user + "' AND password = '" + pass + "';");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
count = rs.getInt("rCount");
}
rs.close();
stmt.close();
if (count != 0) {
JOptionPane.showMessageDialog(null, "User Found, Access Granted!");
}
但是,您也可以这样做:
conn.setAutoCommit(false);
PreparedStatement stmt = conn.prepareStatement("SELECT username, password FROM Users WHERE username = '" + user + "' AND password = '" + pass + "';");
ResultSet rs = stmt.executeQuery();
String un = "";
String up = "";
while (rs.next()) {
un = rs.getString("username");
up = rs.getString("password");
// or any other table fields you want...
}
rs.close();
stmt.close();
if (!un.equals("") && !up.equals("")) {
JOptionPane.showMessageDialog(null, "User Found, Access Granted!");
}
您可能还想查看使用UCanAccess库。它与MS Access一起工作得非常好。