importjava.awt.*;importjavax.swing.*;importjava.awt.event.*;importjava.sql.*;importjava.sql.Connection;importjava.sql.DriverManager;publicclassLoginimplementsActionListen...
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
public class Login implements ActionListener{
JFrame fram;
JLabel l1,l2;
JButton b1,b2;
JTextField tf1;
JPasswordField pf;
public static void main(String agrs[]){
Login login=new Login();
login.Display();
}
void Display(){
JFrame frame=new JFrame("登录窗口");
Container cp=frame.getContentPane();
JPanel p1,p2,p3,p4,main_jp;
main_jp=new JPanel(new GridLayout(2,1,10,10));
p1=new JPanel(new GridLayout(2,2,10,10));
main_jp.add(p1);
p2=new JPanel(new FlowLayout(FlowLayout.CENTER,10,10));
main_jp.add(p2);
p3=new JPanel(new FlowLayout(FlowLayout.LEFT));
p4=new JPanel(new FlowLayout(FlowLayout.LEFT));
cp.add(main_jp);
l1=new JLabel("用户名:",JLabel.CENTER);
l2=new JLabel("密码:",JLabel.CENTER);
tf1=new JTextField(15);
pf=new JPasswordField(15);
p3.add(tf1);
p4.add(pf);
p1.add(l1);
p1.add(p3);
p1.add(l2);
p1.add(p4);
//char[] pw=pf.getPassword();
//String inputUserName=tf1.getText();
//String inputUserPwd=new String(pw);
b1=new JButton("登录");
b2=new JButton("退出");
b1.addActionListener(this);
b2.addActionListener(this);
p2.add(b1);
p2.add(b2);
frame.setSize(400,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b2){
System.exit(0);
}
if(e.getSource()==b1){
char[] pw=pf.getPassword();
String inputUserName=tf1.getText();
String inputUserPwd=new String(pw);
String user_name=null;
String user_pwd=null;
String driverName="com.mysql.jdbc.Driver";
//数据库用户名
String userName="root";
//密码
String userPasswd="xsy341341";
//数据库名
String dbName="a";
//表名
String tableName="mydb";
//联结字符串
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql="SELECT * FROM "+tableName; //注意FROM后面有空格。
ResultSet rs = statement.executeQuery(sql);
user_name=rs.getString("id");
user_pwd=rs.getString("pwd");
if(inputUserName.equals(user_name)&&inputUserPwd.equals(user_pwd))
JOptionPane.showConfirmDialog(null,"成功登录"," ",JOptionPane.DEFAULT_OPTION);
else
JOptionPane.showConfirmDialog(null,"用户名或密码错误"," ",JOptionPane.DEFAULT_OPTION);
}catch(Exception e2){
System.out.println("出现异常情况");
}
}
}
}
经过反复修改,现在异常已经不会出现了,只是在输入用户名和密码时,java程序只会搜索mysql数据库相应的表的第一行(总行有三行),符合第一行的就能登录,而符合第二行第三行的都不能登录,这不是我想要的。我想要是的在登录界面输入时,程序可以检索mysql里的三行数据,只要符合其中任意一行就可以登录。
展开