【发布时间】:2021-11-15 08:06:41
【问题描述】:
我在 String passwordr = r.getString(3); 上不断收到 SQLException。据我了解,r.getString 从结果集中获取第 3 列,其中包含表中的密码。稍后我会将密码器与 txtPassword 中的任何内容进行比较。为什么老是出现 SQL Exception?
如果我将鼠标悬停在“passwordr”上,它会在 NetBeans 中显示“当前上下文中不是已知变量” - 我不确定这是否重要。
try{
// load the sql driver
Class.forName(ConnectionDetails.getDriver());
// attempt to connect
con = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database: "+ ConnectionDetails.getDb());
// prepare an sql statement
stmt = con.createStatement();
String sql = "SELECT * FROM tblusers WHERE fldusername='" + txtUsername.getText() + "';";
// run the query
System.out.println("Before query");
System.out.println(sql);
r = stmt.executeQuery(sql);
System.out.println("After query");
String passwordr = r.getString(1); //FAILS AT THIS LINE
System.out.println(passwordr);
if ( r.next() )// if this returns false there are no records
{
// username found
lblResult.setText("USERNAME Found");
if (passwordr.equals(new String((txtPassword.getPassword()))))
{
lblResult.setText("PASSWORD Correct");
}
else
{
lblResult.setText("PASSWORD Incorrect");
}
}
else
{
lblResult.setText("USERNAME NOT FOUND");
}
}
catch(ClassNotFoundException cnfe)
{ System.err.println("Error finding connection details class");
}
catch(SQLException sqlE)
{
System.err.println("SQL Error");
}
finally
{
// close the statement object
try
{
if( stmt != null )
stmt.close();
System.out.println("Statement object closed");
}
catch(SQLException se)
{
System.err.println("Error: Statement not closed");
}
// close connection to the database
try
{
if( con != null )
con.close();
System.out.println("Connection to db closed");
}
catch(SQLException se)
{
System.err.println("Error: Connection to db not closed");
}
}
}
【问题讨论】:
-
问题太多,但最大的问题可能是您将明文密码直接存储在用户表中。 不要那样做。散列密码并存储加密版本。然后,为了比较,散列密码输入并将其与表中的内容进行比较。
-
执行 SELECT * 然后对列的顺序进行假设可能不是一个好主意。最好使用
getString(columnName)而不是getString(3)。 -
您必须先对结果集调用
next(),然后才能检索列。结果最初位于第一行之前。另外,在提问时,请发布minimal reproducible example 并包含异常堆栈跟踪。