I'm working on a program to manage students in a DB, and I'm working on the part where students can sign in, but for some reason I can never get the if statement to be true. I'm thinking it has something to do with the value I'm getting from the database being an object as opposed to a String. I've tried casting it to String but I get an error, is there anyway I can compare these two values? My code is below so you can take a look. I know there are other questions like this, but I've not been able to get any of their solutions to work. Thanks so much in advance.
public void actionPerformed(ActionEvent e)
{
//int i;
//String name;
if(e.getSource()==logInButton)
{
String name="";
String password="";
name=inputField.getText();
password=inputField2.getText();
try {
connection = DriverManager.getConnection(connectionString, username, pass);
PreparedStatement statement = (PreparedStatement) connection.prepareStatement("SELECT * FROM students");
data = statement.executeQuery();
while(data.next()){
//login = data.getObject("student_id").equals(name) && data.getObject("password").equals(password);
if(data.getObject("student_id").equals(name) && data.getObject("password").equals(password))
{
System.out.println("login = true");
logInPanel.setVisible(false);
postLogInPanel.setVisible(true);
}
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Instead of doing:
data.getObject("student_id");
Try:
data.getString("student_id");
This is assuming your student_id field is some sort of char field. Also you may want to try comparing using
.equalsIgnoreCase //instead of .equals for username unless it is case sensitive...
first of all you need to query the database like
SELECT * FROM students where username='THE ENTER USERNAME' and password='Entered password'
if the size of the result set == 1 then login else invalid credentials or user doesn't exit...
Data of the object can be got via
data.getInt("student_id"); ..
Related
I have tried this so many times but I never did it, this is my code
public static Boolean checkhaveguild(String name) {
try {
Statement statement = connection.createStatement();
PreparedStatement ps = connection.prepareStatement("SELECT * FROM guild");
System.out.println(statement.execute("SELECT * FROM guild WHERE name = "+name+""));
System.out.println("----------");
} catch (SQLException e) {
throw new RuntimeException(e);
}
return false;
}
I am doing a guild plugin on BungeeCord and getting data from MySQL
The code is about checking if the row does not exist and output to boolean
I'd suggest you to learn more about the basics of programming in Java! Minecraft is a great way to start into programming, but you should be interested in doing things properly.
public static boolean hasGuild(String name) {
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = connection.prepareStatement("SELECT COUNT(name) FROM guild WHERE name = ?");
statement.setString(1, name);
resultSet = statement.executeQuery();
if (resultSet.next()) return resultSet.getInt(1) > 0;
} catch (SQLException e) {
// TODO properly handle exception
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO properly handle exception
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO properly handle exception
}
}
}
return false;
}
Some thoughts on what this code is doing:
Asking the database for the number of rows whose name column matches the given string. Always make sure that you only request the data that's necessary for your purpose. Requesting all columns with their data is overkill if you only want to answer if there are any rows or not.
If the number of rows is greater than zero, it'll return true, because there are rows with a matching name column.
Some thoughts you should make yourself:
What is contained in the name column? If it's the guild's name, then that's fine, but if that's the player's name you should consider re-thinking your code. Player's in Minecraft can change their name and hence would lose their guild on your server. Players in Minecraft are uniquely identified by their UUID, which will never change. Maybe consider using the UUID then!
In order for the query to be as fast a possible you should set an INDEX on the name column. That will speed up the lookup proccess even if there are plenty of rows!
Nevertheless: Welcome to StackOverflow! I hope that I could help you and I wish lot's of fun with programming.
in the try, i try sout resultSet and statement before close and it send this to me
resultSet :
com.mysql.cj.jdbc.ClientPreparedStatement: SELECT COUNT(name) FROM guild WHERE name = 'a'
statement :
com.mysql.cj.jdbc.ClientPreparedStatement: SELECT COUNT(name) FROM guild WHERE name = ** NOT SPECIFIED **
and return false is my test at last it will return true if it have if not it will return false
I am currently working on a simple JDBC project and I am stuck at the login form
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/company","root","redhat");
stmt=con.createStatement();
String nm=jTextField1.getText();
char[] pass=jPasswordField1.getPassword();
String pw=Arrays.toString(pass);
String sql="select * from login where uname='"+nm+"' and pass='"+pw+"'";
rs=stmt.executeQuery(sql);
if(rs.next())
{
new MainPage().setVisible(true);
this.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(this, "Wrong User name or password");
jTextField1.setText("");
jPasswordField1.setText("");
}
}
catch(Exception e)
{
System.out.println(e);
}
} `
When this button is clicked a new page that I have created is to be shown ,but it shows "Wrong User name or password" message dialog.
What are my mistakes?
My database is in mysql.
Error 1: Arrays.toString(char[]) will return an array representation, e.g. if the password in jPasswordField1 is password, the result is this string: [p, a, s, s, w, o, r, d]
Fix 1: Use new String(char[]) instead.
Error 2: Using string concatenation to build a SQL statement. This will make your code susceptible to SQL Injection attacks, where hackers can steal your data and delete your tables.
Fix 2: Use a PreparedStatement.
Error 3: Not releasing resources. This will lead to memory leaks.
Fix 3: Use try-with-resources.
Result:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
boolean loginOk;
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost/company","root","redhat")) {
String sql = "select * from login where uname=? and pass=?";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setString(1, jTextField1.getText());
stmt.setString(2, new String(jPasswordField1.getPassword()));
try (ResultSet rs = stmt.executeQuery(sql)) {
loginOk = rs.next();
}
}
}
if (loginOk) {
new MainPage().setVisible(true);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(this, "Wrong User name or password");
jTextField1.setText("");
jPasswordField1.setText("");
}
} catch(Exception e) {
System.out.println(e);
}
}
Arrays.ToString Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements.
In your case Instead of
String pw = Arrays.toString(pass);
You should be using to get the password in String representation.
String pw = String.copyValueOf(pass);
That would seem to indicate that your query returns an empty result set. What happens if you run it against the DB directly?
Also, Arrays.toString(...) will give you a String representation of the array. You probably want the contents of the array in a String - there's a difference. Try using new String(pass) instead.
I think "Wrong User name or password" means rs is null or rs'size is 0.
You should check the name and password.
i want to update a date in the database under some condition, so i tried this method that i call it in button action performed
public void DeleteDate (JTextField txt1, JTextField txt2)
{
try {
Class.forName("com.mysql.jdbc.Driver");
String m = "IMCDietitian";
String unicode= "?useUnicode=yes&characterEncoding=UTF-8";
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/"+m+""+unicode+"","root","");
System.out.println("connected");
String dept = jComboBox1.getSelectedItem().toString();
Statement st = conn.createStatement();
st.executeUpdate("UPDATE "+dept+" SET edate = '"+jTextField1.getText()+"' WHERE pname = '"+txt1.getText()+"' AND rno = '"+txt2.getText()+"' AND edate = '-'");
}
catch (Exception e) {
e.printStackTrace();
}
}
But it doesn't update any thing in the database. Can any one help me?
There could be these reasons for not seeing any updates:
Perhaps the where clause does not result in any rows being returned therefore no row is updated.
Perhaps autocommit is false. In this case you would need to call commit explicitly. As a note, you could also take a look at transactions.
An Exception but it seems that in this case there is none.
Also, use PreparedStatement - it is cleaner and gets compiled for reuse.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm working on a student database managing program, and am working on the login phase. I query the database for the students id and password and try and match an entry to what the student enters. When a match is found login should be set to true, and it should go to the next page, but for some reason its never passing my if then statement. I'm not entire sure whats wrong,the code for this is below. You'll notice the system.out.println statements, those are there so I can see if it is actually going through the database correctly, and as far as I can tell it does, but login next gets set to true. I would really appreciate any help.
public void actionPerformed(ActionEvent e)
{
//int i;
//String name;
if(e.getSource()==logInButton)
{
String name="";
String password="";
name=inputField.getText();
password=inputField2.getText();
System.out.println(name);
System.out.println(password);
boolean login = false;
try {
connection = DriverManager.getConnection(connectionString, username, pass);
PreparedStatement statement = (PreparedStatement) connection.prepareStatement("SELECT * FROM students");
data = statement.executeQuery();
while(data.next()){
System.out.println(data.getObject("student_id"));
System.out.println(data.getObject("password"));
if (data.getObject("student_id") == name && data.getObject("password") == password){
login = true;
}
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(login == true){
System.out.println("login = true");
logInPanel.setVisible(false);
postLogInPanel.setVisible(true);
}
}
In Java, == is object identity. a==b is true if a and b are references to the same object in memory. When you're comparing reference types, like Strings and possibly whatever e.getSource() returns, you should use the equals method to see if the values are the same.
I have used if loop to compare the values present in table and the value entered from the user, but in the code its not entering to if loop rather it is entering to else loop, i need the suggestion for the problem.
Here is the code :
public void idExists(String SkillID) {
try{
Connection conn = dbconnect();
conn.setReadOnly(false);
Statement st = conn.createStatement();
String skilid= "Select [Skill ID]from [Skill Master$]";
ResultSet rs = st.executeQuery(skilid);
while(rs.next()){
String Skill = rs.getString("Skill ID");
System.out.println(SkillID);
}
if (SkillID==Skill) {
System.out.println("the skill id exist");
}
else {
System.out.println("the skill id doesnt exist");
}
endConnect();
}
catch(SQLException e) {
System.err.println("Got an exception in idexist");
System.err.println(e.getMessage());
}
}
}
You're comparing string value by reference.
Since your variable refer to two different String instances with the same value, the condition is false.
You should compare strings using the equals method.
Also, you probably want to put the if inside the loop.
Finally, you should replace all of that code with a (parameterized!) WHERE clause.