Quick question. I got a code below, which checks with a database whether a given ID is available in the database, if so, it retrieves all attendance histories for the ID, otherwise if the ID didn't exist in the database it should display an error message. The code I got however, always says that the record has been attached, and then displays the error message as well regardless whether the ID exists or not. I think I probably have to change the order of the code or such? Could you please advise?
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent arg0) {
String studentID = textField.getText();
try {
Statement st = con.con.createStatement();
ResultSet rs = st.executeQuery("SELECT StudentID, date FROM attendance WHERE StudentID ="+textField.getText());
while ( rs.next() ) {
String student = rs.getString("StudentID");
String date = rs.getString("date");
System.out.println(student+"");
System.out.println(date);
}
JOptionPane.showMessageDialog(frmAttendanceHistory, "Attendance has been registered.");
frmAttendanceHistory.setVisible(false);
if (!rs.next()) {
JOptionPane.showMessageDialog(frmAttendanceHistory, "A record for the given Student ID doesn't exist");
}
}
catch (SQLException e) {
JOptionPane.showMessageDialog(frmAttendanceHistory, "Attendance couldn't be registered. Please try again!");
e.printStackTrace();
}
}
});
You're repeatedly calling rs.next() until it returns false (as otherwise you'll never get out of the while loop) - then you're calling rs.next() again. Why would you expect it to return true then?
I suspect you want something like:
if (rs.next()) {
String student = rs.getString("StudentID");
String date = rs.getString("date");
System.out.println(student+"");
System.out.println(date);
JOptionPane.showMessageDialog(frmAttendanceHistory,
"Attendance has been registered.");
frmAttendanceHistory.setVisible(false);
} else {
JOptionPane.showMessageDialog(frmAttendanceHistory,
"A record for the given Student ID doesn't exist");
}
You're doing a second rs.next, which would go to a second record if there was one. If there's only one (which is already consumed further up in your app), then it fails giving you a success followed by a failure.
while ( rs.next() ) {
followed by
if (!rs.next()) {
Doesn't make any sense as the if will always execute. Your loop will continue until rs.next() returns false.
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 wanted an error to popup, when the user entered a wrong id into the delete field. But even if a wrong id is entered, the query still proceeds, but no data is deleted. Here's my code:
String value = jTextField19.getText();
if (value == null || "".equals(value)) {
JOptionPane.showMessageDialog(null, "The field is blank!");
} else {
theQuery("DELETE FROM inventorydb WHERE item_id=('"+jTextField19.getText()+"') AND item_id IS NOT NULL");
}
The theQuery method:
private void theQuery(String query) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory", "root", "");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Done!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error!");
}
}
First of all: do not ever directly build SQL queries from user input, use prepared statements instead. If you don't know about SQL Injection, you should.
If you are using JDBC, you can check the result of #executeUpdate() to see how many rows were affected. If it was zero, then you can say that it was a wrong id.
This is the method definition:
public int executeUpdate(java.lang.String sql)
The return value is:
An int that indicates the number of rows affected, or 0 if using a DDL statement.
In the program at hand, you can just simply do this:
int deleted = st.executeUpdate(query);
if (deleted == 0) {
JOptionPane.showMessageDialog(null, "Nothing to delete!");
return;
}
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"); ..
I am a beginner in writing programs, I have created a search record function for my assignment.
public void searchRecord(){
for(int ct = 0; ct< 1; ct++){
System.out.println("Please insert student ID");
System.out.print("Student ID: ");//prompt for student ID to search
String data = k.nextLine().trim();
String sql = "SELECT * FROM Students WHERE StudentID = '"+data+"'";
try{
rs = st.executeQuery(sql);
if(rs.next()){
displayRecord();
rs.next();
showMenu();
}
else{
System.out.print("No record found. ");
ct--;
}
}catch (Exception ex){
System.out.println("Problem searching.");
}
}
However, after I try to get data from the result, it shows Invalid Cursor State.
If I want to retrieve data, I'll have to execute the Display next record method which is:
try{
if(rs.next()){
displayRecord();
}
else{
rs.previous();
System.out.println("No more records!");
}
}catch (Exception ex){
System.out.println("There is problem showing next data.");
}
I tried adding "rs.next" at the search record method after "displayRecord" but it wouldn't solve the problem. Is there anyway to solve this?
By the way my display record method:
public void displayRecord(){//get and display data from current row of record
try{
String ID = rs.getString(1);
String fname = rs.getString(2);
String lname = rs.getString(3);
String conNo = rs.getString(4);
String mail = rs.getString(5);
String plate = rs.getString(6);
Date date = rs.getDate(7);
System.out.print("Student ID: "+ID+"\nName: "+fname+" "+lname+"\nCar Number: "+plate+"\nContact Number: 0"+conNo+"\nE-Mail Address: "+mail+"\nDate Registered: "+date);
}catch (Exception ex){
System.out.println(ex);
}
}
Any helps or advices are appreciated.
I don't quite understand what your code is supposed to do. But I suspect you don't fully understand how JDBC statements and result sets work.
If you execute a query that returns many rows, you would write something like this:
ResultSet rs = stmt.executeQuery(sqlQuery);
while (rs.next()) {
String id = rs.getString(1);
String name = rs.getString(2);
// do something with the current row
}
Note that ResultSet instance allows you to access the data from the current result row. next() both advances to the next result row and tells you if there is next row (or whether you have advanced beyond the last row). Initially, it's positioned before the first result row. So next() needs to be called before accessing the first row's data. But that's all done in the single line while (rs.next()).
In your case, I would expect that the query only returns a single result row as the StudendID is most likely a unique key. So the code would look like this:
ResultSet rs = stmt.executeQuery(sqlQuery);
if (rs.next()) {
String id = rs.getString(1);
String name = rs.getString(2);
// do something with the current row
} else {
// no student with specified ID found
}
However, you code contains two calls to next() and another one to previous(), which is confusing.
There error message Invalid Cursor State indicates that you are trying to access the current row's data when in fact the result set is position before the start or after the end of the result set.
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.