jTable update button and add new - java

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

Related

Java - get the value of selected list item

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.

Error at MySQL server

I am getting the following error:
...check the syntax that corresponds to your MySQL server version for
the right syntax to use near "Item1" at line 1
Here is the relevant part of the code:
String e = e_id.getSelectedItem().toString();
String value1 = e;
String o = o_code.getSelectedItem().toString();
String value2 = o;
String value3 = o_credit.getText();
// String value4 = session.getText();
// String value5 = designation.getText();
// String value6 = phd_com_id.getText();
String sql = "update passes_optional set o_code='"+value2+"', o_credit='"+value3+"' where e_id='"+value1+"'";
pst = conn.prepareStatement(sql);
pst.execute();
e_id is a drop down list with the values "Item1", "Item2", "Item3", and "Item4". The table contains info on Item1.
That's because with prepareStatement you have to use PreparedStatements.
String sql="update passes_optional set o_code=?, o_credit=? where e_id=?";
PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1, value2);
pst.setString(2, value3);
pst.setString(3, value1);
pst.execute();
Oracle official Prepared Statements tutorial
UPDATE
As pointed out by JonK, you should also be using pst.executeUpdate() instead of pst.execute():
String sql="update passes_optional set o_code=?, o_credit=? where e_id=?";
PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1, value2);
pst.setString(2, value3);
pst.setString(3, value1);
pst.executeUpdate();

Using preparedstatement in Text datatypes

In PreparedStatement which method i need to use execute the class
I write a method like
public Text getMessage(){
return message;
}
In my class
PreparedStatement ps;
ps=con.prepareStatement("insert into tblmessage
(message) values(?)");
ps.setString(2, usermsgmodel.getMessage());
ps.executeUpdate();
i got an error in this line saying that "the method getMessage return type is Text, So you setString property cannot accommodate Text value "
ps.setString(1, usermsgmodel.getMessage());
Try following :
public Text getMessage(){
return "Hello"; // or whatever you want to return
}
Class :
PreparedStatement ps;
ps=con.prepareStatement("insert into tblmessage (message) values(?)");
ps.setString(1, usermsgmodel.getMessage());
ps.executeUpdate();
You are only inserting 1 column data in table so you have to use 1 not 2 in ps.setString(1,usermsgmodel.getMessage());
and one question is that where you are setting message ? I don't understand the return message line so I have used Hello.
Use this, it works fine.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hossain?useUnicode=true&characterEncoding=UTF8;","root","root");
PreparedStatement ps=con.prepareStatement("select * from UserTable where name=? and password=?");
ps.setString(1,username);
ps.setString(2,userpass);
ps.executeQuery();
}catch(Exception e){e.printStackTrace();}
Make it as
ps.setString(1, usermsgmodel.getMessage());

Error : Index parameter out of range

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.

How to insert the same record into two different table in java?

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

Categories