I have a java Swing Application that in which i'm designing a small brain challenge game. The issue is that I'm stack at the first stage of the game where I want to load the details of the current user from an sqlite database, but from two different tables. Here's my full code:
//This is the method that loads the data
private void showDetails(){
try(Connection dbConn = dbConnect.initConn()){
Statement stmt = dbConn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM status");
//Display the name of the Current User
if(rs.next()){
currentUserLbl.setText(rs.getString("currentUser"));
else{
JOptionPane.showMessageDialog(null, "An Unknown Error Occureds.");
dispose();
indexMenu im = new indexMenu();
im.setVisible(true);
}
stmt.close();
//Update the form with the other values from the database
PreparedStatement uStmt = dbConn.prepareStatement("SELECT Score, Level FROM users WHERE Name = ?");
uStmt.setString(1, currentUserLbl.getText());
ResultSet uRs = uStmt.executeQuery();
if(rs.next()){
levelLbl.setText(rs.getString("Level"));
highscoreValue.setText(rs.getString("Score"));
}
else{
//This error shows up anytime I run the code
JOptionPane.showMessageDialog(null, "An Unknown Error Occured.");
//This line also seems not to work
this.dispose();
indexMenu im = new indexMenu();
im.setVisible(true);
}
uStmt.close();
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Anytime I run the program, it shows the error I've indicated in the code. I just don't know what I've done wrong. Any help will be much appreciated.
Related
Cheers everyone, beginner here!.
I'm currently working on a Java application to keep track of the inventory in our warehouse. It's all on localhost until it's finished. I've created two tables in MySQL database: one table shows the article code, location and quantity (VOORRAADSYSTEEM); the other table shows article code and description (STAMDATA).
In my GUI, I've got a JTable which loads data from VOORRAADSYSTEEM, and on mouseclickevent (getSelectedRow) shows the data in the corresponding JTextFields (so far so good). The only field not showing is the description field (which should be read from the STAMDATA table).
I've tried creating a method for this specific part of the program. The method runs a query to the second table using a inner join to the first table. Here's the code below.
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(2, sql);
descriptionTxt.setText(rs.getString(sql));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
At this moment I'm not exactly sure how to approach this problem. I'm also going to try using foreign keys. Any help would be appreciated.
There are better ways to handle what you want to do. For instance you could get all the information you need with one query by joining the table on a common column (ARTICLENUMBER and ARTICLECODE) and then display it.
Right now it looks/sounds like you might be trying to get all the information with two queries.
However, there are some errors with your load description method:
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
ResultSet results = conn.createStatment().executeQuery(sql);
if(results.next()) //make sure something was returned to avoid null pointer exception
descriptionTxt.setText(rs.getString("DESCRIPTION"));
else
JOptionPane.showMessageDialog(null, "no results returned");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This should work a little better for you.
Inside my Add button click i have typed some codes which works very well and inside my try catch block i have two JOptionPane messages. 1st message is to say that info has been added sucessfully and the other which is inside the catch block is to say that Client cannot be added twice to the same tour on same date.
When I run this code without any primary key violations it shows the 1st message (which is correct) but also shows the 2nd message as well. It should show only 1st message and stop. But after showing both messages it adds to the database.
When I enter something that will give primary key violation, it shows add successfully message( which is wrong) and then the Error message. It doesnt add to the database.
What am I doing wrong?
Here is my code.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DBConnection db = new DBConnection();
if (txt_name.getText().isEmpty() || txt_escort.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Cannot have empty fields");
} else {
clientID = combo_client.getSelectedItem().toString();
tourID = combo_tour.getSelectedItem().toString();
date = combo_date.getSelectedItem().toString();
escortID = txt_escort.getText();
clientName = txt_name.getText();
try {
query = "INSERT INTO tourRParticipant(ClientID,Name,TourID,StartDate,EscortID) VALUES (?,?,?,?,?)";
PreparedStatement stm = db.getconn().prepareStatement(query);
JOptionPane.showMessageDialog(null, "Added successfully!");
stm.setString(1, clientID);
stm.setString(2, clientName);
stm.setString(3, tourID);
stm.setString(4, date);
stm.setString(5, escortID);
rs = stm.executeQuery();
rs.next();
conn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR..Client cannot be added to the same tour with the same date");
}
ViewTable();
}
}
First of all, you display the success message JOptionPane.showMessageDialog(null, "Added successfully!"); before executing the update. It should be displayed after the insert statement is executed.
Second of all, you should call executeUpdate not executeQuery, since you are executing an INSERT statement.
stm.executeUpdate();
JOptionPane.showMessageDialog(null, "Added successfully!");
JOptionPane.showMessageDialog(null, "Added successfully!");
should be after
rs = stm.executeQuery();
And as pointed in other answer, stmt.executeUpdate() should be used instead of stmt.executeQuery(). As you are passing an update query to executeQuery() method, it is throwing exception. That's why you are always getting two messages.
I am making a GUI and I need to update one column called "OCCURRENCES" whenever a patient needs help. I am using Netbeans (Java). For some reason I am not getting any errors. But My table does not Update. The executeUpdate is returning '0'. I have close all my result set statements and prepared statements at the end of the 'try', 'catch'.Also any other updates like updating from textfields, insertion of new patient and deleting patient from a table is working fine; just having problem with updating this column which initial value I have set to be zero whenever an occurrence happens I would like to call this method to increment value on column. I'm just learning to use sqlite, and I am really confuse please help here is the part of the code I am having problems with, Also it reaches the JOPtionPane message successfully.
try
{
conn = javaConnect.ConnectDB();//Returns Connection
PreparedStatement pst = conn.prepareStatement("UPDATE PEMs SET OCCURRENCES = ? "//1
+ "WHERE ROOM = ?");//2
pst.setInt(1, 1);
pst.setInt(2,1);
pst.executeUpdate();
int updated=pst.executeUpdate(); // get count to see if anything was updated
System.out.println("OCC" + updated);
JOptionPane.showMessageDialog(null, "SUCCESSFULL OCCURRENCE");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error UpdateOccurence :" + e);
e.printStackTrace();`enter code here`
}finally {
try{
rs.close(); pst.close(); }
catch(Exception e) { } }
I have been able to link postgresql with java. I want the user to input a name in a text box in java and a search is performed and checks if the name exists in the database.
My code so far:
String hostname=this.hostNameText.getText();
try
{
s = connection.createStatement();
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = "+hostname;
rs = s.executeQuery(q);
}catch(Exception e)
{
System.out.println("Problem in searching the database 1");
}
I am getting problem to link to the table hostdetails. Please note that hostdetails contain a field nammed HOSTNAME(in capital letters). When I run the above code, I get "Problem in searching the database 1"is displayed. Kindly please help me:)
Try using parameterized queries to protect against SQL injection. Use as follows:
String hostname=this.hostNameText.getText();
try
{
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = ?"; //notice change here
//and use params like this
PreparedStatement pStmnt = connection.prepareStatement(q);
pStmnt.setString(1, hostname);
rs = pStmnt.executeQuery(q);
}catch(Exception e)
{
//error handling here
}
I am working in a project known as Employee attendance management system.For this I had created a java form.The form contains employee ID,employee name fields,next button.
If I press next button the next employee details has to be displayed in the above two fields.In order to do this I had used for loop the problem hear appears is it is displaying last employee details from the database.
My code is:
int i=1;
try {
ResultSet rs;
Connection con;
Statement st;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:vasu");
st = con.createStatement();
for(i=1;i<=5;++i){
rs = st.executeQuery("select ID,EName from attendence where ID="+(i));
while(rs.next()) {
t1.setText(rs.getString("ID"));
t2.setText(rs.getString("EName"));
}
}
}
catch (Exception e) {
}
Sorry for my poor english.
Could any one please help me..
Well Thanks in advance.
There is problem in this loop
while(rs.next()) {
t1.setText(rs.getString("ID"));
t2.setText(rs.getString("EName"));
}
you need to store the values from database in an array and then iterate over it with your (prev,next) button like
i=0;
while(rs.next()) {
dataset["id"][i]=(rs.getString("ID");
dataset["EName"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
t1.setText(dataset["id"][i]);
I have not checked syntax but the logic is correct.
The values are being overwritten each time in t1 and t2 when you call the loop. This is why the last record value is being displayed.