Else statement not executing inside while loop of SQL database - java

Else statement not working inside while loop
public void loginButton() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/finditdb","root","root");
Statement stmt = con.createStatement();
String usernameInput = usernameField.getText();
String passwordInput = passwordField.getText();
ResultSet rs = stmt.executeQuery("SELECT * FROM finditdb.login WHERE username like '" + usernameInput +"' and password like '" + passwordInput +"'");
while(rs.next()){
String usernameDb = rs.getString("username");
String passwordDb = rs.getString("password");
if(usernameInput.equals(usernameDb) && passwordInput.equals(passwordDb)){
System.out.println("Access Granted..");
}
else {
System.out.println("Access denied..");
}
}
}

You could try this and let me know if it works the way you want it to.
while(true){
if(rs.next()){
String usernameDb = rs.getString("username");
String passwordDb = rs.getString("password");
if(usernameInput.equals(usernameDb) && passwordInput.equals(passwordDb)){
System.out.println("Access Granted..");
break;
}
}
else{
System.out.println("Access denied..");
break;
}
}
We haven't mentioned any exit condition within the while loop parenthesis, so the loop keeps running till no more records are left to be fetched (else will print Access denied and break) or if access is granted (breaks again).

Related

Can i have two connection statement in a single button action performed using java swing.?

