So i have this jTable on my frame and a jComboBox. Inside my jComboBox is the list of phones. What i want to do is to have the jTable get the database of a specific product inside the jComboBox. Suppose i pick the Samsung S7 in the jComboBox. When i click the "Details" jButton the jTable will show the Data of Samsung S7(Model, Price, Stock, etc.). How do i do this? Here is my code:
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/projectephone","root","");
String sql= "select * from samsung";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs= pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Failed to add");
}
}
But this code just make my jTable show all of my data inside my database table. Any ideas?
When the details button is clicked
get the current selected phone from the JComboBox (given as phone name or internal id into your database table or whatever)
and then use this value to limit your search.
For example
String phoneName = ... // current selected in the the combobox
String sql= "select * from samsung where name = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, phoneName);
ResultSet rs= pst.executeQuery();
Related
I have a problem with JComboBox. It's blocking another field in a frame meant to display another value that is linked through a foreign key in a database, a value that depends on the combo box already pop out. But somehow, after the user clicks the combo box it is blocking another field. The app is using MySql.
Here's the code:
ComboBox method to fill value from DB
public void comboBoxBerat(){
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
try {
sql = "SELECT * FROM weight_of_services";
rs = stat.executeQuery(sql);
while (rs.next()) {
jComboBoxBerat.addItem(rs.getString("weight"));
}
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Action when selection is made from combo box, its get the value that linked with foreign key
private void jComboBoxBeratActionPerformed(java.awt.event.ActionEvent evt) {
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
String item = (String)jComboBoxBerat.getSelectedItem();
String sql = "SELECT price FROM weight_of_services WHERE weight = ?";
try {
pst = con.prepareStatement(sql);
pst.setString(1, item);
rs = pst.executeQuery();
if (rs.next()) {
String price = rs.getString("price");
txtHargaBerat.setText(price); //put value from combobox to txtField
}
con.close();
} catch (Exception e) {
}
}
The problem after I select from the box its blocking another field.
This is the combo box problem in the frame
It's solved. This because i am using jpanel for customizing color for the frame. Its just so messed up with the stacking one panel on top of the other one. That's why my dropdown list get blocked. So what I did, removed all the panel. Custom and sorting it more carefully and tidy from the start.
I am facing a problem while completing my project.
I have created a JFrame with 2 JPanels. The first panel is the login panel, after the user enters his ID and password, he will be directed to the second panel to view his information (ID, Name, Medical Situation) which are saved in the databased connected to my Eclipse project.
The "Login" button already has a query using actionPerformed to verify if the password and ID are correct (if they exist in the database), so the user can login successfully.
What I want to do now is to create another query, to fetch (getText) ID, Name and Medical Situation from the database, depending on the ID the user will enter in JTextField = idTXT when he login, and setText in these JLabels: IDdraw_LBL, namedraw_LBL, msdraw_LBL in the second JPanel
Please check my code below:
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
//setting visibility of panels
patient_frame.setVisible(true);
patient_login.setVisible(false);
patient_appointments.setVisible(false);
//connecting to database
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/clinic", "root", "newpass");
//verifying ID and password code
String query="select * from patients where P_ID=? and Password=?";
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1, idTXT.getText());
pst.setString(2, passwordField.getText());
ResultSet rs=pst.executeQuery();
int count =0;
while(rs.next()){
count=count+1;
}
if (count ==1){
JOptionPane.showMessageDialog(null, "Welcome!");
}
else{
JOptionPane.showMessageDialog(null, "Incorrect username or password.");
}
rs.close();
pst.close();
I tried to write another query to retrieve the information from database but it doesn't work:
idTXT.getText();
String query1="select * from patients where P_ID=?";
PreparedStatement pst1=con.prepareStatement(query1);
ResultSet rs1=pst1.executeQuery();
while (rs1.next()){
IDdraw_LBL.setText(rs.getString("P_ID"));
namedraw_LBL.setText(rs.getString("Name"));
msdraw_LBL.setText(rs.getString("Medical_Situation"));
}
pst1.close();
}catch(Exception exx) {
JOptionPane.showMessageDialog(null, e);
}
}
}
It gives me this long-window error when running the program
Any help will be appreciated, Thanks in advance!
You're missing a parameter to your query:
String query1="select * from patients where P_ID=?";
PreparedStatement pst1=con.prepareStatement(query1);
ResultSet rs1=pst1.executeQuery();
You've defined an input parameter (?), but you're not assigning it before executing the query.
For example:
pst1.setInt(1, MY_ID);
ResultSet rs1=pst1.executeQuery();
I figured out that i didn't write the ResultSet parameter correctly in the while loop. It is rs1 not rs:
IDdraw_LBL.setText(rs1.getString("P_ID"));
Thank you !!
i have the following jframe :
and i wanna make the buttons work im still new to programming can someone help me please? i want the add row btn to add a new row to database, the update btn let me save changes and delete delete the selected row, also the jTextBoxes are connected to the database
i tried doing this to update :
Connection conn=null;
PreparedStatement pst = null;
try{
String value1=txt_cid.getText();
String value2=txt_carid.getText();
String value3=txt_aid.getText();
String value4=txt_rd.getText();
String value5=txt_bd.getText();
String value6=txt_bn.getText();
String sql="update booking set customer_id'"+value1+"',car_id'"+value2+"',agency_id'"+value3+"',return_date'"+value4+"',booking_date'"+value5+"',booking_number'"+value6+"',";
pst=conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "table updated");
}catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
but it didnt work out for me i get exception error
You haven't stated what the error is but UPDATE takes an equals operator for every parameter. Also use PreparedStatement placeholders to avoid SQL Injection attacks:
String sql = "update booking set customer_id=?, car_id=?,agency_id=?,return_date=?,booking_date=?,booking_number=?";
pst = conn.prepareStatement(sql);
pst.setInt(1, value1);
pst.setInt(2, value2);
... // set the other parameters
Read: UPDATE Syntax
I have write program that program have 2 frame one frame to add item and save to database
in another frame I have to select the item which is add in first frame in JComboBox I write that code for insert data into database but I don't know how to display in JComboBox
try {
String host = "jdbc:derby://localhost:1527/PROCAT";
String uName = "zain";
String uPass = "zain";
con = DriverManager.getConnection(host, uName, uPass);
String m = "insert into ITEMB (ITEM,ITEMNAME,PRISE) values(?,?,?)";
ps = con.prepareStatement(m);
ps.setInt(1, Integer.parseInt(jTextField3.getText()));
ps.setString(2, jTextField2.getText());
ps.setString(3, jTextField4.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "record saved");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
This for JComboBox:
try
{
String host = "jdbc:derby://localhost:1527/PROCAT";
String uName = "zain";
String uPass = "zain";
con = DriverManager.getConnection(host,uName,uPass);
st = con.createStatement();
rs = st.executeQuery("select ITEMNAME from ITEMB;");
while (rs.next()) {
jCom.addItem(rs.getString("ITEMNAME"));
}
}
catch(Exception ex) {
JOptionPane.showMessageDialog(null,ex);
}
On my understanding, there are 2 frames. One of them is for viewing records and has the JComboBox, the other one is for inserting records and has the JTextField.
The default frame would be the one with the JComboBox. If you want to add a new record into the JComboBox, a frame will appear for adding of records.
Once the INSERT statements are issued, the frame with the JTextField will be closed and the frame with the JComboBox will appear showing the newly added records.
You can provide a Reload button for deleting the items inside the JComboBox and then reloading the data using the SELECT statement.
while (rs.next()) {
jComboBox.addItem(rs.getString("ITEMNAME"));
}
And then, use
jComboBox.repaint();
I am try to run the code below but every time I run it, it don't work. Could any one please highlight what i am doing wrong?
What the code should do is:
I have to table in the database called r and another called sa, table r contain column said as a foreign key. in my java front end i have a Jtable in a jpanel and an update button in another jpanel. when the user select a row in the jtable and then click update. the tool will display data from r in text boxes as well as data from sa if the selected row in the jtable r have sa id as a foreign key.
the Code
if(updateClicked == true){
btnSubmit.setVisible(false);
btnUpdate.setVisible(true);
btnNew.setEnabled(false);
Statement st;
PreparedStatement ps;
ResultSet rs;
try {
String rid = table.getValue(0);
JOptionPane.showMessageDialog(null, rid);
String rq ="SELECT * FROM `r` WHERE 'r_id`=' "+rid+"'";
ps = Login.con.prepareStatement(rq);
rs = ps.executeQuery();
String saID = rs.getString(2);
String q = "SELECT sa.Argument FROM sa, r WHERE r.sid ="+sID ;
st = Login.con.createStatement();
rs = st.executeQuery(q);
String argu = rs.getString(1);
System.out.println(argu);
if (argu.isEmpty()==false){
btnAddSA.doClick();
txtaArg.setText(argu);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the Console output
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'R0004' in 'where clause'
First of all give your tables proper names. "r" and "sa" don't mean anything.
I don't know what the problem with your SQL is but I will suggest that you use a PreparedStatement. It makes it easier to code the SQL so you don't worry about delimiter type mistakes.
A basic example would be:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, "Name1" );
stmt.setString( 2, "Title1" );
stmt.executeUpdate();
You can search the forum or web for more information.