我正在尝试获取代码来检查我的用户名和密码是否在数据库中,只是我到处都有错误。你有解决办法吗?
这是我在Login_form中的代码:
PreparedStatement st;
ResultSet rs;
// donnez l'username et le password
String username = jTextField_Username.getText();
String password = String.valueOf(jPasswordField.getPassword());
// requete indiquant si les identifiants existent
String query = "SELECT * FROM 'users' WHERE 'username' = ? AND 'password' = ?";
try {
st = Connecter.getConnection().prepareStatement(query)
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
if(rs.next())
{
// Show my new form
}else{
// Error message
}
} catch (SQLExeption ex) {
Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
}
这是我的连接器代码
package javaapplicationhotel2;
导入java.sql。*;
公共类连接器{
static Object getConnection() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Connection con;
public Connecter() {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch(ClassNotFoundException e){
System.err.println(e);
}
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel","root","");
}catch(SQLException e){System.err.println(e);}
}
Connection obtenirconnexion(){return con;}
PreparedStatement prepareStatement(String select__from_classe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
答案 0 :(得分:0)
问题似乎存在于您的Connecter类中。特别是在getConnection()
和prepareStatement()
方法中,因为它们总是返回抛出UnsupportedException
的方法。另一个问题是getConnection()
的返回类型为Object
,即使您在try块中将其视为连接器也是如此。因此,建议您将getConnection
的返回类型更改为Connection并返回一个new Connection()
或首先使用new Connection()
。另外,您可能希望替换您的setString(int, String)
调用,而这些调用大概替换了'?'与相应的用户名和密码,以及String.format(String, Object...)
。您可以使用此方法替换字符串的某些部分(例如,%s表示字符串,%d表示整数,等等。)因此,在您的情况下,您可以按以下方式使用它:
String format = "SELECT * FROM 'users' WHERE 'username' = %s AND 'password' = %s;"
String query = String.format(format, username, password);
请注意:
在现代的jdbc中,实际上不需要向Class.forName(String)
加载Driver类,因此您可以忽略它。
最后一件事: 如果您下次可以适当地缩进代码,那将是很好的选择,因为这样会使理解起来容易得多。