我有一个应用程序,其中用户正在输入用户名,并且应用程序正在从数据库查询中返回用户标识。如何在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