what is the best way to check if the user is exist
i have wrote this code
try{
PreparedStatment mPre=conn.preparedStatement(INSERT INTO TABLE VALUES(?,?);
}catch(Exception e)
{
if(e.getMessage().contains("Dublicated"))
{
throw new Exception("user is exist");
}
}finally {
mPre.close();
conn.close();
}
my friends told me that this is stupid query
and i should do like this
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT COUNT(*) AS total FROM .......");
int cnt = rs.getInt("total");
Your friend is right. You can check if row exists by query:
SELECT EXISTS(SELECT 1 FROM *table* WHERE *something*)
As long as you are trying to insert a row that breaks the unique primary key constraint of database tables AND the exception thrown has a stack trace that contains the word "duplicated" then your code should work fine.
But in the unlikely event that the stack trace changes and does NOT contain that word, your code won't work anymore.
It's more likely that you are trying to insert a row with a unique primary key value but an existing username, which won't give you the error that you hope for. That's the reason why it would be smarter/safer to retrieve results for that username and count how many results there are.
When you are trying to verify if the given username and password exists in your user table, you should use PreparedStatment because it will help you in protecting your application from SQL injection.
But
Inserting a new user to the database is not the right way to do user validation.
You can do something like this example:
String selectSQL = "SELECT * FROM USER_TABLE WHERE USER_ID = ? AND PASSWORD = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
preparedStatement.setString(2, "1234");
ResultSet rs = preparedStatement.executeQuery(selectSQL );
while (rs.next()) {
//You will need user information to render dashborad of your web application
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
}
Complete code refrence: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/
Related
Here is the code for my servlet which recieves username parameter from a registration form
String tusername=request.getParamater("un");
String dbURL="db.com";
String dbusername= "lc";
String dbpassword="lcpw";
Connection con=(Connection) DriverManager.getConnection(dbURL,dbusername,dbpassword);
Statement stmt= con.createStatement();
String query="SELECT * FROM users.username WHERE username=(tusername)";
ResultSet rs= stmt.executeQuery(query);
if(rs.next()==false){
//create new userobject with value of tusername
}
My question is how do I create a new user object with calue of tusername, would it be like so ?
if(rs.next()==false){
Statement stmt=con.createStatament();
String query="INSERT INTO user.username VALUE 'tusername'";
ResultSet rs= stmt.updateQuery(query);
}
I understand some of this might be archaic (such as not using a prepared statement) , I am just trying to better my understanding and I think I am having some small syntax issues, thanks :)
You should be using a NOT EXISTS query to do the insert, and also you should ideally be using a prepared statement:
String sql = "INSERT INTO user.username (username) ";
sql += "SELECT ? FROM dual WHERE NOT EXISTS (SELECT 1 FROM user.username WHERE username = ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, tusername);
ps.setString(2, tusername);
int result = ps.executeUpdate();
if (result > 0) {
System.out.println("Inserted new user " + tusername + " into username table";
}
else {
System.out.println("User " + tusername + " already exists; no new record was inserted");
}
I don't know what your actual database is. The above should work out of the box for MySQL and Oracle. It might need to be modified slightly for other databases.
An alternative to the above query would be to just use your current insert, but make the username column a (unique) primary key. In that case, any attempt to insert a duplicate would fail at the database level, probably resulting in an exception in your Java code. This would also be a more database agnostic approach.
I have a derby users database which I query, when the user clicks login on the application.
However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.
Here is my code:
String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
try{
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
con = DriverManager.getConnection(url);
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
try{
while (rs.next()) {
if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
sql.close();
con.close();
return true;
}
} catch (NPE ...) {...}
}
I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error.
Why is the recordset always Null?
Thanks for your help :)
The documentation says
ResultSet getGeneratedKeys() throws SQLException
Retrieves any auto-generated keys created as a result of executing this Statement
object.
If this Statement object did not generate any keys, an empty
ResultSet object is returned.
Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.
You can try ResultSet rs = sql.executeQuery();. It should work.
You are using it in wrong way.
The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.
select simply select the rows from the table. In this case there is no chance of any keys getting generated.
In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.
As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS.
You just modify below lines and everything will be fine.
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
with
sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();
I'm developing a webservice using JSON that inserts the email of g+ user(once the user chooses to login to my app through google sign-in).
I don't want my webservice to enter multiple entries for the same user into my table.
I want to overwrite the old entry of email with the newer one.
what should I do?
Edit 1:
//setGplusEmail
public ArrayList<Status> setEmail(Connection con,String gplusMail) throws SQLException
{
ArrayList<Status> gplusUserList = new ArrayList<Status>();
//con.setAutoCommit(false);
String sql = "INSERT INTO gpluslogin (gmail) VALUES ('"+gplusMail+"')";
String sql1 = "INSERT INTO gpluslogin (gmail) VALUES ('"+gplusMail+"') ON DUPLICATE KEY UPDATE (gmail = '"+gplusMail+"')";
PreparedStatement stmt = con.prepareStatement(sql);
PreparedStatement stmt1 = con.prepareStatement(sql1);
try{
stmt.executeUpdate();
stmt1.executeUpdate();
}catch(Exception e){
}
Status s = new Status();
s.setStatus("Successfully Inserted...");
gplusUserList.add(s);
return gplusUserList;
}
Is this the right way to execute?
After creating unique key on gmail column you can use any one statement out of below 2-
REPLACE INTO gpluslogin (gmail) VALUES('abc#gmail.com');
OR
INSERT INTO gpluslogin (gmail) VALUES('abc#gmail.com') ON DUPLICATE KEY UPDATE gmail='abc#gmail.com';
UPDATE user_table SET email=$newemail WHERE userID = $userID
I have a MySQL table with entries already in it and I have it connected to my Java program so it displays the table values whenever the program is run. I'm basically trying to implement a search field where the user can type any attribute's value and all the entries that match that value will be loaded into the table. Then the user will be able to select the right entry that matches and they can edit, or update that entry's information. This would be useful for me particularly when you have entries that have the same value, for instance first name, last name, or zip code.
try {
String sql = "SELECT * FROM donors WHERE donor_id = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
try {
String sql = "SELECT * FROM donors WHERE first_name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
The search field only searches for the second query, but not the first, so I can type a name and the matching names will load into the table, but when I try to input an id number, nothing happens. I'm fairly new to this, but I think it has something to do with my resultset object? Not exactly sure though. Any help would be great.
What happens here is that the second result overwrites the first. I think the easiest solution is to use or in the where clause, like this:
String sql = "SELECT * FROM donors WHERE (donor_id = ?) or (first_name = ?)";
ps.setString(1, txtSearch1.getText());
// but of course there are 2 ?'s now, we have to give the value to the second one
// as well
ps.setString(2, txtSearch1.getText());
Due to the way placeholders work in JDBC you'll have to provide a value for each ?.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting unexpected output in program
To be frank,this question may be silly to ask, but I'm a novice in Java.
This is my Table emp(name,id,address,date).
Now I'm going to match a certain employee's corresponding password.
String sql = "select emp_id,password from regid";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
// here will be iterate function using resultset,i guess
// what should be the best logic to check the name and password...any inputs
//in terms of code
if(if (employee.equals(rs.getString("emp_id")) && password.equals(rs.getString("password")))){
You are Mr. emp // in terms of code
}
else{
Who are You ?? //in terms of code
}
}
Any inputs will be highly appreciated.
Use a PreparedStatement to create your query. So your parameterized query for the PreparedStatement would be something like this:
SELECT * from regid WHERE emp_id = ? AND password = ?
Plug in the paremeter values and execute your statement. So it would be something like this:
PreparedStatement ps = null;
ResultSet rs = null;
boolean validUser = false;
try{
ps = connection.prepareStatement("SELECT * from regid WHERE emp_id = ? AND password = ?");
ps.setString(1, [user_id_input]);
ps.setString(2, [user_pw_input]);
rs = ps.executeQuery();
validUser = rs.next();
}finally{
//Release your resources
}
if(validUser){
//user is validated
}
As a side note, I would also suggest to validate your user's input before feeding it to your query.
You are selecting the data for all employees and looking through them for a match.
Much better to have the database filter it:
select count(*) from regid where emp_id = ? and password = ?
Then you only need to check if this returns 0 or 1.
Also, password is hopefully just a password hash.
fetching all data from database make your application performance slow, So fire following query retrieve one record.
boolean status = false;
String emp_name = "";
String emp_password = "";
String sql = "select * from regid where emp_id='"+emp_id+"' AND password='"+password+"'";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
if(emp_id.equals(rs.getString("emp_id")) && password.equals(rs.getString("password")))
{
// fetch employee data
status = true;
}
}
if(status)
{
// login correct
}
else
{
// login incorrect
}
Query your database with "select emp_id,password,... from regid where emp_id=? and password=?"
Create a PreparedStatement and set emp_id and password. it will return you 1 row if emp_id and password match.
You actually shouldn't be matching the password in the result set. Your sql query should be something like
select emp_id from regid where password='userpassword'
where userpassword is the password you got from the screen your using