When checking in the database, the output is repeating / looping - java

I only clicked the button once, but the output is 2. I wonder if there is something wrong with my condition in the while loop? Or should I use a different approach?
As you can see in the picture, I entered only one data, but the output, executes the conditions in
if and else;
String pass = PF.getText();
String user = TF.getText();
Connection con = connect.getConnection();
Statement st;
ResultSet rs;
String query = "SELECT username, password FROM users";
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
if(user.equals(rs.getString(("username")))){
if(pass.equals(rs.getString(("password")))){
System.out.println("Logged In!");
}else{
System.out.println("Error");
}
}else{
System.out.println("Not in the database!");
}
}
st.close();

As per your table, you have two rows. And, you execute following query, it will return two rows.
String query = "SELECT username, password FROM users";
You could add username and password in where clause instead.
PreparedStatement stmt = connection.prepareStatement("SELECT username, password FROM users where username =? AND password=?");
stmt.setString(1, userid);
stmt.setString(2, pass);
Better use PreparedStatement to avoid any sql injection.

In below line you are selecting all the rows in users table
String query = "SELECT username, password FROM users";
You need to limit it to specific one that you want using WHERE clause.
Wikipedia about WHERE clause:
WHERE clauses are not mandatory clauses of SQL DML statements, but can
be used to limit the number of rows affected by a SQL DML statement or
returned by a query. In brief SQL WHERE clause is used to extract only
those results from a SQL statement, such as: SELECT, INSERT, UPDATE,
or DELETE statement.
Like below:
String query = "SELECT username, password FROM users WHERE username = '"+yourVariable+"' password = '"+yourVariable+"'";
I did this using String concatenation. This will lead to SQL injection. So you can use PreparedStatement as #Ravi mentioned.
Oracle doc. about PreparedStatement:
A SQL statement is precompiled and stored in a PreparedStatement
object. This object can then be used to efficiently execute this
statement multiple times.
Also this question may help you.

Related

Retrieve data from database by java & myphpadmin

The user will be asked to enter one E_Id (PK) to retrieve the "salary" data of that employee. For example, the user key in e.g. 105, it will return the data which is 2600. What is the query I should write as the user will enter the different PK each time to get different data? I have connected successfully to the myth-admin.
SELECT salary FROM Employee WHERE E_ID = ?????? (supposed to be the input of user)
Thanks in advance
The simpliest way to do this is by using a JDBC statement. A basic query would look like following:
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/test", "root","root");
Statement statement= conexion.createStatement();
String id="105"; //Here you would need to get the input of the user
String query= "select Salary from Employee where E_ID='"+id+"'";
ResultSet rs=statement.executeQuery(query);
Another way more seccure would be using Prepared Statement to avoid SQL injection.
String query= "select Salary from Employee where E_ID= ? ";
Connection conexion= DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
PreparedStatement ps= conexion.prepareStatement(query);
sentencia.setString(1, "105");
ResultSet rs = ps.executeQuery();

MySQL Java prepared statement Syntax error

I need to select rows from mysql table based on various criteria, for example Colour= Black, or size= L.
The code works without the preparedstatement and the question marks, but whenever I attempt to use the question marks the code does not run.
I have read something about typing the question mark like \'?'// but I am not sure about the exact format.
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Statement stmt = con.createStatement();
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
ResultSet rs = stmt.executeQuery(sql);
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
Also, Size is written out in orange colour, but the error happens also when I only use this sql String
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ?;";
I have looked at like 20 different answers, but didnt find anything helpful, so thanks in advance for any help!
You are executing the query using a normal java.sql.Statement, not using a java.sql.PreparedStatement. This won't work because a normal Statement does not support parameterized queries. So, remove the creation and execution of the Statement, and make sure you execute the statement using the PreparedStatement:
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement preparedStmt = con.prepareStatement(sql)) {
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
try (ResultSet rs = preparedStmt.executeQuery()) {
// process result set
}
}
Also note the addition of try-with-resources, which will ensure connections, statements and result sets are closed correctly.

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 table 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
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.
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 = connection.prepareStatement(query);
preparedStatement.setString(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;.
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.
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.
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,
rs.first()
to confirm there are data available in the returned ResultSet.
Try,
if (rs.first()) {
JOptionPane.showMessageDialog(null, "already");
}
This is the final code will is working absolutely fine.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT * FROM table_name WHERE name=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,jtf.getText());
ResultSet rs = preparedStatement.executeQuery();
if(rs.next()==true){
JOptionPane.showMessageDialog(null,"Value already exist");
}
else{
JOptionPane.showMessageDialog(null,"Value not present");
String query1="INSERT INTO table_name(col_name) VALUES (?)";
preparedStatement = conn.prepareStatement(query1);
preparedStatement.setString(1,jtf.getText());
preparedStatement.execute();
JOptionPane.showMessageDialog(null,"DONE");
}
rs.close();
preparedStatement.close();
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
}

Oracle :SQL command not properly ended

String req="INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)";
I want to make a request with Conditions but I get the error:
SQL command not properly ended
You have an invalid SQL query. Here's your current SQL statement:
INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)
If we split this into several lines for better understanding, you will have this:
INSERT INTO NOTIFICATIONS
VALUES(6,1,sysdate,'toz',02542,'bporp')
(SELECT valide from mouvement where valide=?)
Which is not a valid statement, not even for any SQL tool. That's because you have 2 statements without separating them: an INSERT and then a SELECT, and you're not executing an INSERT INTO <TABLE1> SELECT ... FROM <TABLE2>.
You should execute a single SQL statement per Statement or PreparedStatement. This, in Java, should be done like this:
String sql1 = "INSERT INTO NOTIFICATIONS"
+ " VALUES(6,1,sysdate,'toz',02542,'bporp')";
String sql2 = "SELECT valide from mouvement where valide=?";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql1);
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, <parameter_value>);
ResultSet rs = pstmt.executeQuery();

MySQL upsert (ON DUPLICATE KEY) using JDBC Prepared Statement

I am trying to write a method to have an UPSERT functionality with a prepared statement in java. The code looks as follows;
public boolean addUserDeviceToken(String userid, String password, String deviceToken, Connection connection) {
String addDeviceToken = "INSERT INTO swiped.Users (userid, password, deviceToken) VALUES( ?, ?, ?) ON DUPLICATE KEY UPDATE devicetoken = ?";
boolean result = false;
ResultSet rs = null;
PreparedStatement st = null;
try {
st = connection.prepareStatement(addDeviceToken);
st.setString(1, userid);
st.setString(2, password);
st.setString(3, deviceToken);
st.setString(4, deviceToken);
What I am unsure of is whether i use st.executeQuery(); or st.executeUpdate(); as surely it depends on the condition of the duplicate key?
What is the correct approach
thanks
You don't want to get a resultSet, there's no result apart the number of insertions or updates, simply use executeUpdate.
Extract from the javadoc :
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement

Categories

Resources