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
Related
image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}
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.
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/
Well I was wondering if there is any other way to get data from a SQL Query.
What I mean is that the "main" code that I always find is
Connection con = (connect to db)
PreparedStatement st = con.prepareStatement(....);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
//do something
}
But if I want to retrieve specific data for example lets assume that my query is
Connection con = L2DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("SELECT login,email FROM accounts WHERE login=?");
ps.setString(1, account);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
if (rs.getString("login").equals(account))
{
email = rs.getString("email");
break;
}
}
Is there any other way except that while loop to retrieve data?
The if condition inside the while loop is completely redundant - the where clause takes care of it and assures that any data returned from this query would have a login field that's equal to the value of account.
If you're sure there's no more than one row like this (e.g., the login column is a unique identifier in your table), you could just replace the while loop with an if:
// Check that such a logic exists
if (rs.next()) {
email = rs.getString("email");
}
// for good measures, just double check there isn't more than one
// of these logins:
if (rs.next()) {
throw new Exception ("This cannot be!"); // Or something more sensible
}
I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.