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.
Related
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);
Currently making a java program that grabs data off of a MSAccess Database and some of these errors are extremely frustrating. I keep getting this SQL.Exception : Too few parameters. Expected 1 error on the last remaining bugs in this program.
Little background on the db: It has 3 tables (A player table (11 columns), a team table (3 columns), and an Opponent table (6 columns).
These are both of the functions and I am fairly certain the problem lies in here somewhere
conn = Connect.ConnectDB();
String sql = "insert into Player ("+"PlayerLastName,"+"PlayerFirstName,"+"Position)"+ "values("+txtid.getText()+ ",'"+txtname.getText()+"','"+txtaddress.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.executeQuery();
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
or this function
String sql = "select * from Player where PlayerLastName = " +txtid.getText()+ "";
String pine = null;
try{
pst = conn.prepareStatement(sql);
ResultSet res;
res = pst.executeQuery();
pine.equalsIgnoreCase(jTable1.getModel().getValueAt(rowsu, 10).toString());
while(res.next()){
JOptionPane.showMessageDialog(null, txtname + " " + txtid.getText() + " has a total of " +"4");//+ pine);//res.getInt("Penalties") );
}
UpdateJTable();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
For one thing, it looks like you're missing single quotes around the last name in the insert statement.
There may be other errors as well, that's just the first thing I noticed.
This should be pretty easy to debug if you just log the sql string before executing it.
EDIT
I think your calls to setString() are also a problem. Here is how you should do this:
conn = Connect.ConnectDB();
String sql = "insert into Player (PlayerLastName, PlayerFirstName, Position) values(?, ?, ?)";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
pst.execute();
JOptionPane.showMessageDialog(null, txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
whenever i try to insert, delete and update i get the following syntax error. but after I close the exception jdialog and restart the application the data is either inserted, update and deleted
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your mariaDB server for the right syntax to use near 'Customer' at line 1
Insert query
try {
String sql = "Insert into Customer(ID , FirstName, MiddleName, LastName, DOB, Gander, Address, City, PostCode) "
+ "values (?, AES_ENCRYPT(?, 'uk112'),AES_ENCRYPT(?, 'uk112'),"
+ "AES_ENCRYPT(?, 'uk112'),?,AES_ENCRYPT(?, 'uk112'),"
+ "AES_ENCRYPT(?, 'uk112'),AES_ENCRYPT(?, 'uk112'),"
+ "AES_ENCRYPT(?, 'uk112'))";
pst = newconn.prepareStatement(sql);
pst.setString(1, jTextFieldID.getText());
pst.setString(2, jTextFieldFirstname.getText());
pst.setString(3, jTextFieldMiddlename.getText());
pst.setString(4, jTextFieldLastname.getText());
pst.setString(5, ((JTextField)txt_Date.getDateEditor().getUiComponent()).getText());
pst.setString(6, Gander);
pst.setString(7, jTextFieldAddress.getText());
pst.setString(8, jTextFieldCity.getText());
pst.setString(9, jTextFieldPostcode.getText());
pst.execute();
newconn.close();
JOptionPane.showMessageDialog(null, "Saved");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Update query
try{
String value1 = jTextFieldID.getText();
String value2 = jTextFieldFirstname.getText();
String value3 = jTextFieldMiddlename.getText();
String value4 = jTextFieldLastname.getText();
String value5 = ((JTextField)txt_Date.getDateEditor().getUiComponent()).getText();
String value6= Gander.toString();
String value7= jTextFieldAddress.getText();
String value8 = jTextFieldCity.getText();
String value9 = jTextFieldPostcode.getText();
String sql = "update Customer set FirstName= AES_ENCRYPT(?,'uk112'),"
+ "MiddleName= AES_ENCRYPT(?,'uk112'),"
+ "LastName= AES_ENCRYPT(?,'uk112'),"
+ "DOB=?,Gander= AES_ENCRYPT(?,'uk112'),"
+ "Address= AES_ENCRYPT(?,'uk112'),"
+ "City= AES_ENCRYPT(?,'uk112'),"
+ "PostCode= AES_ENCRYPT(?,'uk112') where ID=?";
pst = newconn.prepareStatement(sql);
pst.setString(1, value2);
pst.setString(2, value3);
pst.setString(3, value4);
pst.setString(4, value5);
pst.setString(5, value6);
pst.setString(6, value7);
pst.setString(7, value8);
pst.setString(8, value9);
pst.setString(9, value1);
pst.execute();
newconn.close();
JOptionPane.showMessageDialog(null, "Data is updated");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
Delete query
String sql = "delete from Customer Where ID =?";
try{
pst= newconn.prepareStatement(sql);
pst.setString(1, jTextFieldID.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
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