问题描述
我正在尝试使用 corba 和 java swing 为图形界面创建桌面应用程序。
如您所知,在 CORBA 中,我们必须创建主要方法,例如:连接到数据库、计算...在服务器中,因此我在服务器类中创建了一个用于连接到数据库的方法。
java 类方法如下所示:
public void connect_db(){
// Todo Auto-generated method stub
JTextField txtUsername = FrameLogin.txtUsername;
jpasswordfield pwd= FrameLogin.pwd;
JLabel lblLoginMessage= FrameLogin.lblLoginMessage;
try {
Class.forName("com.MysqL.cj.jdbc.Driver");
Connection conn =(Connection)DriverManager.getConnection("jdbc:MysqL://localhost:3306/utilisateurs","root","Mrayhana123");
Statement stm = conn.createStatement();
String sql="select * from etudiant where username='"+txtUsername+"' and pwd='"+pwd+"'";
ResultSet result = stm.executeQuery(sql);
if(result.next()){
lblLoginMessage.setText("you are connected");
lblLoginMessage.setForeground(Color.GREEN);
}
else {
lblLoginMessage.setText("Incorrect username or password!");
lblLoginMessage.setForeground(Color.RED);
}
} catch(Exception e){
//System.out.println("not connected to database");
e.printstacktrace();
}
}
并且我通过以下方式在包含图形界面的客户端类中调用它:
public static JTextField txtUsername;
public static jpasswordfield pwd;
public static JLabel lblLoginMessage = new JLabel("");
pnlBtnlogin.addMouseListener(new MouseAdapter() {
@Override
String username = txtUsername.getText();
String pwd= pwd.getText();
try {
SraCorbaimpl sci = new SraCorbaimpl();
sci.connect_db();
} catch(Exception e1){
//System.out.println("not connected to database");
e1.printstacktrace();
}
但结果总是显示我的用户名或密码不正确!即使我输入了数据库中的用户名和密码。
感谢您帮助我
解决方法
根据您的 comment,我了解到您已成功连接到数据库,但您的查询未返回任何行。
如果您问题中的代码是您的实际代码,那么您将向 [SQL] 查询传递 JTextField
而不是 JTextField
的文本。密码也是一样。您传递的是 JPasswordField
而不是实际密码。
试试下面的代码。
public void connect_db(){
JTextField txtUsername = FrameLogin.txtUsername;
JPasswordField pwd= FrameLogin.pwd;
JLabel lblLoginMessage= FrameLogin.lblLoginMessage;
try {
// Class.forName("com.mysql.cj.jdbc.Driver"); <- not required
Connection conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/utilisateurs","root","Mrayhana123");
Statement stm = conn.createStatement();
String sql="select * from etudiant where username='"+txtUsername.getText()+"' and pwd='"+pwd.getText()+"'"; // Change here.
ResultSet result = stm.executeQuery(sql);
if(result.next()){
lblLoginMessage.setText("you are connected");
lblLoginMessage.setForeground(Color.GREEN);
}
else {
lblLoginMessage.setText("Incorrect username or password!");
lblLoginMessage.setForeground(Color.RED);
}
} catch(Exception e){
//System.out.println("not connected to database");
e.printStackTrace();
}
因为您使用的是字符串连接,所以 JTextField
的 toString 被插入到您的 SQL 字符串中。
考虑改用 PreparedStatement。
String sql="select * from etudiant where username=? and pwd=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,txtUsername.getText());
ps.setString(2,pwd.getText());
在这种情况下,如果省略 .getText()
,代码将不编译。