how to use textfield input in mysql SELECT query
how to use textfield input in mysql SELECT query
I am using java netbeans and mysql. I want to check whether the value entered by the user in a textfield tf is already present in the mysql tabel or not.
String query1="SELECT * FROM trytable WHERE name='8'";
ResultSet rs=stmt.executeQuery(query1);
if(rs.isBeforeFirst()==true){JOptionPane.showMessageDialog(null,"already");}
In the above code in place of 8 i want to give the value that the user input in the form and then check whether that value already exist in form or not.
Please help me in the first line . Thanks
2 Answers
2
You should use a PreparedStatement
instead of a regular statement. This is more secure than a normal Statement
and allows you to avoid SQL injection issues.
PreparedStatement
Statement
You would change your query like so:
String query = "SELECT * FROM trytable WHERE name=?;";
Note the ?
at the end of the query. This can be replaced later in your code when setting up the PreparedStatement
:
?
PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, userInput);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) System.out.println("Record exists!");
Here, you are telling the prepared statement to replace the first ?
in the query, with the value of userInput
. So, if the user inputs a 3, the query that gets executed would be SELECT * FROM trytable WHERE name=3;
.
?
userInput
SELECT * FROM trytable WHERE name=3;
Also note that rs.next()
returns true
if the query returns any results, so that would be the proper way to determine if the record exists.
rs.next()
true
ResultSet is like a table, it has a cursor. At the beginning the cursor is above the first row so isBeforeFirst()
will always return true
even there are no results in the ResultSet
.
isBeforeFirst()
true
ResultSet
In order to retrieve results you need to move the cursor to the next row, to do that you can use,
rs.next()
If the cursor moved to the next row successfully (which means there are more results) it will return true
otherwise false
. As you only need the first result you can also use,
true
false
rs.first()
to confirm there are data available in the returned ResultSet
.
ResultSet
Try,
if (rs.first()) {
JOptionPane.showMessageDialog(null, "already");
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
So you have two issues: How to declare a variable in Java netbeans, and how to query a database? For the second point, what if someone inserts '8' while you're in the middle of checking?
– Strawberry
51 mins ago