如何从MySQL数据库中获取特定数据?

时间:2016-06-26 10:57:16

标签: java mysql sql database

我成功创建了一个在线MySQL数据库并将我的java程序连接到它。

现在我想从中获取数据: 在我的数据库表中,“playerdata”是三行:

  

ID,用户名,密码

我创建了一个JavaFX(从swing更改)窗口,其中包含一个Textfield(用于用户名),一个Passwordfield(用于密码)和一个登录按钮。

这是按钮的事件代码:

//makes a query in table "Login" searching for "username"s and "password"s
String query = "select * from playerdata where username=? and password=?";                  
//passing query to preparedStt (statement)
PreparedStatement preparedStt = cnct.prepareStatement(query); 

//setting Strings for username and password 
preparedStt.setString(1, userName.getText()); //index 1 for username (upper ?)
preparedStt.setString(2, userPassword.getText()); //index 2 for username (upper ?) (index starts at 1)

ResultSet resSet = preparedStt.executeQuery(); //executes query result to resSet

int count = 0;

while(resSet.next()) {
    count++; //increments counter
}

if(count == 1) { //goes one time if query matches user and pass
    System.out.println("Access granted!");
} else { //otherwise login is incorrect
    System.out.println("Access denied!");
    System.exit(0);
}

//closes resources
resSet.close();
preparedStt.close();

因此,此查询将遍历所有用户名和密码,如果它们与Textfield(userName)和Passwordfield(userPassword)匹配,则授予访问权限。

我遇到了一个问题!正如我上面提到的,我有三行,这个查询搜索两行。我想知道登录我程序的玩家的ID。你知道我怎么能搞定这个吗?

我已经尝试制作第三个索引(和id =?),然后使用resSet.getString(3),但它给出了一个错误,指出未指定索引3

感谢。

1 个答案:

答案 0 :(得分:1)

你可以简单地得到你的身份:

String query = "select * from playerdata where username=? and password=?"; //makes a query in table "Login" searching for "username"s and "password"s

            PreparedStatement preparedStt = cnct.prepareStatement(query); //passing query to preparedStt (statement)

            //setting Strings for username and password 
            preparedStt.setString(1, userName.getText()); //index 1 for username (upper ?)
            preparedStt.setString(2, userPassword.getText()); //index 2 for username (upper ?) (index starts at 1)

            ResultSet resSet = preparedStt.executeQuery(); //executes query result to resSet

            int count = 0;
            int id = 0;
            while(resSet.next()) {
                count++; //increments counter
                id = resSet.getInt("id");
            }

            if(count == 1) { //goes one time if query matches user and pass
                System.out.println("Access granted!");
            } else { //otherwise login is incorrect
                System.out.println("Access denied!");
                System.exit(0);
            }

            //closes connection
            resSet.close();
            preparedStt.close();