how can I get the value of an list?
This are my two lists and after selecting these two values from the list(as marked) I want to insert these two elements(strings) into my database at this postition in my code:
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, txtFieldName.getText());
pst.setString(2, txtFieldNumber.getText());
// pst.setString(3, listDay.);
And at the last position I want to select the value which the user selects in the UI two list :
JButton btnNewButton_2 = new JButton("Speichern");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.sql.Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/dblabor","root","");
String query = "INSERT INTO Teach(Prof,Laborname,Room,Day,Time) VALUES(?,?,?,?,?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, txtFieldName.getText());
pst.setString(2, txtFieldLaborname.getText());
pst.setInt(3, Integer.parseInt(txtFieldRoom.getText()));
pst.setString(4, (String) listDay.getSelectedValue());
pst.setString(5, (String) listTime.getSelectedValue());
pst.execute();
pst.close();
JOptionPane.showMessageDialog(null, "Succssesfull");
}
catch(Exception e1) {
JOptionPane.showMessageDialog(null, "Wrong");
}
`
Thank you all in advance.
how can I get the value of an list?
You have been told to simply use:
Object value = list.getSelectedValue();
System.out.println(value);
Did you display the value?
Have you read the tutorial on JDBC Database Access?
I believe you need to use executeUpate() method of the PreparedStatement to change the data.
If you are using Swing, try method javax.swing.JList#getSelectedValue to get value from JList object.
Related
I'm Trying to get Information from a database to fill a Jcombobox, I'm trying to use the following codes but they are not working, in all of them the combo box is not being cleaned when.
Fisrt Attempt
try {
con = Connectionz.getConnection();//Connection Object
pst = con.prepareStatement("SELECT * AS achooserfill FROM Login_Users WHERE [C Team Lead] =?");
pst.setString(1, va);
rs = pst.executeQuery();
while (rs.next()) {
achooser.removeAll();
achooser.addItem("Please select agent");
achooser.addItem(rs.getString("achooserfill"));
}
}catch(Exception e){
System.err.println(e);
}
Second Attempt
try {
con = Connectionz.getConnection();//Connection Object
pst = con.prepareStatement("SELECT * FROM Login_Users WHERE [C Team Lead] =?");
pst.setString(1, va);
rs = pst.executeQuery();
while (rs.next()) {
achooser.removeAll();
achooser.addItem("Please select agent");
achooser.addItem(rs.getString("[VA #]"));
}
}catch(Exception e){
System.err.println(e);
}
Third Attempt
try {
con = Connectionz.getConnection();//Connection Object
pst = con.prepareStatement("SELECT [VA #] FROM Login_Users WHERE [C Team Lead] =?");
pst.setString(1, va);
rs = pst.executeQuery();
while (rs.next()) {
achooser.removeAll();
achooser.addItem("Please select agent");
achooser.addItem(rs.getString("[VA #]"));
}
}catch(Exception e){
System.err.println(e);
}
In all of the cases the result is the same,
I Would really appreciate any kind of info or any resource to fix the situation
in all of them the combo box is not being cleaned.
achooser.removeAll();
The removeAll() method is a method of the Container, not the combo box.
You want:
achooser.removeAllItems();
to remove the items from the combo box.
And that statement should be outside of the loop.
Also, for something like this did you even verify that your ResultSet contains data. First you should just hardcode the data to prove that the addItem() method works. Then once you know that logic is working you make the code more dynamic by getting the data from the database.
I like #camickr's comment, so am revising my answer. Try populating the model from the resultset, then declaring the JComboBox:
MutableComboBoxModel model = new DefaultComboBoxModel();
while (rs.next()){
model.addItem(rs.getString("achooserfill"));
}
JComboBox achooser = new JComboBox(model);
I have two JComboboxes A and B, so if I select any item form A then values related to the item selected in A should fill in JCombobox B. I tried this but get an error:
java.lang.ArrayIndexOutOfBoundsException: 0
at pst.setString(1, client.getSelectedItem().toString());
try
{
String query="select `User_Name` from Client where `Client_Name`='?' ";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, client.getSelectedItem().toString());
ResultSet rs=pst.executeQuery();
user.addItem("--Select--");
while(rs.next())
{
user.addItem(rs.getString("User_Name"));
}
// return;
System.out.println(query);
}
catch(Exception g)
{
g.printStackTrace();
}
The PresparedStatement takes care of quoting the parameter, when you use setString()
Try
String query="select User_Name from Client where Client_Name = ?";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, String.valueOf(client.getSelectedItem()));
I guess that when you use '?' the prepared statement does not count this as parameter and this is why you get the IndexOutOfBounce
you have done a mistake ,
no need to use '?' , it should be just Client_Name=?
I created a form to insert drug information to the db.
Only ItemID, ItemName and Expiry date is required.
User can add other details if want.
My code for above functionality;
private void Save_btnActionPerformed(java.awt.event.ActionEvent evt) {
try {
String id = itemid_txt.getText();
String name = itemname_txt.getText();
String rec=reclevel_txt.getText();
String qty=qty_txt.getText();
String wp =wprice_txt.getText();
String sp =sprice_txt.getText();
Date expp =expday_chooser.getDate();
String dess = des_txtarea.getText();
String date = ((JTextField)dayChooser.getDateEditor().getUiComponent()).getText();
String exp = ((JTextField)expday_chooser.getDateEditor().getUiComponent()).getText();
String des = des_txtarea.getText();
if(id==null && name==null && exp==null){
JOptionPane.showMessageDialog(null, "Fill required fields(Item ID ,Item Name ,Exp Date) and Try again...");
}else if(wp!=null && sp!=null && rec!=null && qty!=null && exp==null){
String sql = "Insert into druginfo (ItemID,ItemName,AddedDate,RecorderLevel,InStock,WSPrice,CostPrice,ExpDate,Description)values (?,?,?,?,?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, id);
pst.setString(2, name);
pst.setString(3, date);
pst.setString(4, dess);
pst.setString(5, qty);
pst.setString(6, wp);
pst.setString(7, sp);
pst.setString(8, exp);
pst.setString(9, des);
}else{
pst.setString(1, id);
pst.setString(2, name);
pst.setString(3, date);
pst.setString(4, null);
pst.setString(5, null);
pst.setString(6, null);
pst.setString(7, null);
pst.setString(8, null);
pst.setString(9, des);
}
pst.execute();
JOptionPane.showMessageDialog(null, "New Item Data Saved...");
itemid_txt.setText(null);
itemname_txt.setText(null);
reclevel_txt.setText(null);
qty_txt.setText(null);
wprice_txt.setText(null);
sprice_txt.setText(null);
expday_chooser.setDate(null);
des_txtarea.setText(null);
} catch (SQLException ex) {
Logger.getLogger(InventoryManagementenew.class.getName()).log(Level.SEVERE, null, ex);
}
}
But not adding to the database when only required fields given and all fields are are given. Code throws java.lang.NullPointerException .
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.bit.project.InventoryManagementenew.Save_btnActionPerformed(InventoryManagementenew.java:468)
at com.bit.project.InventoryManagementenew.access$500(InventoryManagementenew.java:27)
at com.bit.project.InventoryManagementenew$6.actionPerformed(InventoryManagementenew.java:366)
line 468 is pst.setString(1, id);.
Help me to correct this.
You only initialize the PreparedStatement in the else if clause. The else part has neither the sql string nor the prepared statement.
State pst=conn.prepareStatement(sql); before your if-else conditions currently it will only be initialized in first else if part otherwise pst will be null in subsequent else-if and else block.
Your preparedStatement object is referring to null as it is only initialized in if block of if-else-if construct.
To solve the problem either initialize the preparedStatement outside if-else-if block or initialize it in each block if, elseif and else.
One thing more you are not closing preparedStatement in your code this could lead to memory leak and will cause out of memory or too many connections to DB at higher rate of transactions in future.
Below is my code of a jFrame btn_update:
private void txt_updateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String Value1=txt_Emp_ID.getText();
String Value2=txt_Name.getText();
String Value3=txt_Surname.getText();
String Value4=txt_age.getText();
String Value5=txt_Username.getText();
String Value6=txt_Password.getText();
String sql = "update employee set Emp_ID=?, name=?,surname=?,age=?,username=?,password=?";
pst.setString(1, Value1);
pst.setString(2, Value2);
pst.setString(3, Value1);
pst.setString(4, Value1);
pst.setString(5, Value1);
pst.setString(6, Value1);
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
JOptionPane.showMessageDialog(null, "Updated!!");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
and my configurations:
Connection conn=null;
ResultSet rs = null;
PreparedStatement pst = null;
when I try to press the update button I get this:
java.sql.SQLException:Parameter index out of Range (2>number of parameters, which is 1)
can someone help me?
A few issues
Your exception message indicates that the PreparedStatement only has 2 parameters. Assign the variable before setting the parameters
Copy/paste error where parameters 3-6 are all Value1 instead of Value3, Value4, etc.
executeQuery is used to query the database. Use executeUpdate for database write operations
Result:
preparesStatement = connection.prepareStatement(sql);
preparesStatement.setString(1, value1);
...// etc.
preparesStatement.setString(6, value6);
How can I insert records into two different table? I made two sql statement and it won't work.
private void cmdsubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
String sql = "Insert into customer (Customer_ID,First_Name,Last_Name,Birthdate,Gender,Occupation,Address,Email,Contact,Status,Income,Amount,Term,Interest,Date_Applied,Purpose,Other) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txtID.getText());
pst.setString(2, txtfname.getText());
pst.setString(3, txtlname.getText());
pst.setString(4,((JTextField)birthdate.getDateEditor().getUiComponent()).getText());
String gender = cmbgender.getSelectedItem().toString();
pst.setString(5, gender);
pst.setString(6, txtoccupation.getText());
pst.setString(7, txtaddress.getText());
pst.setString(8, txtemailadd.getText());
pst.setString(9, txtcontact.getText());
String status = cmbstatus.getSelectedItem().toString();
pst.setString(10, status);
String income = cmbincome.getSelectedItem().toString();
pst.setString(11,income);
pst.setString(12, txtamount.getText());
String period = cmbperiod.getSelectedItem().toString();
pst.setString(13, txtloan.getText() + " " + period);
pst.setString(14, txtinterest.getText());
pst.setString(15, ((JTextField)datechooser.getDateEditor().getUiComponent()).getText());
String purpose = cmbpurpose.getSelectedItem().toString();
pst.setString(16, purpose);
pst.setString(17, txtother.getText());
Double balance = Double.parseDouble(txtamount.getText()) * Double.parseDouble(txtinterest.getText());
String s = "Insert into payments (Customer_ID,Customer_Name,Amount,Interest,To_Pay) values (?,?,?,?,?)";
pst = conn.prepareStatement(s);
pst.setString(1, txtID.getText());
pst.setString(2, txtfname.getText()+","+txtlname.getText());
pst.setString(3, txtamount.getText());
pst.setString(4, txtinterest.getText());
pst.setString(5, balance.toString());
pst.execute();
JOptionPane.showMessageDialog(null, "Record Save");
Menu menu = new Menu();
this.setVisible(false);
menu.setVisible(true);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
The problem appears to be that you aren't calling pst.execute() before you call this line:
pst = conn.prepareStatement(s);
This is overwriting your previous pst variable; creating a new PreparedStatement.
I'm not entirely sure about that API, but it seems like you have one execute for two statements. Also, you should consider making a function if a good chunk of the code is exactly the same. Less places to maintain