Check database if it has same values - java

Good evening. Below is my code on adding items in my database
String sql = "Insert into userinfo(firstname,lastname,contactNumber,email,address,username,password,accountType) value (?,?,?,?,?,?,?,?)";
String accountType = (String) jComboBoxAccType.getSelectedItem();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, jTextFieldFistName.getText());
ps.setString(2, jTextFieldLastName.getText());
ps.setString(3, jTextFieldContactNumber.getText());
ps.setString(4, jTextFieldEmail.getText());
ps.setString(5, jTextFieldAddress.getText());
ps.setString(6, jTextFieldUsername.getText());
ps.setString(7, jTextFieldPassword.getText());
ps.setString(8, accountType);
ps.execute();
How would I be able to check if there is already an existing username and password before adding?

Normally, you want the database to enforce such data integrity rules itself. This ensures that the data is correct. You don't want to check at the application-level, because that introduces race conditions (two inserts happening at essentially the same time, where both validate that the table has not duplicates and then both insert the same values).
You can guarantee uniqueness using a unique constraint or unique index (the former is implemented using the latter). This will generate an error when a duplicate value is inserted. It is easy to create:
alter table userinfo add constraint unq_username_password unique (username, password);
That said, normally a user would have only one password, so the constraint would be only on the user name:
alter table userinfo add constraint unq_username unique (username);

You need something like this code
PreparedStatement ps=connection.prepareStatement("select 1 from userinfo where username=? and password=?");
ps.setString(1, jTextFieldUsername.getText());
ps.setString(2, jTextFieldPassword.getText());
ps.execute();
if (ps.getResultSet.next()) {
// So, user and password already in database
}
else {
// Insert value...
}
But, as for me, check the existing same pair of (username,password) during adding new user to database is not a good idea.

There are 3 different ways to perform the checking:
1) Create a query that search if a record with the same username and password exists, something like:
SELECT COUNT(*) as exists FROM userinfo WHERE username = :username AND password = :password
or
SELECT username as exists FROM userinfo WHERE username = :username AND password = :password
So if a duplicate record is found the "exists" field is going to return a value different than 0 or NULL.
2) Just create an unique index for both username and password and when you are trying to insert a duplicated record an error is going to be raised, so you have to use a a "try...catch" statement between the "ps.execute".
3) Adding a subquery that checks if duplicate values exists (See: https://stackoverflow.com/a/3025332/1641558)

You should only change the query as,
Insert ignore into userinfo(firstname,lastname,contactNumber,email,address,username,password,accountType) value (?,?,?,?,?,?,?,?)

Related

Update data netbeans

I have a problem when updating data with NetBeans. When I update without changing the id, the error message appears key duplicate '10' for 'primary'
SQL = "update sumber set nama_sumber=?, alamat_sumber=?, kapasitas_sumber=? WHERE id_sumber='"+kodegudang+"'";
ps = conn.prepareStatement(SQL);
ps.setString(1, txt_id.getText());
ps.setString(2, txt_nama.getText());
ps.setString(3, txt_alamat.getText());
ps.setString(4, kapasitasdos.getText());
JOptionPane.showMessageDialog(null, "Sumber Air berhasil Diedit");
ps.executeUpdate();
All the primary key values in a table must be different. I'm guessing that you already have a row with nama_sumber = 10 (or whatever the primary key is). You can check that by connecting to the database directly and running select * from sumber.

Cannot delete or update a parent row - Java

I teacher is trying to delete a row, which is used by a student.
But how can I delete this row anyway?
If the teacher wants to delete the lesson it should delete it anyway?
This is the function I have for the delete query:
con = DriverManager.getConnection ("jdbc:mysql://localhost:3307/lessons","root","");
String query = "DELETE FROM lessons WHERE Number= ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1,txtFieldNumber.getText());
pst.executeUpdate();
.
CREATE TABLE UserLogin(
Number INTEGER,
UserNumberINTEGER,
FOREIGN KEY (Number) REFERENCES termin(Number),
FOREIGN KEY (UserNumber) REFERENCES User(UserNumber)
);
CREATE TABLE lessons(
Number INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
LName VARCHAR(20)
);
CREATE TABLE User(
Name VARCHAR (20),
UserNUmber INTEGER NOT NULL PRIMARY KEY
);
You have to perform 2 separate deletes and in the right order using the same value for the Number parameter.
First delete from UserLogin with
DELETE FROM UserLogin WHERE Number = ?
And then use the command you have today
DELETE FROM lessons WHERE Number = ?
If you want to be sure both statements gets executed properly you can use manual commit like this
You can't use setString when the underlying column is int
Assuming your txtFieldNumber.getText() returns a number in String format, Try the following
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
Update:
Based on your question edit, looks like you are first trying to delete primary key in lessons which is being referenced in UserLogin table. This is the reason you're facing the error.
To overcome this, you may want to first delete in UserLogin table and then delete the corresponding rows in lessons table.
String query = "DELETE FROM UserLogin WHERE Number= ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
pst.executeUpdate();
String query2 = "DELETE FROM lessons WHERE Number= ?";
pst = con.prepareStatement(query2);
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
pst.executeUpdate();
This should solve your issue

getting the result of sql command in java [duplicate]

This question already has an answer here:
java.sql.sqlexception column not found
(1 answer)
Closed 4 years ago.
i need to get the last id entered in my data base witch is AUTO_INCREMENT so i did this
String Var = "SELECT MAX(id) FROM goupe ; ";
ResultSet vari=st.executeQuery(Var);
while(vari.next()){
nombre = vari.getInt("id");}
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)VALUES('"+name+"','"+familly+"','"+email+"','"+pass+"','"+module+"','"+specialite+"','"+card+"','"+nombre+"');";
st.execute(sql);
but i had this problem Column 'id' not found.
so what should i do to have it right .
I have to say, there are a couple of really easy things you can do to greatly improve your code.
If your latest ID is generated elsewhere, then embed the query directly into the statement such that you don't need to go get it. That will reduce the risk of a race condition.
Use PreparedStatements. Let me ask you this question: What do you suppose is going to happen if one of your user's name is O'Ryan?
Since your code is just a snip, I also will only provide a snip:
int index = 1;
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)" +
"VALUES(?,?,?,?,?,?,?,(SELECT MAX(id) FROM goupe));";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(index++, name);
ps.setString(index++, familyname);
ps.setString(index++, email);
ps.setString(index++, password);
ps.setString(index++, module);
ps.setString(index++, speciality);
ps.setString(index++, card);
int rows = ps.executeUpdate();
if(rows == 1) {
System.out.println("Successfully inserted row");
}
When you execute the query SELECT MAX(id) FROM goupe;, then in the returned table, the column name no longer remains as id.
So, the best approach is to provide a name for the column like below:
SELECT MAX(id) AS maxid FROM goupe;
Then, you can get the value using:
vari.getInt("maxid")

