Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Sql only grabs last sql entry

  1. #1
    Junior Member
    Join Date
    Apr 2013
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Sql only grabs last sql entry

    I am trying to grab usernames and passwords from a mysql table to make a game login, it connects and obtains the data but only accepts, the last entry on the mysql table...

    heres my code for the mysql:

    package packagenamehere.lol.didnotputit;
    import java.sql.*;
    //TODO make this work!!!!
    public class DBConnect {
       // JDBC driver name and database URL
       static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
     
    /*
       //  Database credentials
       static final String USER = "no";
       static final String PASS = "lol";
       static Connection conn = null;
       static Statement stmt = null;
       static String sql;
       static String username;
       static String password;
       */
         // static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
     
     
       //  Database credentials
       static final String USER = "user";
       static final String PASS = "pass";
       static Connection conn = null;
       static String DB_URL = "jdbc:mysql://127.0.0.1:3306/";
       static String dbName = "dbname";
       static Statement stmt = null;
       static String sql;
       public static String username;
       public static String password;
     
     
     
     
       public static void DBConnector() {
     
       try{
    	   /*
    	    *  Class.forName(JDBC_DRIVER).newInstance();
     
     *  
     */    
    	   //STEP 2: Register JDBC driver
     
     
          Class.forName("com.mysql.jdbc.Driver");
     
          //STEP 3: Open a connection
          System.out.println("Connecting to database...");
          //conn = DriverManager.getConnection(DB_URL,USER,PASS);
          conn = DriverManager.getConnection(DB_URL + dbName + "?user=" + USER + "&password=" + PASS);
     
          //STEP 4: Execute a query
          System.out.println("Creating statement...");
          stmt = conn.createStatement();
     
          sql = "SELECT username, password FROM Darkrealm";
          //SELECT username, password FROM Darkrealm
          ResultSet rs = stmt.executeQuery(sql);
          //STEP 5: Extract data from result set
          while(rs.next()){
             //Retrieve by column name
        	 //int id  = rs.getInt("id");
        	 username = rs.getString("username");
             password = rs.getString("password");
            // String first = rs.getString("first");
             //String last = rs.getString("last");
     
             //Display values
            // System.out.print("ID: " + username);
             //System.out.print(", Age: " + age);
             //System.out.print(", First: " + first);
             //System.out.println(", Last: " + last);
     
          }
          //STEP 6: Clean-up environment
          rs.close();
          stmt.close();
          conn.close();
       }catch(SQLException se){
          //Handle errors for JDBC
          se.printStackTrace();
       }catch(Exception e){
          //Handle errors for Class.forName
          e.printStackTrace();
       }finally{
          //finally block used to close resources
          try{
             if(stmt!=null)
                stmt.close();
          }catch(SQLException se2){
          }// nothing we can do
          try{
             if(conn!=null)
                conn.close();
          }catch(SQLException se){
             se.printStackTrace();
          }//end finally try
       }//end try*/
     
       System.out.println("Goodbye!");
    }//end main
    }//end FirstExample

    and the password checker

    package package.here;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.JPasswordField;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.ImageIcon;
     
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JComponent;
    import javax.swing.KeyStroke;
     
    import com.Bc1151.Darkrealm.Game;
    import com.Bc1151.Darkrealm.comptent.DBConnect;
    import com.Bc1151.Darkrealm.input.GameKeyController;
     
     
    public class PasswordField extends JFrame {
     
        private JPanel passwordPanel;
     
        private JPasswordField passwordField;
     
        private JLabel passwordLabel;
        public static GameKeyController gkc = new GameKeyController();
        private JButton userConfirmationBtn;
        private JButton submenu;
     
        private Image icon;
     
        private ImageIcon frameBackground;
        DBConnect db = new DBConnect();
     
        String sql = db.sql;
        JButton closebutton = new JButton("Close");
     
        String sqlusername = db.username;
        JLabel usernamelabel = new JLabel("Username:");  
        JTextField username = new JTextField(10); 
     
        String sqlpassword = db.password;
        String password = "password1"; 
        Statement stmt = db.stmt;
        public String loggedonS = "false";
        public PasswordField() {
        	//loggedon = false;
            icon = new ImageIcon("c:/pics/mercuryLogo.jpg").getImage().getScaledInstance(300, 300, 0);
            frameBackground = new ImageIcon("c:/pics/passwordbck2.jpg");
     
     
     
     
     
            passwordField = new JPasswordField();
            passwordLabel = new JLabel("Password: ");
            userConfirmationBtn = new JButton("Enter");
     
            submenu = new JButton("Submenu");
     
           // setLayout(new GridLayout(3,2));  
           // add(usernamelabel);  
            //add(username);  
           // add(passwordLabel);  
            //add(passwordField);  
            //add(userConfirmationBtn);  
            //add(cancel); 
            initComponents();
        }
     
        private void initComponents() {
        	//loggedon = false;
        	Game game = new Game();
            game.frame.setVisible(false);
     
            // set the properties of this label
            passwordLabel.setBounds(12, 63, 80, 20);
            passwordLabel.setFont(new Font("Monospaced", Font.BOLD, 12));
            passwordLabel.setForeground(Color.BLACK);
     
            usernamelabel.setBounds(12, 13, 80, 20);
            usernamelabel.setFont(new Font("Monospaced", Font.BOLD, 12));
            usernamelabel.setForeground(Color.BLACK);
            // set the properties and actions of this text field
     
            username.setBounds(88, 13, 185, 20);
            passwordField.setBounds(88, 63, 185, 20);
            // set the properties and actions of this button
            Action pass = new AbstractAction() {
     
                public void actionPerformed(ActionEvent e) {
     
    					// retrive the password data from the password field
    					char[] passwordChars = passwordField.getPassword();
    					String usernameChars = username.getText();
    					String passwordStr = "";
    					String usernameStr = "";
    					usernameStr = usernameChars;
    					// convert the returned password characters as string
    					for (int x = 0; x <= passwordChars.length - 1; x++) {
     
    					    passwordStr = passwordStr + passwordChars[x];
    					}
     
    					// check if the password entered is valid
     
               //  if (Password.isPasswordAuthentic(passwordStr)) {
     
     
    					   // do something here
    					//}
    					//TODO change to mysql
    						if (passwordStr.equals(sqlpassword) && usernameStr.equalsIgnoreCase(sqlusername)){
    							disableWindow();
    							loggedonS = "true";
    						}
    						else if (passwordStr.equals("") && usernameStr.equals("")) {
    						    System.out.println("you typed nothing :P");
    						    // do something here
    						} else if (usernameStr.equals("")) {
    							System.out.println("please enter a username");
    						} else if (passwordStr.equals("")) {
    							System.out.println("please enter a password");
    						}
    						else {
    						    System.out.println("incorrect username or password");
    						   // do something here
    						}
     
     
    					}
     
            };
            closebutton.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e)
                {
                    //Execute when button is pressed
     
                	System.out.println("you clicked close");
                	try {
    					close();
    				} catch (InterruptedException e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				}
                }
            });      
            userConfirmationBtn.addActionListener(pass);
            userConfirmationBtn.setMnemonic(KeyEvent.VK_E);
            userConfirmationBtn.setBounds(88, 105, 90, 20);
            userConfirmationBtn.setFont(new Font("Monospaced", Font.BOLD, 11));
            userConfirmationBtn.setBackground(Color.LIGHT_GRAY);
            userConfirmationBtn.registerKeyboardAction(userConfirmationBtn.getActionForKeyStroke(
                                                       KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
                                                       KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
                                                       JComponent.WHEN_IN_FOCUSED_WINDOW);
            userConfirmationBtn.registerKeyboardAction(userConfirmationBtn.getActionForKeyStroke(
                                                       KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
                                                       KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
                                                       JComponent.WHEN_IN_FOCUSED_WINDOW);
            closebutton.setBounds(88, 135, 90, 20);
            closebutton.setFont(new Font("Monospaced", Font.BOLD, 11));
    //        closebutton.setMnemonic(KeyEvent.VK_E);
            closebutton.setBackground(Color.LIGHT_GRAY);
            closebutton.addKeyListener(gkc.login); 
     
            passwordPanel = new JPanel() {
     
                @Override
                protected void paintComponent(Graphics g) {
     
                    // Scale image to size of component
                    Dimension d = getSize();
     
                    g.drawImage(frameBackground.getImage(), 0, 0, d.width, d.height, null);
     
                    super.paintComponent(g);
                }
            };
            passwordPanel.setOpaque(false);
     
            // set this panel's layout to null for absolute positioning of
            // components
            passwordPanel.setLayout(null);
     
            // add the components to this panel
            passwordPanel.add(username);
            passwordPanel.add(usernamelabel);
            passwordPanel.add(passwordLabel);
            passwordPanel.add(passwordField);
            passwordPanel.add(userConfirmationBtn);
            passwordPanel.add(closebutton);
            passwordPanel.addKeyListener(gkc.login); 
     
            // add the panel to the container
            getContentPane().add(passwordPanel);
            getContentPane().addKeyListener(gkc.login); 
            addKeyListener(gkc.login); 
            setTitle(" User Confirmation");
            setIconImage(icon);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(288, 190); //added 200
            setResizable(false);
            setLocationRelativeTo(null);
            setVisible(true);
           // loggedon = false;
        }
     
        /**
         * Invoke this method if this window doesnt have any more use for this
         * current event.
         */
        private void disableWindow() {
    		Game game = new Game();
     
    		System.out.println("disable window");
     
            setVisible(false);
     
            game.showwindow();
        }
        public static void close() throws InterruptedException{
        	System.out.println("closing...");
        	Thread.sleep(500);
        	System.exit(0);
     
        }
     
    }

    --Thanks in advanced!

    -Bc1151


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Sql only grabs last sql entry

    I'm not sure what the purpose is? Your code selects username and password - do you want to get them all? The code as is will only get the last because the variables username/password after the while loop will be set to the values of the last record.

  3. #3
    Junior Member
    Join Date
    Apr 2013
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sql only grabs last sql entry

    Quote Originally Posted by copeg View Post
    I'm not sure what the purpose is? Your code selects username and password - do you want to get them all? The code as is will only get the last because the variables username/password after the while loop will be set to the values of the last record.

    (thanks who ever unlocked it!)

    and yes, i want to check all the users and passwords to the text box's

    --- Update ---

    bump (are these aloud?)

  4. #4
    Junior Member
    Join Date
    Apr 2013
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Sql only grabs last sql entry

    anyone?

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sql only grabs last sql entry

    The code needs to do something with the data inside the loop before the loop goes around again. If the data is not used, its value is replaced the next time the loop goes around. Only the last value will remain in the variables.
    If you don't understand my answer, don't ignore it, ask a question.

  6. The Following User Says Thank You to Norm For This Useful Post:

    Bc1151 (April 5th, 2013)

  7. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Sql only grabs last sql entry

    Please don't bump your threads, it is poor etiquette for a technical forum.

    If you want to collect all the username/passwords, then you need to collect them into something. A Collection perhaps? An Array?

  8. The Following User Says Thank You to copeg For This Useful Post:

    Bc1151 (April 5th, 2013)

  9. #7
    Junior Member
    Join Date
    Apr 2013
    Posts
    7
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default

    Thanks guys (I will give you likes once I get to my pc

    And thanks for the rules on bumping copeg!

Similar Threads

  1. SQL Query
    By mija in forum JDBC & Databases
    Replies: 13
    Last Post: December 20th, 2012, 07:23 PM
  2. [SOLVED] How to modify core Java interface java.sql.Statement.execute(String sql)?
    By amughost in forum Java Theory & Questions
    Replies: 6
    Last Post: June 9th, 2012, 04:31 PM
  3. Replies: 1
    Last Post: June 14th, 2011, 11:08 AM
  4. SQL in Java
    By Sai in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 1st, 2011, 03:38 PM
  5. sql compiler
    By tsuki in forum JDBC & Databases
    Replies: 6
    Last Post: October 16th, 2009, 10:35 PM