My complete code to access data from two different databases using single hive jdbc driver. I get sql exception on next database connection, before that it works perfectly. Kindly, suggest me some solution to further process. Where as next prepared statement query throws sql exception. But doing on a separate button action it works fine, while i'm doing in a single action it throws error.
String s1 = jTextField1.getText();
String s2 = jTextField2.getText();
String s3 = jTextField3.getText();
String s4 = new String(jPasswordField1.getPassword());
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db", "arunachalam", "");
Statement st = con.createStatement();
String sql = "select dbname,tbname from check where userid='" + s3 + "'and tbname='" + s2 + "'";
String sql1 = "select userid,password from user_reg where userid='" + s3 + "'";
ResultSet rs = st.executeQuery(sql);
try {
PreparedStatement ps = con.prepareStatement(sql1);
ResultSet rs1 = ps.executeQuery();
while (rs.next() && rs1.next()) {
if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
jSeparator1.setVisible(true);
jScrollPane1.setVisible(true);
try {
Connection con1 = DriverManager.getConnection("jdbc:hive2://localhost:10000/" + s1, "arunachalam", "");
ArrayList<Tweet> list = new ArrayList<Tweet>();
String ve = "select id,created_at,source,favorited,retweet_count,retweeted_status,entities,text,user,in_reply_to_screen_name from " + s2;
PreparedStatement ps1 = con1.prepareStatement(ve);
ResultSet rs2 = ps1.executeQuery();
Tweet tweet;
while (rs2.next()) {
tweet = new Tweet(rs.getLong("id"), rs.getString("created_at"), rs.getString("source"), rs.getBoolean("favorited"), rs.getInt("retweet_count"), rs.getString("retweeted_status"), rs.getString("entities"), rs.getString("text"), rs.getString("user"), rs.getString("in_reply_to_screen_name"));
list.add(tweet);
String[] columnName = {"Tweet_ID", "Created_At", "Source", "Favorited", "Retweet_Count", "Retweeted_Status", "Entities", "Text", "User", "Screen_Name"};
Object[][] twt = new Object[list.size()][10];
for (int i = 0; i < list.size(); i++) {
twt[i][0] = list.get(i).gettweetid();
twt[i][1] = list.get(i).getcreated();
twt[i][2] = list.get(i).getsource();
twt[i][3] = list.get(i).getfavor();
twt[i][4] = list.get(i).getcount();
twt[i][5] = list.get(i).getstatus();
twt[i][6] = list.get(i).getentities();
twt[i][7] = list.get(i).gettext();
twt[i][8] = list.get(i).getuser();
twt[i][9] = list.get(i).getscreen();
TheModel model = new TheModel(twt, columnName);
jTable1.setModel(model);
jTable1.setRowHeight(20);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
break;
} else if ((!rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Database Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (!rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Table Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (!rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Password is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((!rs1.getString("userid").equals(s3)) && (rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "User ID is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else {
JOptionPane.showMessageDialog(null, "Access Denied", "Error", JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
} catch (Exception e) {
showMessageDialog(null, e);
}
To be responsive, as the application would freeze during actionPerformed use
invokeLater.
Yes separate connections for instance with different users, one for reading only, one for admin tasks, is quite possible. However I did not see calls to close().
(Also a single-user (such as an embedded) database might not do.)
To automatically close connection, statement and result set use try-with-resources: try (DECLARATION; ... ; DECLARATION) { ... } - saves a lot.
The explicit class loading with Class.forName no longer is needed for current drivers.
// Java 8
SwingUtilities.invokeLater(() -> {
String sql = "select dbname, tbname from check where userid=? and tbname=?";
try (Connection con = DriverManager.getConnection(
"jdbc:hive2://192.168.1.13:10000/twitter_db", "arunachalam", "");
PreparedStatement st = con.prepareStatement(sql)) {
st.setString(1, s3);
st.setString(2, s2);
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
List<Tweet> list = new ArrayList<>();
String hive = "select id,created_at,source,favorited,retweet_count,"
+ "retweeted_status,entities,text,user,in_reply_to_screen_name from "
+ s2;
try (Connection con1 = DriverManager.getConnection(
"jdbc:hive2://localhost:10000/"+s1, "arunachalam", "");
PreparedStatement ps1 = con1.prepareStatement(hive);
ResultSet rs2 = ps1.executeQuery()) {
...
});

im getting an error at resultset line

<%# page import= "java.sql.*"
import= "java.util.*"%>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st = con.createStatement();
String name = request.getParameter("name");
String username = request.getParameter("user");
String pass = request.getParameter("pas");
String cpass = request.getParameter("cpas");
String sql2 = "select * from user where user='"+username+"';";
ResultSet rs = st.executeQuery(sql2);
if(rs.next())
{
response.sendRedirect("index.html?err=Username already taken");
}
else
{
String sql = "insert into user values('"+name+"', '"+username+"','"+pass+"',"+cpass+");";
st.executeUpdate(sql);
response.sendRedirect("blank.html");
}
%>
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st = con.createStatement();
String name = request.getParameter("name");
String username = request.getParameter("user");
String pass = request.getParameter("pas");
String cpass = request.getParameter("cpas");
String sql2 = "select * from user where user='"+username+"';";
ResultSet rs = st.executeQuery(sql2);
if(rs != null && rs.next())
{
response.sendRedirect("index.html?err=Username already taken");
}
else
{
String sql = "insert into user values('"+name+"', '"+username+"','"+pass+"',"+cpass+");";
st.executeUpdate(sql);
response.sendRedirect("blank.html");
}

unable to concatenate variable with sql query

Here is sample code ...
Statement stmt = con.createStatement();
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println(query); // displaying only `
ResultSet rs = stmt.executeQuery(query);
System.out.println(query);
while (rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
If String passed Instead of passing variable then it works ...like
ResultSet rs = stmt.executeQuery("select * from work_product where product_name ='product' ");
I also used preparedStatement...but not working ...
PreparedStatement statement = con.prepareStatement("select * from work_thing_db.work_product where product_name = ? ");
statement.setString(1,ch);
Here is full code ....
#FXML protected void keyReleased(KeyEvent evt)throws Exception {
//SetTimer();
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
}
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Using : IntelliJ IDEA 14 CEOutput :
Enter key Fired
product
In dbSearch
Concat String :product
'
kindly point out my mistake ... i'm new in java... and further i need to use like and or with it .... please provide answer with explanation... Thanks in advance.
It's possible there is no match in the data. You could run a non filtered query first and see what values you have for product_name in the table.
I haven't thought of it....
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
ch = ch.trim().toString(); // trim and type cast ... its working
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Now it is fetching data properly ...
There is something wrong in the way you concatenate the string
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
so when the user will enter "ENTER" (can be \n or \r) you will concatenate before the condition of the key value so concateString will always contain your string + "ENTER" (i.e. the carriage return). Thats the reason you only get the quote when you print your query
Not to modify much of your code, you can do
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
} else {
concateString = concateString + ch; //concateString has scope
}
}
and so you will pass the correct string

to check whether the search element isn't available in DB

I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}

Unable to Match user and pass Login form netbeans

how can I match user and password in the conditions below. I am always getting UserName/Password does not match.
try
{
Conn();
st = conn.createStatement();
rs = st.executeQuery("Select UserName,PassWord from login_tbl where UserName = '"+txtUser.getText()+"' and PassWord = '"+txtPass.getPassword()+"'");
if(rs != null)
{
new CarRent().setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(null, "Your Username or Password is incorrect","",JOptionPane.ERROR_MESSAGE);
}
}
You should use this rs.next() instead of this rs != null
try
{
JOptionPane.showMessageDialog(null, "Username is : " + txtUser.getText().trim().toString() + " Password is : " + txtPass.getPassword().trim().toString(),"",JOptionPane.ERROR_MESSAGE);
Conn();
st = conn.createStatement();
rs = st.executeQuery("Select UserName,PassWord from login_tbl where UserName = '"+txtUser.getText()+"' and PassWord = '"+txtPass.getPassword()+"'");
if(rs.next())
{
JOptionPane.showMessageDialog(null, "Password is valid","",JOptionPane.ERROR_MESSAGE);
new CarRent().setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(null, "Your Username or Password is incorrect","",JOptionPane.ERROR_MESSAGE);
}
i already solved my problem thanks to all :)
String sql = "select * from login_tbl where usern=? and pass=?";
try{
Conn();
ps=conn.prepareStatement(sql);
ps.setString(1,txtUser.getText());
ps.setString(2,new String(txtPass.getText()));
rs=ps.executeQuery();
if (rs.next()){
//about s= new about();
//
//s.setVisible(true);
new CarRent().setVisible(true);
dispose();
}
else
{
JOptionPane.showMessageDialog(null, "Password or Username is incorrect");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}

Categories