I am relativity new to java programming any way here what i am trying to do
I am trying to populate combobox1(Add list) with the courses available to the student and then removing the selected item and sending to combobox2(drop list)
but its simply not reacting right especially when the student doesn't have any courses that are available to add and it returns the exceptions
"net.ucanaccess.jdbc.ucanaccessSQLException:cardinality violation"
&
"java.lang.NullPointerException"
here's how initialize each of the comboboxes
try
{String mail=Login.user_mail;
String sql = "select CourseCode from Course where CourseCode!=(select CourseCode from CourseStudent where StudentEmail='"+mail+"') OR NOT EXISTS(select CourseCode from CourseStudent where StudentEmail='"+mail+"')";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox1.setModel(m);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.toString());
}
then combo box2
String mail=Login.user_mail;
String sql = "select CourseCode from CourseStudent where StudentEmail='"+mail+"'";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox2.setModel(m);
}
this is within the Add button
String ID = (String) jComboBox1.getSelectedItem();
String mail=Login.user_mail;
try {
dbm.insert(" insert into CourseStudent (StudentEmail, CourseCode ) values ('"+mail+"', '"+ID+"') ");
jComboBox2.addItem(jComboBox1.getSelectedItem());
jComboBox1.removeItem(jComboBox1.getSelectedItem());
} catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Insertion Faild\n"+ex);
}
and this is with the drop button
try {
String ID = (String) jComboBox2.getSelectedItem();
String mail=Login.user_mail;
dbm.delete("delete from CourseStudent where CourseCode='"+ID+"' And StudentEmail='"+mail+"'");
jComboBox1.addItem(jComboBox2.getSelectedItem());
jComboBox2.removeItem(jComboBox2.getSelectedItem());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Delete Faild\n"+e);
}
i think the problem lays in the combobox1 SQl statement but i really can't see any other way to do it as i need to retrieve the courses from a table while making sure that the user doesn't take it already from another table...
any help would be greatly appreciated as i said i have been using java for a couple of weeks now and i haven't used sql before so i am a little lost
Related
Good day, just wanna ask. I have a Java GUI where I want to add multiple data from SQL server to my Jtable. The flow here is that I would want to use the text field as search field where I will add the info for searching and use the Jbutton to perform the search action then it will give/show me the data to my Jtable. Actually the code is running however some of the data like the 1st data added to my SQL serve and from data id 7 and and up are not showing. How would I fix this and show multiple data with same order ID form SQL server?
Thank you!!
try {
String query = "select * from `sales_product` where order_id = ?";
pst = con.prepareStatement(query);
pst.setString(1, txsearch.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
while(rs.next()) {
String prodname = rs.getString("prodname");
String price = String.valueOf(rs.getInt("price"));
String qty = String.valueOf(rs.getInt("qty"));
String total = String.valueOf(rs.getInt("total"));
model = (DefaultTableModel) datatable.getModel();
model.addRow(new Object[]{
prodname,
price,
qty,
total
});
int sum = 0;
for (int a = 0; a < datatable.getRowCount(); a++) {
sum = sum + Integer.parseInt(datatable.getValueAt(a, 3).toString());
}
Ltotal.setText(Integer.toString(sum));
}
}
else {
JOptionPane.showMessageDialog(this, "No order found!");
txsearch.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(milktea.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(rs.next()) {
while(rs.next()) {
No need for the if (rs.next()) statement. That is causing you to skip the first row of data in the ResultSet.
All you need is the while (rs.next()) statement to create the loop to read all rows in the ResultSet.
Good evening all!
I've been working on a simple warehouse/inventory management system which is connected to a mySql database. One of the tables in that database (OESCODE) has information about which area ("AREA") of the warehouse an article is in, and a corresponding numeric value ("CODE"). Example, small goods would be 1, long goods would be 2 etc etc.
In the GUI, i've a jCombobox that allows you to select the area, and the idea is to have a textfield below display the corresponding numeric value.
Here's a screenshot of what I mean:
Screenshot 1
It's the fields labeled Hal (halCombo) and OES (oesTxt) Code.
The corresponding code:
private void pickHalComboPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
String fill = (String) halCombo.getSelectedItem();
String query = "SELECT * FROM OESCODE WHERE AREA=?";
try {
pst = conn.prepareStatement(query);
pst.setString(1, fill);
rs = pst.executeQuery();
if (rs.next()) {
String code = rs.getString("CODE");
oesTxt.setText(code);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Here's the catch though: the fields above (labeled Artiekelcode, Omschrijving and Eenheid) do EXACTLY the thing i'm describing above. Example, when i click a value in the Artiekelcode field, the Omschrijving and Eenheid fields get autofilled with the corresponding values (from a different database table, ofcourse).
Here's the code for that:
private void pickArticleComboPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
String fill = (String) pickArticleCombo.getSelectedItem();
String query = "SELECT * FROM STAMDATA WHERE ARTIKELNUMMER=?";
try {
pst = conn.prepareStatement(query);
pst.setString(1, fill);
rs = pst.executeQuery();
if (rs.next()) {
String desc = rs.getString("OMSCHRIJVING");
String eenh = rs.getString("EENHEID");
eenheidTxt.setText(eenh);
pickDescriptionTxt.setText(desc);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
So for the past hours, I've been trying to figure out why it works on the fields above and not on the fields below, since both principles are the same.
Any thoughts would be highly appreciated.
Thanks in advance!
First I have table Appointment_Table with columns Appointment_ID,Doc_ID,Dep_Id,SchedDate,Patient_ID and Patient_Table with Patient_ID,FName,MI,LName, and so on.... and Doctor_Table with Doc_ID,FName,MI,LName and so on... so that I created a frame Add Appointments frame with 3 JComboBox first is Department Name and it contains of course the Deparment Name and then the Doctor Names inside it contains FName,Mi,LName and same for the Patient Name.
So that I insert all departments name in JCombobox that only have a doctor
public void ViewDepartmentName(){
try{
String sql = "Select DISTINCT Department_Name from Department_Table\n" +
"inner join User_Table on Department_Table.Department_ID=User_Table.Department_ID\n" +
"where Role_ID = 3";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String add1 = rs.getString("Department_Name");
DoctorDep.addItem(add1);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
so whenever I click the JComboBox of Department name it will show only the Department name that have a doctors
and also for the Patient Name
private void ViewDoctorPatientsBox(){
try{
String sql = "Select * from Patient_Records";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String add1 = rs.getString("First_Name");
String add2 = rs.getString("MI");
String add3 = rs.getString("Last_Name");
DoctorPatient.addItem(add1+" "+add2+" "+add3);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
}
and in Patient Name I insert the Fname,MI,Lname like so showed in the code above
same with the Doctor Names it only show when I select their Departments like so
try{
String sql = "Select * from User_Table\n" +
"inner join Department_Table on User_Table.Department_ID=Department_Table.Department_ID\n" +
"where Department_Name = ? AND Availability = 1";
pst = conn.prepareStatement(sql);
pst.setString(1, (String)DoctorDep.getSelectedItem());
rs = pst.executeQuery();
DoctorNames.removeAllItems();
DoctorNames.addItem("Select");
while(rs.next()){
String add1 = rs.getString("First_Name");
String add2 = rs.getString("MI");
String add3 = rs.getString("Last_Name");
DoctorNames.addItem(add1+" "+add2+" "+add3);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally {
try {
rs.close();
pst.close();
}catch(Exception e){
}
}
after I select all I want to select I need to save it to Appointment_Table that only their Doc_ID,Dep_ID,Patient_ID but the JComboBox have the name what syntax should I do?
that only their Doc_ID,Dep_ID,Patient_ID but the JComboBox have the name what syntax should I do?
Your combo box needs to store two pieces of data:
the ID
the name.
So you need to create a custom object to store in the combo box and then you need to only display the name in the combo box.
There are two approaches to displaying the name:
Create a custom renderer. This is the better approach but is a little more involved. See Combo Box With Custom Renderer for an example of this approach.
Override the toString() method of your custom object to simply return the name. The default renderer for the combo box will invoke the toString() method of the object. See Combo Box With Hidden Data for more information on this approach.
I have read notes about this but none seems to work for me. I have an SQLite database and with Netbeans as my IDE, I have a jframe that displays data records in a jtable, with records displayed in ascending order. Clicking on a record displays them in jtextfields.
I want to move to next record in database in ascending order when I click on a button, but it doesn't seem to work. What am I doing wrong?
try{
String sql ="select * from Employees order by Name ASC";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
int i = rs.getInt("ID");
String idi= Integer.toString(i);
id.setText(idi);
String a = rs.getString("Name");
name.setText(a);
String b = rs.getString("Contact");
contact.setText(b);
String c = rs.getString("Email");
email.setText(c);
String d = rs.getString("Residence");
residence.setText(d);
String e = rs.getString("Job_Type");
comboJob.setSelectedItem(e);
}
else {
rs.previous();
}
}
catch(SQLException | HeadlessException ex)
{
JOptionPane.showMessageDialog(null, ex);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
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]=Integer.toString(rs.getInt("ID"));
dataset["Name"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
id.setText(dataset["ID"][i]);
name.setText(dataset["EName"][i]);
not checked syntax but the logic is correct.
I have a MySQL database which contains data i would like to populate into a JList in my java program. I have two JList, one which is fill with Events Title and the second is to be fill with Guest Name.
What i would like is when the user click on any of the Events Title, the second JList will show all the Guest Name that belong to that Event.
I have already successfully populate the first JList with all the Events Title. What I'm having trouble with is when the user click on the Events Title, the Guests Name will show twice on the second JList. How can i make it to show only once?
Here is what i got so far...
Java Class
private JList getJListEvents() {
if (jListEvents == null) {
jListEvents = new JList();
Border border = BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(1, Color.black, Color.black), "Events", TitledBorder.LEFT, TitledBorder.TOP);
jListEvents.setBorder(border);
jListEvents.setModel(new DefaultListModel());
jListEvents.setBounds(new Rectangle(15, 60, 361, 421));
Events lEvents = new Events();
lEvents.loadEvents(jListEvents);
jListEvents.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
EventC eventC = new EventC();
//eventC.MonitorRegDetailsInfo(jListEvents, jTextFieldEventName, jTextFieldEventVenue, jTextFieldEventDate, jTextFieldEventTime, jTextAreaEventDesc);
//eventC.MonitorRegPackageInfo(jListEvents, jTextFieldBallroom, jTextFieldBallroomPrice, jTextFieldMeal, jTextFieldMealPrice, jTextFieldEntertainment, jTextFieldEntertainmentPrice);
eventC.MonitorRegGuest(jListEvents, jListGuest);
}
});
}
return jListEvents;
}
Controller Class
public void MonitorRegGuest(JList l, JList l2){
String event = l.getSelectedValue().toString();
Events retrieveGuest = new Events(event);
retrieveGuest.loadGuests(l2);
}
Class with all the sql statement
public void loadGuests(JList l){
ResultSet rs = null;
ResultSet rs2 = null;
ResultSet rs3 = null;
MySQLController db = new MySQLController();
db.getConnection();
String sqlQuery = "SELECT MemberID FROM event WHERE EventName = '" + EventName + "'";
try {
rs = db.readRequest(sqlQuery);
while(rs.next()){
MemberID = rs.getString("MemberID");
}
} catch (SQLException e) {
e.printStackTrace();
}
String sqlQuery2 = "SELECT GuestListID FROM guestlist WHERE MemberID = '" + MemberID + "'";
try {
rs2 = db.readRequest(sqlQuery2);
while(rs2.next()){
GuestListID = rs2.getString("GuestListID");
}
} catch (SQLException e) {
e.printStackTrace();
}
String sqlQuery3 = "SELECT Name FROM guestcontact WHERE GuestListID = '" + GuestListID + "'";
try {
rs3 = db.readRequest(sqlQuery3);
while(rs3.next()){
((DefaultListModel)l.getModel()).addElement(rs3.getString("Name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
db.terminate();
}
Thanks in advance!
Please for the time being forget about the SQL. Then follow the steps below:
Start with the example --- the corresponding Java Web Start link.
Play with the sample, to see how to add elements to a list.
Then all you need to do is grab a reference to the one you want to copy and for each element copy it then add to the 2nd list.
Enjoy Java.
EDIT:
I am still looking at your code and I am still confused of what is going on (Please consider making a SSCCE). But let me guess, as something is telling me that when you are calling the ListSelectionListener you are not using getIsValueAdjusting() of the ListSelectionEvent, right? Therefore, this might be as well it, for more read here.
As far as I can see, you aren't clearing the list before populate it, you could try to clear the model first, like:
String sqlQuery3 = "SELECT Name FROM guestcontact WHERE GuestListID = '" + GuestListID + "'";
try {
rs3 = db.readRequest(sqlQuery3);
DefaultListModel lm = (DefaultListModel)l;
lm.clear();
while(rs3.next()){
(lm.getModel()).addElement(rs3.getString("Name"));
}
} catch (SQLException e) {
e.printStackTrace();
}