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.
Related
I have a music database so I'll need a search function, now when entering into the search bar, I get the error : "Invalid argument in JDBC call: parameter index out of range: 1"
public static Song getSongByName(String name)
{
String sql =
"SELECT songID FROM Song "+
"WHERE name = '?'; ";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt (1);
name = rs.getString (2);
erg = new SongImpl(id,name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
It seems like you are selecting just one column instead of two.
The correct SQL query would be:
SELECT songID, songName FROM Song WHERE name = '?';
Try this:
public static Song getSongByName(String name)
{
String sql =
"SELECT songID, songName FROM Song "+
"WHERE name = ?";
Connection conn = Connections.getConnection();
Song erg = null;
try
{
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
rs.next();
int id = rs.getInt(1);
String name = rs.getString(2);
erg = new SongImpl(id, name);
rs.close();
pstmt.close();
}
catch(SQLException exc)
{
System.err.println("Fehler: in SQL-Aufruf");
System.err.println("["+sql+"]");
exc.printStackTrace();
System.exit(6);
}
Connections.putConnection(conn);
return erg;
}
Let me know if that helped :)
Look onto examples https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Try to remove single quotes:
String sql =
"SELECT songID FROM Song "+
"WHERE name = ?; ";
You should use string parameters without quotes because your statement interpreted as a SQL query without parameters.
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.
Hi I am new here and I need some help in populating other jcomboboxes. All I wanted is that if I will select Last name from the first combobox, the other combobox will be populated by First names of patients/persons that has same Lastnames same as the Middlename. I hope you can help me
here's the pic:sample
As of now this is the code that I got to get values from database and put it on the first jcombobox:
public void lastname(){
try{
Connection con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost/javaclinic", "root","");
String sql1 = "select * from patient";
PreparedStatement pst1 = con.prepareStatement(sql1);
ResultSet rs1 = pst1.executeQuery();
while(rs1.next()){
lastn.addItem(rs1.getString("PLastname"));
}
}
catch(SQLException e){
}
}
Modify the sql to search database , if user enter any value like:
String sql1 = "SELECT * FROM patient";
if(lastName.equals(""))
{
sql1 +=" WHERE PLastName = '" + lastName + "'";
}
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
I have the following sql tables:
Authors:
Id Name
2 John Smith
Books:
Id AuthorID Title
1 2 Shreak
I am trying to add more books to the books table through a GUI which has a drop down box to display the authors from the authors table and a textbox for entry of new book and a save button. The followiing is that correspond to the save button:
pprivate void save_bookActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "INSERT into books (AuthorId,Title) VALUES (?,?)";
pst = con.prepareStatement(sql);
pst.setInt(1, author_name_combo.getSelectedItem());
pst.setString(2, book_name.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "New Book has been added");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void FillCombo(){
try {
con = DriverManager.getConnection(url, user, password);
String sql = "SELECT * FROM Authors";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
String author = rs.getString("Name");
author_name_combo.addItem(author);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
I am a beginner and im struggling to populate the table with new data. the progamme compiles but the books table display NULL for Both AUTHOR ID and TITLE. how do I populate the table correctly so that author Id is automatically looked up from Authors table and given the approprate id number from there. please note author id is foreign key in books table.
Assuming you're working with Swing (i.e. JComboBox and JTextField).
You are not assigning the values to the ? variables correctly. First, AuthorID is an integer and you need to assign the ID of the author, not the selected text.
One way to go around it is to create your own simple class to hold ID and name of an author, with the corresponding toString() method:
class OneAuthor extends AbstractMap.SimpleEntry<Integer, String> {
public OneAuthor(Integer id, String name) {
super(id, name);
}
public String toString() {
return getValue();
}
}
Then, when you're populating your JComboBox with authors' names, use this class instead of String:
ResultSet rs = con.createStatement().executeQuery("SELECT id, name FROM authors ORDER BY name");
while(rs.next()) {
author_names_combo.addItem(new OneAuthor(rs.getInt(1), rs.getString(2));
}
And then you can easily specify the correct author's ID:
pst.setInt(1, ((OneAuthor)author_name_combo.getSelectedItem()).getKey());
Second, instead of using getSelectedText(), you need to use getText() method on the book title text field. getSelectedText() will only return the text highlighted in the field, while getText() will return the whole text. Thus, your full code will be something like this:
pst = con.prepareStatement(sql);
pst.setInt(1, ((OneAuthor)author_name_combo.getSelectedItem()).getKey());
pst.setString(2, book_name.getText());
If your AuthorID is of type INTEGER in your database then the problem is you are inserting String value for it in this statement pst.setString(1, author_name_combo.getName());