Updating AuthorID From ComboBOX value - java

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());

Related

Autofill a textfield when clicking a value in jComboBox

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!

Recognize and Select Name in JComboBox with Space

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.

find a name in a sqlite table and return the id?

What I'm trying to do seems simple but I get this error SQLITE_ERROR] SQL error or missing database (no such column: user1)
public String getIdUser(String name) {
try {
this.stat = conn.createStatement();
String sql = "SELECT id_user FROM User WHERE name = " + name;
ResultSet user = stat.executeQuery(sql);
return user.toString();
} catch (SQLException e) {
return null;
}
}
Replace
String sql = "SELECT FROM User WHERE name = " + name;
with
String sql = "SELECT * FROM User WHERE name = " + name; // you can also specify a column/columns instead of *
I see many problems in your code :
First
Your query should return something it should be :
SELECT col_name1, col_name2, ... FROM User ...
Or if you want to select every thing :
SELECT * FROM User ...
Second
String or Varchar should be between two quotes, your query for example should look like :
SELECT col_name1 FROM User WHERE name = 'name'
Third
I don't advice to use concatenation of query instead use Prepared Statement it is more secure and more helpful (I will provide an example)
Forth
To get a result you have to move the cursor you have to call result.next()
Fifth
Name of variable should be significant for example ResultSet should be ResultSet rs not ResultSet user
Your final code can be :
PrepareStatement prst = conn.prepareStatement("SELECT colName FROM User WHERE name = ?");
prst.setString(1, name);
ResultSet rs = prst.executeQuery();
if(rs.next()){
reuturn rs.getString("colName");
}
Without quoting the name string it's interpreted as column name, and thus the error you see. You could surround it with single quotes, but that's still generally a bad practice, and will leave the code vulnerable to SQL injection attacks.
Additionally, you're missing the select list (specifically, the id_user column), and missing getting it from the result set.
And finally, you forgot to close the statement and the result set.
If you put all of these corrections together, you should use something like this:
public String getIdUser(String name) {
try (PreparedStatmet ps =
conn.prepareStatement("SELECT id_user FROM User WHERE name = ?")) {
ps.setString(1, name);
try (ResultSet rs = stat.executeQuery()) {
if (rs.next()) {
return rs.getString(1);
}
}
} catch (SQLException ignore) {
}
return null;
}

How to delete searched row from jtable and sql database based on searched value

I've created a sql database with a table called users. It holds the user_id, user_name and email. I've created a form that allows the user to search for any record and displays the filtered record on a JTable.
I want to delete the row the search result filters based on the searched value meaning the user can search either the user_id, user_name or email.
users {user_id, user_name, email}
This is what I have
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, searchTxt.getText());
pst.setString(2, searchTxt.getText());
((DefaultTableModel)userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
searchTxt is the text field.
This code deletes all the rows in my table.
If I change it to DELETE from user where user_id = ?, it only deletes the row when it is searched by user_id.
users {user_id, user_name, email}
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, searchTxt.getText());
pst.setString(2, searchTxt.getText());
((DefaultTableModel) userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
With that code you're always producing a complete deletion of the table because you always obtain a TRUE in your WHERE clause
If searchTxt.getText() is "hello", the prepared statement will be
DELETE from user where hello = hello
Which is equivalent to
DELETE from user where true
Or
DELETE from user
You just have to differentiate between searchTxt and columnName
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, columnName);
pst.setString(2, searchTxt.getText());
((DefaultTableModel) userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}

cardinality violation and NullPointerException while populating a combobox with available courses

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

Categories

Resources