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.
Related
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.
I want to insert primary key of selected item of combo box
but I got this error Parameter index out of range(12 > number of parameter which is 0)".
I really don't know how to fix this.
Here is my code:
String valueTrainer = "kosong";
try
{
String sql2 = "Insert into ahli (MemberID, TrainerID, Name, ICNumber, Address, Nationality,"
+ "PhoneNumber, Email, EmergencyPerson, EmergencyContact, DateReg, MemberTypeID) "
+ "values(?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sql2);
pst.setString(1, MemberIDTextField.getText());
pst.setString(2, valueTrainer);
pst.setString(3, NameTextField.getText());
pst.setString(4, jTextField1.getText());
pst.setString(5, AddressTextArea.getText());
//Nationality combo box
String nationalityList = NationalityComboBox.getSelectedItem().toString();
pst.setString(6, nationalityList);
pst.setString(7, PhoneNumberTextField.getText());
pst.setString(8, EmailTextField.getText());
pst.setString(9, EmerContactPersonTextField.getText());
pst.setString(10, EmerContactNumberTextField.getText());
//Date Chooser
pst.setString(11, ((JTextField)MemberDateChooser.getDateEditor().getUiComponent()).getText());
//membertype combobox
// problem start from here, I think..
String memberTypeList = MemberTypeComboBox.getSelectedItem().toString();
String sql1 ="Select MemberTypeID from jeniskeahlian where Type = '"+memberTypeList+"' " ;
pst = conn.prepareStatement(sql1);
rs = pst.executeQuery();
while(rs.next()){
String memberType = rs.getString("MemberTypeID");
pst.setString(12, memberType);
}
pst.execute();
JOptionPane.showMessageDialog(null, "New member has been added");
} catch (SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
You are not using pst properly.
same named reference on prepared statement can not be used on different sql statement unless one is used and closed properly. Prepare, set, execute, close on one statement, and then repeat the same on another statement.
Change your code as below.
try
{
String memberTypeList = MemberTypeComboBox.getSelectedItem().toString();
String sql1 ="Select MemberTypeID
from jeniskeahlian
where Type = ? " ;
pst = conn.prepareStatement(sql1);
pst.setString( 1, memberTypeList );
rs = pst.executeQuery();
String memberType = "";
while(rs.next()){
memberType = rs.getString("MemberTypeID");
}
rs.close();
pst.close();
String sql2 = "Insert into ahli (MemberID, TrainerID, Name,
ICNumber, Address, Nationality,
PhoneNumber, Email, EmergencyPerson,
EmergencyContact, DateReg, MemberTypeID)
values(?,?,?,?,?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(sql2);
pst.setString(1, MemberIDTextField.getText());
pst.setString(2, valueTrainer);
pst.setString(3, NameTextField.getText());
pst.setString(4, jTextField1.getText());
pst.setString(5, AddressTextArea.getText());
//Nationality combo box
String nationalityList = NationalityComboBox.getSelectedItem().toString();
pst.setString(6, nationalityList);
pst.setString(7, PhoneNumberTextField.getText());
pst.setString(8, EmailTextField.getText());
pst.setString(9, EmerContactPersonTextField.getText());
pst.setString(10, EmerContactNumberTextField.getText());
//Date Chooser
pst.setString(11, ((JTextField)MemberDateChooser
.getDateEditor()
.getUiComponent()).getText());
pst.setString(12, memberType);
pst.execute();
JOptionPane.showMessageDialog(null, "New member has been added");
} // try
While your insert statement seems properly populated, in the while-loop you rare trying to execute a select statement which has no parameters, so that pst.setString(12,memberType) fails.
String sql1 ="Select MemberTypeID from jeniskeahlian where Type = '"+memberTypeList+"' " ; //no ? in this query
Before you execute the query you should have set all the values for all the parameters.
i have this error . The index 2 is out of range. on pst.setString(2, textField.getText();
how can i deal with it.
this is my code
try{
String sql="update inventory set Name=?,Category=?,Brand=?,Price=?,ExDate=?,Tags=?,Quantity=?,Barcode=? where Id=?";
pst.setString(2, textField.getText());
pst.setString(3, textField_1.getText());
pst.setString(4, textField_2.getText());
pst.setString(5, textField_3.getText());
pst.setString(6, textField_4.getText());
pst.setString(7, textField_5.getText());
pst.setString(8, textField_9.getText());
pst.setString(9, textField_6.getText());
pst.setString(1, textField_8.getText());
pst=con.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Updating Item Successful","Updated",JOptionPane.PLAIN_MESSAGE);
new server().setVisible(true);
setVisible(false);
} catch(Exception e1){e1.printStackTrace();}
Based on the documentation, Couple of things to notice here.
your sql contains name att index 1. So when you try to update this column you should use the same index. something like this:
pst.setString(1, textField.getText());
You are always invoking setString methods. Although it looks like some of the columns might be of type int or else. for example your 'id' column should be set with this:
pst.setInt(9, Integer.parseInt(textField_8.getText())); (notice that I have changed the index as well.)
And as I mentioned in my comment earlier, you should move your pst=con.prepareStatement(sql) to the top. (right after your string declaration.)
A prepared statement should be created before being used to set the variables. As the commenter said you need to move the prepared statement creation before setting variables to it.
Refactor your code like this:
try{
String sql="update inventory set Name=?,Category=?,Brand=?,Price=?,ExDate=?,Tags=?,Quantity=?,Barcode=? where Id=?";
pst=con.prepareStatement(sql);
pst.setString(2, textField.getText());
pst.setString(3, textField_1.getText());
pst.setString(4, textField_2.getText());
pst.setString(5, textField_3.getText());
pst.setString(6, textField_4.getText());
pst.setString(7, textField_5.getText());
pst.setString(8, textField_9.getText());
pst.setString(9, textField_6.getText());
pst.setString(1, textField_8.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Updating Item Successful","Updated",JOptionPane.PLAIN_MESSAGE);
new server().setVisible(true);
setVisible(false);
}
catch(Exception e1)
{
e1.printStackTrace();
}
finally
{
pst.close();
}
this is my edited code...
java.sql.Timestamp sqlNow = new java.sql.Timestamp(new java.util.Date().getTime());
stmt = con.createStatement();
//stmt.executeUpdate("INSERT INTO cregn values('"+appno+"','"+usname+"','"+upwd +"','"+fname+"','"+mname+"','"+lname+"','"+dob+"','"+gend+"','"+faname+"','"+saddr+"','"+caddr+"','"+staddr +"','"+pin+"','"+cno+"','"+email+"','"+occ+"','"+secques+"','"+answer+"','Processing','"+sqlNow+"')");
pst = con.prepareStatement("INSERT INTO cregn (aplno, username, pwd, firstname,middlename,lastname, dob,gender, fathername, street,city,state, pincode, phone, email,occupation,secques,answer,dor) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pst.setInt(1, appno);
pst.setString(2, usname);
pst.setString(3, upwd);
pst.setString(4, fname);
pst.setString(5, mname);
pst.setString(6, lname);
pst.setString(7, dob);
pst.setString(8, gend);
pst.setString(9, faname);
pst.setString(10, saddr);
pst.setString(11, caddr);
pst.setString(12, staddr);
pst.setString(13, pin);
pst.setString(14, cno);
pst.setString(15, email);
pst.setString(16, occ);
// pst.setString(17,ph);
pst.setString(17, secques);
pst.setString(18, answer);
pst.setTimestamp(19, sqlNow);
pst.executeUpdate();
out.println("Registration Successful for application " + appno);
} catch (Exception ee) {
out.println("Invalid Data! All fields are mandatory..." + ee.getMessage());
}
%>
after executing this code error displayed "Invalid Data! All fields are mandatory..data truncation"
You are not executing the statement.
You need to call executeUpdate
You have to call execute or executeUpdate on pst in order to actually do the work. E.g., at the end:
pst.executeUpdate();
All that the code you've shown does is prepare the statement for execution, it doesn't execute it. This is one of the main differences between PreparedStatement and Statement. In Statement, you pass the SQL to execute directly into executeUpdate (as seen in your commented-out line using stmt). With a PreparedStatement, you supply the SQL with ? as you've done, set those parameters, and then call executeUpdate (or execute), which you haven't done.
There is no executeUpdate() being called on pst.
use pst.executeUpdate(); to execute the query and make sure that in transaction use setAutoCommit(true) has to be called.
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