Im trying to avoid SQL duplication. I found this code here how to prevent duplication. Java,SQL which is successful. I know rs.next will move the cursor, but how does it help avoid duplication (does it compare every value)? What is done is just checking is there another row and if there return true right?
Connection conn = // Connect to the database...
PreparedStatement ps =
conn.prepareStatement("SELECT username FROM login where username = ?";
ps.setString(1, value1);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog
(null,"username is already existed! please create new username.");
}
Your code is quite straightforward. You make a query that fetches ALL rows of the table login where username = XXX. Then you check whether there is any data in the ResultSet by executing the rs.next() function. This function returns a boolean value that is true when there is yet more data in the rs and false when there is no more data.
As you said, it also moves the cursor.
Does it compare every value(row)?
Yes. Your query looks every row up and checks whether username = XXX
Related
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());
}
I am trying to check if a player is already is in the database with this code:
Statement sql = mySql.getConnection().createStatement();
ResultSet check = sql.executeQuery("SELECT * FROM `playerinfo` WHERE Username='" + player.getName() + "';");
System.out.println(check.toString());
if(check != null) {
System.out.println("2");
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Player already in database");
check.close();
sql.close();
return;
}
I checked but nothing is in the database and it says that the player already contains in the database
Sorry for bad english
Some considerations:
When checking whether the database contains a certain value, it's good practise to do this using a query that returns a single value (and not SELECT * which returns all columns of all rows that match the WHERE condition). You can do this e.g. by selecting a single check flag (SELECT 1) with a row-limiting clause (LIMIT 1):
SELECT 1 FROM playerinfo WHERE Username = ? LIMIT 1
This query is guaranteed to return only one row (with a single column, '1') if a player with the given name exists, or no rows if there are no players with the given name.
As others have pointed out, when you're inputting parameters into the query, you should use a PreparedStatement instead of a simple statement with concatenated inputs. This way, you can avoid SQL injection and the database is also able to reuse/cache the query (or cursor) internally.
Finally, you should close the resources you use, even if an Exception gets thrown during the execution. This is best done in the finally clause, or if you're on Java 7 or later, using the try-with-resources statement.
With these things in mind, a re-write of your code could look like this:
PreparedStatement ps = null;
try {
ps = mySQL.getConnection()
.prepareStatement("SELECT 1 FROM playerinfo WHERE Username = ? LIMIT 1");
ps.setString(1, player.getName());
ResultSet rs = ps.executeQuery();
// the first invocation of rs.next() returns true if
// there are rows in the result set, or false if no rows were found
if (rs.next()) {
System.out.println("2");
Bukkit.getConsoleSender().sendMessage(ChatColor.RED
+ "Player already in database");
}
rs.close();
} finally {
if (ps != null) {
ps.close();
}
}
I think instead of checking if the ResultSet is null or not, you should check if the ResultSet contains any row or not.
Apart from that, use PreparedStatements.
I have a database and at present I am using the PreparedStatement to call data from the database using an SQL statement. However I know that once a PreparedStatement has finished the ResultSet closes.
I need an alternative to this (the resultset closing) as the Prepared Statement is run every time the user clicks a button and the input to the Prepared Statement can change however the ResultSet cannot take any new values.
Any thoughts would be appreciated.
You should copy the data from the ResultSet into objects of your own before closing the PreparedStatement.
For instance:
preparedStatement = conn.prepareStement("select * from people");
resultSet = preparedStatement.executeQuery();
//copying the value
while(resultSet.hasNext()){
String name = resultSet.getString("name");
String surname = resultSet.getString("surname");
//Person is a class of your own
Person person = new Person(name,surname);
//people is a Collection of Person created outside this loop
people.add(person);
}
Afterwards, make sure you close the PreparedStatement in a finnally block, and use the object in the people collection instead of using the ResultSet directly.
Alright, so I'm trying to store data in Sqlite. So I'm trying to store the id of the user with the a "line". Yet, it seems that the where clause is failing me.
String query = "SELECT * FROM Users WHERE username='Fellixombc";
ResultSet result = this.sqlStatement.executeQuery(query);
int userId = 0;
while(result.next()) {
System.out.println("TRUE");
userId = result.getInt("id");
System.out.println(result.getString("username"));
}
And true is not printing. Yet, if I remove the WHERE clause from the query, it will print out all of the usernames/id's fine, and of course "TRUE".
Am I missing something with Sqlite and it's syntax?
edit: Just to clarify there is a user in the Users column with the id of 1 and with the username Fellixombc
edit: So I took your guy's suggestion and tried prepare statement, heres my code now:
PreparedStatement sqlStatement = this.sqlConnection.prepareStatement("SELECT * FROM Users WHERE username=?");
sqlStatement.setString(1, "Fellixombc");
ResultSet result = sqlStatement.executeQuery();
int userId = 0;
while(result.next()) {
System.out.println("TRUE");
userId = result.getInt("id");
System.out.println(result.getString("username"));
}
result.close();
Essentially, you want to store the username, correct?
Your current query will retrieve all information on relative to a username. It's what a SELECT query does, it retrieves.
If you need to create a new user, use:
INSERT INTO Users (username) Values ('Fellixombc');
I should tell you that you might need to provide more information in this query, depending on what other fields your Users table has.
EDIT:
In your select statement, you have an open single quote.
"SELECT * FROM Users WHERE username='Fellixombc"
should be
"SELECT * FROM Users WHERE username='Fellixombc'"
To avoid issues with SQL injection, consider the prepareStatement function.
Try doing a trim on your username field. Its possible there's a spurious space somewhere in the data thats causing your where clause to fail.
"SELECT * FROM Users WHERE trim(username) ='Fellixombc'"
Also, agree with #MPelletier. You should definitely be using PreparedStatements.
I am trying to retrieve results from a DB in a resultset. However i want to execute an update query for each entry in the resultset, but i get an exception.
this is my code
try {
Statement statement = sqlconnection.conn.createStatement();
query = "select * from reminders where year<= "+ syear +" and month<=" + smonth +" and date<"+ sday +" and reminded like 'false';";
rs= statement.executeQuery(query);
while (rs.next()){
id=rs.getInt("sno");
String reminder = rs.getString("remind");
JOptionPane.showMessageDialog(null, reminder);
statement.executeUpdate("update reminders set reminded='true' where sno="+id+";");
}
Can any1 show me a better way of doing this ?? I am pretty new to programming. Hence showing me how to it will be really helpful.
thanks
You're still looping over the results from statement when you're trying to perform an update with it. I'd try using a second Statement object for your updates.
Your ResultSet is not updatable.
Statement statement = sqlconnection.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);