我有一個應用程序,其中用戶正在輸入用戶名,並且應用程序正在從數據庫查詢中返回用戶標識。如何在try/catch之外使用變量?
我遇到的問題是如何在userIDLbl
中顯示userID
?
代碼看起來像這樣:
JButton currentRoleBtn = new JButton("Get ID");
currentRoleBtn.setBounds(50, 50, 150, 30);
currentRoleBtn.setToolTipText("Press to get the ID for the user");
currentRoleBtn.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
int userID;
String userName = adUserNameTxt.getText().toString();
StringBuffer getRolesQuery1 = new StringBuffer("select id from hib.person where name = '");
getRolesQuery1.append(userName).append("'");
try
{
ResultSet rs = stmt.executeQuery(getRolesQuery1.toString());
try
{
while (rs.next())
{
userID = rs.getInt(1);
System.out.println("The User ID is: " +userID);
}
}
finally
{
rs.close();
}
}
catch (SQLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
//Create UserID label
JLabel userIDLbl = new JLabel("User ID is: " +userID);
userIDLbl.setFont(new Font("Georgia", Font.PLAIN, 14));
userIDLbl.setForeground(new Color(50,50, 25));
userIDLbl.setBounds(25, 200, 200, 30);
您有一個SQL注入漏洞。 – SLaks
爲什麼你不能只在內部移動代碼? –
是什麼讓它不能正常工作?看起來好像這樣可以,如果你確定用戶ID是ResultSet中的最後一個用戶ID,也就是說。 – SubSevn