Skip to Main Content

Java Database Connectivity (JDBC)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

ResultSet.GetString() not matching up with string from text box.

843859Jun 3 2008 — edited Nov 20 2014
I am having a problem matching strings...
When I attempt to compare a string got from a textfield with one from the database....they dont match EVEN when they look exactly alike.

The thing is.
I make a new user using the strings from a text field.
I then query the datebase using a WHERE clause to pull out just that user.
I then use resultset.getString("Password") to catch the string value from that column.
I then try comparing the string from the result set with the string from the textfield.
For some reason...they don't match up.

<User TABLE>
Username (Text. limit of 20)
Password (Text. limit of 20)
LastRoom (Number. Default of 1)

<Room TABLE>
RoomID (Autonumber)
RoomDescription (Text)
RoomName (Text)

Assume the database is entirely empty.
Then add one room record with the value of 1.

Now place the database in the parent directory of the gameObjects folder.

Now run loginFrame.java as a Java Application.

The first console message you will get is
Connected to Database: "<databaseFilePath>"
confirming you connected to the database.

Type in the data:
User: Test
Pass: User

Click login

A console message will pop up with the following:
User:'Test' not found.
User Null condition true
Bad User condition true
This is test code to see if it reached certain points.
The first line is if no records were returned when searching for the user.
The second is if the username field is still null for the AccessConnection (meaning no user is logged in)
The third is to notify that the bad user condition is true (at which point the new user button appears).

Without changing the data, press the new user button.
The status bar will notify you that the user was successfully added.

Without changing the data, press the login button.
You will get the following console data:
DATABASE: User:'Test' Password:'User' Room:1
INPUT:    User:'Test' Password:'User'
Database pass:'User'!='User'
User Null condition true
The first two lines reiterate what was retrieved from the database and from user input. As you can see, they seem to match.
However when the two passwords (or users) are checked so see if they are equal, they returned false.

The question is...WHY! Is it some unicode ascii thing?

Here is the two java files in the gameObjects folder. Note: I made this using Eclipse 3.3.

AccessConnection.java
package gameObjects;
import java.io.File;
import java.sql.*;

public class AccessConnection {
	public Connection conn = null;
	public String userName = null;
	public int lastRoom = 0;
	public String statusBar = null;
	final public String BADPASS = "Invalid User password";
	final public String BADUSER = "User does not exist. Please add new user";
	final public String LOGGEDIN = " successfully Logged In";
	final public String EMPTY_PASS_USER = "You must enter something in both password and user";
	final public String OVER_PASS_USER = "Both user and password each have a limit of 20 characters";

	public AccessConnection() {
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			String filename = "gameJM.mdb";
			File inFile = new File(filename);

			String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
			database += inFile.getAbsolutePath().trim() + ";DriverID=22;READONLY=true)";
			
			conn = DriverManager.getConnection(database, "", "");
			System.out.println("Connected to Database: \"" + inFile.getAbsolutePath() + "\"");
		}
		catch (Exception e)
		{
			System.err.println("Open Error:" + e.getMessage());
		}
	}
	
	public Connection getConnection()
	{
		return conn;
	}
	
	public void CloseConnection()
	{
		try {
			conn.close();
			System.out.println("Connection Closed");
		}
		catch (Exception e)
		{
			System.err.println("CloseConnection Error: " + e.getMessage());
		}
	}
	
	public void RunNonQuery(String query)
	{
		try {
			Statement statement = conn.createStatement();
			statement.execute(query);
		}
		catch (Exception e)
		{
			System.err.println("RunNonQuery Error: " + e.getMessage());
		}
	}
	
	public ResultSet RunQuery(String query)
	{
		ResultSet rs = null;
		try {
			PreparedStatement s = conn.prepareStatement(query);
			rs = s.executeQuery();
		}
		catch (Exception e)
		{
			System.err.println("RunQuery Error: " + e.getMessage());
		}
		return rs;
	}
	
	public void Login(String user, String pass)
	{
		ResultSet rs = RunQuery("SELECT * " + 
				"FROM User " +
				"WHERE (Username='"+user+"')");
		Boolean passMatch = false;
		try {
			
		if (rs.next())
		{ 	String userGet = rs.getString("Username");
			String passGet = rs.getString("Password");
			int roomGet = rs.getInt("LastRoom");
			System.out.println("DATABASE: User:'"+userGet+"' Password:'"+passGet+"' Room:"+roomGet);
			System.out.println("INPUT:    User:'"+user+"' Password:'"+pass+"'");
			if (passGet==pass)
				passMatch = true;
			if (!passMatch)
			{	
				System.out.println("Database pass:'"+passGet+"'!='"+pass+"'");
				statusBar = BADPASS;
			}
			else
			{ 	System.out.println("User:'"+user+ "' logged in.");
				userName = userGet;
				statusBar = userName +LOGGEDIN;
				lastRoom = roomGet;
			}
		}
		else
		{	System.out.println("User:'"+user+ "' not found.");
			statusBar = BADUSER;
		}
		rs.close();
		}
		catch (Exception e)
		{
			System.err.println("Login Error: " + e.getMessage());
			
		}
	}
	
	public void Logout()
	{
		userName=null;
	}
	
	public void addUser(String user, String pass)
	{
		if (user.length()>20 || pass.length()>20)
		{
			statusBar = OVER_PASS_USER;
		}
		else if (user.length()==0 || pass.length()==0)
		{
			statusBar = EMPTY_PASS_USER;
		}
		else
		{
			RunNonQuery("INSERT INTO User ( Username, Password, LastRoom )\r\n" + 
					"values('"+user+"','"+pass+"',1);\r\n" + 
					"");
			statusBar = "User:" + user + " added";
		}
	}
	
	public void updateUserRoom()
	{
		RunNonQuery("UPDATE User SET User.LastRoom = " + lastRoom 
				+ " WHERE Username=" + userName);
	}
}
loginFrame.java
package gameObjects;

