Java 如何从MySQL数据库中获取特定数据?
我成功地创建了一个在线MySQL数据库,并将我的java程序连接到它 现在我想从中获取数据: 在我的数据库表“playerdata”中有三行: ID、用户名、密码 我创建了一个JavaFX(由swing更改)窗口,其中包含一个文本字段(用于用户名)、一个密码字段(用于密码)和一个登录按钮 这是我的按钮事件代码:Java 如何从MySQL数据库中获取特定数据?,java,mysql,sql,database,Java,Mysql,Sql,Database,我成功地创建了一个在线MySQL数据库,并将我的java程序连接到它 现在我想从中获取数据: 在我的数据库表“playerdata”中有三行: ID、用户名、密码 我创建了一个JavaFX(由swing更改)窗口,其中包含一个文本字段(用于用户名)、一个密码字段(用于密码)和一个登录按钮 这是我的按钮事件代码: //makes a query in table "Login" searching for "username"s and "password"s String query = "se
//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=?),然后使用reset.getString(3)
,但它给了我一个错误,即没有指定索引3
谢谢。您只需按以下方式获取您的id即可:
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();
非常感谢。工作得很好。现在很明显。。我不知道为什么我没有看到。错误是因为我试图获取一个字符串,但它是一个整数。如果这对您有帮助,您可以验证我的答案!