How to insert and select from mysql simultaneously

I have a requirement where I need to insert mobile number in mysql if and only if the number is is not present.So for this I am first checking if a number is present in mysql using select query .If number is not present then insert.Following is my code
PreparedStatement pt1=con.prepareStatement("select * from registerSmsUsers where mobile='"+mobile+"'");
PreparedStatement pt=con.prepareStatement("insert into registerSmsUsers values(?,?,?)");
pt.setString(1, name);
pt.setString(2, email);
pt.setString(3, mobile);
ResultSet rs1=pt1.executeQuery();
if(rs1.next())
{pt.executeUpdate();}
i dont know whether this is a efficient way or not.Please suggest me a better way then this
Probably the easiest way in mysql is:
insert ignore into registerSmsUsers values(?,?,?)
When assuming you have unique key on mobile
You may check it here: How to 'insert if not exists' in MySQL?
Or here: http://dev.mysql.com/doc/refman/5.6/en/insert.html
Many of the proposed solutions (including yours) have a race condition that can cause a primary key or unique constraint violation. You code also have a possible SQL injection attack by concatenating SQL rather than using prepared statement parameters. Use SELECT...FOR UPDATE.
PreparedStatement ps = con.prepareStatement("SELECT name, email, mobile FROM registerSmsUsers WHERE mobile=? FOR UPDATE",
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
ps.setString(1, mobile);
ResultSet rs = ps.executeQuery();
if (rs.next()) { // it exists already
rs.moveToCurrentRow();
rs.updateString(3, mobile);
rs.updateRow();
} else { // it does NOT exist
rs.moveToInsertRow();
rs.updateString(1, name);
rs.updateString(2, email);
rs.updateString(3, mobile);
rs.insertRow();
}
rs.close();
ps.close();
EDIT: Just make sure you have an index on registerSmsUsers.
CREATE INDEX registerSmsUsers_mobile_ndx ON registerSmsUsers(mobile)
or a unique contraint (which implicitly creates an index):
ALTER TABLE registerSmsUsers ADD CONSTRAINT registerSmsUsers_mobile_unq UNIQUE (mobile)
With an index, even with millions of records the update/insert will basically be instant.
EDIT2: Added cursor/result set options.
I think it would be better to create a stored procedure and then in that stored procedure you can first use the IF NOT EXISTS clause to check if the user exists using the select statement. If the user is not present you can insert the user in database.
Something like this:
IF NOT EXISTS(SELECT 1 FROM `registerSmsUsers` WHERE mobile= #mobile) THEN
BEGIN
INSERT INTO
`registerSmsUsers`
(
//column names
)
VALUES
(
//values
);
END;
END IF;
Also there is a INSERT IGNORE statement which you can use like this:
insert ignore into registerSmsUsers values(?,?,?)
if not exists(select * from registerSmsUsers where mobile='232323') <-- will check your mobile no
begin
insert into registerSmsUsers values(?,?,?)
end
This one is also an efficient way to check your method is also working fine but this also can be done
See difference is you will have only one query here
i hope this will help you thanks
[Edit]
Your questions answer
Ya there is a execution time diff between yours and mine query its depends upon a database size what you are using if you are using small size database (probably 1000 people) then you will not see any diff between your query and mine query but if your are using lakhs of users then your will have a performace issues check include execution plan in mysql you will get realtime difference between two
As requested, here is my tweaked version of brettw's answer:
import java.sql.*;
public class MySQLtest {
public static void main(String[] args) {
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:mysql://192.168.1.3/zzzTest?" +
"useUnicode=yes&characterEncoding=UTF-8" +
"&user=root&password=whatever");
String newName = "Gord";
String newEmail = "gord#example.com";
String newMobile = "416-555-1212";
String sql =
"SELECT " +
"id, " +
"name, " +
"email, " +
"mobile " +
"FROM registerSmsUsers " +
"WHERE mobile = ? " +
"FOR UPDATE";
PreparedStatement pst = con.prepareStatement(
sql,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
pst.setString(1, newMobile);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
rs.moveToCurrentRow();
rs.updateString("name", newName);
rs.updateString("email", newEmail);
rs.updateRow();
System.out.println("Existing row updated.");
}
else {
rs.moveToInsertRow();
rs.updateString("name", newName);
rs.updateString("email", newEmail);
rs.updateString("mobile", newMobile);
rs.insertRow();
System.out.println("New row inserted.");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
Note that id is the Primary Key for the table: int(11) NOT NULL AUTO_INCREMENT

Sqlite Query Issue

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.

Categories

Resources