import java.sql.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;

import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;

import java.awt.*;
import java.awt.event.*;

public class loginFrame extends javax.swing.JFrame {
	private JButton jbtnLogin;
	
	AccessConnection gameDatabase;
	Connection conn;
	private JTextField jtfUser;
	private JButton jbtnLogout;
	private JLabel jlblStatusBar;
	private JLabel jlblPass;
	private JPanel jpLoginButtons;
	private JButton jbtnNewuser;
	private JPanel jpLogin;
	private JLabel jlblUser;
	private JTextField jtfPass;

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		loginFrame inst = new loginFrame();
		inst.setVisible(true);
	}
	
	public loginFrame() {
		super();
		try {
			gameDatabase = new AccessConnection();
			conn = gameDatabase.getConnection();
			
			if (gameDatabase.getConnection() == null)
			{
				System.out.println("Database Connection failure");
			}
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
		initGUI();
	}
	
	private void initGUI() {
		try {
			BorderLayout thisLayout = new BorderLayout();
			getContentPane().setLayout(thisLayout);
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setName("loginFrame");
			this.setDefaultLookAndFeelDecorated(true);
			{
				jlblStatusBar = new JLabel();
				getContentPane().add(jlblStatusBar, BorderLayout.SOUTH);
				jlblStatusBar.setText("Please log in.");
				jlblStatusBar.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
				jlblStatusBar.setPreferredSize(new java.awt.Dimension(440, 18));
			}
			{
				jpLogin = new JPanel();
				getContentPane().add(jpLogin, BorderLayout.NORTH);
				GridBagLayout jpLoginLayout = new GridBagLayout();
				jpLoginLayout.rowWeights = new double[] {0.1};
				jpLoginLayout.rowHeights = new int[] {7};
				jpLoginLayout.columnWeights = new double[] {0.0, 0.1, 0.0, 0.1, 0.0};
				jpLoginLayout.columnWidths = new int[] {};
				jpLogin.setLayout(jpLoginLayout);
				{
					jlblUser = new JLabel();
					jpLogin.add(jlblUser, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
					jlblUser.setText("User");
				}
				{
					jtfUser = new JTextField();
					jpLogin.add(jtfUser, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
					jtfUser.setText("");
				}
				{
					jlblPass = new JLabel();
					jpLogin.add(jlblPass, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
					jlblPass.setText("Password");
				}
				{
					jtfPass = new JTextField();
					jpLogin.add(jtfPass, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
					jtfPass.setText("");
				}
				{
					jpLoginButtons = new JPanel();
					jpLogin.add(jpLoginButtons, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
					{
						jbtnLogout = new JButton();
						jpLoginButtons.add(jbtnLogout);
						jbtnLogout.setText("Logout");
						jbtnLogout.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								jbtnLogoutActionPerformed(evt);
							}
						});
					}
					{
						jbtnNewuser = new JButton();
						jpLoginButtons.add(jbtnNewuser);
						jbtnNewuser.setText("New User");
						jbtnNewuser.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								jbtnNewuserActionPerformed(evt);
							}
						});
					}
					{
						jbtnLogin = new JButton();
						jpLoginButtons.add(jbtnLogin);
						jbtnLogin.setText("Login");
						jbtnLogin
						.addActionListener(new ActionListener() {
							public void actionPerformed(
									ActionEvent evt) {
								jbtnLoginActionPerformed(evt);
							}
						});
					}
				}
			}
			this.addWindowListener(new WindowAdapter() {
				public void windowOpened(WindowEvent evt) {
					thisWindowOpened(evt);
				}
				public void windowClosed(
						WindowEvent evt) {
					rootWindowClosed(evt);
				}
			});
			pack();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void thisWindowOpened(WindowEvent evt) {
		jbtnNewuser.setVisible(false);
		jbtnLogout.setVisible(false);
		jpLogin.repaint();
	}
	
	private void rootWindowClosed(
		WindowEvent evt) {
		try {
			gameDatabase.CloseConnection();
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}
	}
	
	private void jbtnLoginActionPerformed(
			ActionEvent evt) {
			gameDatabase.Login(jtfUser.getText(), jtfPass.getText());
			if (gameDatabase.userName == null)
			{	System.out.println("User Null condition true");
				if (gameDatabase.statusBar == gameDatabase.BADUSER)
				{	System.out.println("Bad User condition true");
					jbtnNewuser.setVisible(true);	}	
			}
			else
				{
				jbtnNewuser.setVisible(false);
				jbtnLogin.setVisible(false);
				jbtnLogout.setVisible(true);
				}
				
			jpLogin.repaint();
			jlblStatusBar.setText(gameDatabase.statusBar);
					
		}
	
	private void jbtnLogoutActionPerformed(ActionEvent evt) {
		gameDatabase.Logout();
		jbtnLogin.setVisible(true);
		jpLogin.repaint();
	}
	
	private void jbtnNewuserActionPerformed(ActionEvent evt) {
		gameDatabase.addUser(jtfUser.getText().trim(), jtfPass.getText().trim());
		jlblStatusBar.setText(gameDatabase.statusBar);
		if (gameDatabase.statusBar != gameDatabase.OVER_PASS_USER 
				&& gameDatabase.statusBar != gameDatabase.EMPTY_PASS_USER)
		{
			jbtnLogin.setVisible(true);
			jbtnNewuser.setVisible(true);
			jpLogin.repaint();
		}
	}
}
Could you please help me?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 1 2008
Added on Jun 3 2008
3 comments
846 views