The POS system does some form of calculation if you click "Pay". When the "Pay" button is pressed the numerical values in "pay" textfield is to be deducted from whatever value is in "subtotal" textfield then the balance is to be displayed in the "balance" textfield at the same time this data is to be inserted in a "Sales" table in their respective columns. The value in the "balance" textfield doesnt get inserted in its corresponding column even though the column "balance" in my database is of INT datatype of length 11.
Note: The funny thing is if i change the datatype of "balance" to be varchar it inserts data but it shows 0 instead of the actual value i want.
Below is my Sales method
The error is
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect integer value: '' for column 'balance' at row 1'] Image
private void sales(){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDateTime now = LocalDateTime.now();
String date = dtf.format(now);
String subT = subtotal_textfield.getText();
String payinKsh = pay_textfield.getText();
String bal = balance_textfield.getText();
int lastinsertID = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/supermarket", "root","");
String query = "insert into sales(date,subtotal,pay,balance)values(?,?,?,?)";
pst = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pst.setString(1, date);
pst.setString(2, subT);
pst.setString(3, payinKsh);
pst.setString(4, bal);
pst.executeUpdate();
ResultSet generatedKey = pst.getGeneratedKeys();
if (generatedKey.next()) {
lastinsertID = generatedKey.getInt(1);
}
JOptionPane.showMessageDialog(this, lastinsertID);
} catch (ClassNotFoundException ex) {
Logger.getLogger(POS.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(POS.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is happening because of datatype mismatch. What have to take them in similar/matching/same datatype to do your insertion. Either keep your balance column as INT as you mentioned and then convert your bal String value to int like this:
Integer.parseInt(bal);
So, change your
pst.setString(4, bal);
statement to this -->(edited)
try
{
pst.setInt(4, Integer.parseInt(bal));
} catch(Exception e)
{
pst.setInt(4, 0);
}
Or, change your balance column to varchar and insert bal as String value but first of all check what do you get in your bal variable.
I want retrieve the value picked from combo box to jtextfield. As per my UI combobox is in 4th. So I coded:
pst.setString(4, (String)cmbPaySub.getSelectedItem());
and the error pop-up:
Parameter index out of range.(4> number of parameters, which is 1".
I tried by coding;
pst.setString(1, (String)cmbPaySub.getSelectedItem());
Neither error will pop-up and value also not picking up.
private void cmbPaySubActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sipnena", "root", "");
String sql="select * from payments where cmbSubject=?";
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(4, (String)cmbPaySub.getSelectedItem());
ResultSet rs=pst.executeQuery();
while(rs.next()){
txtFee.setText(rs.getString("Fee"));
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Kindly help me to retrieve the value to the jtextfield.
When reading the result you're replacing the entire text by the result's value in a loop so only the last value will show:
while(rs.next()){
txtFee.setText(rs.getString("Fee"));
}
You should concatenate all the values, and then set the text:
StringBuilder text = new StringBuilder();
while(rs.next()){
text.append(rs.getString("Fee"));
text.append("\n");
}
txtFee.setText(text.toString());
I've created a sql database with a table called users. It holds the user_id, user_name and email. I've created a form that allows the user to search for any record and displays the filtered record on a JTable.
I want to delete the row the search result filters based on the searched value meaning the user can search either the user_id, user_name or email.
users {user_id, user_name, email}
This is what I have
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, searchTxt.getText());
pst.setString(2, searchTxt.getText());
((DefaultTableModel)userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
searchTxt is the text field.
This code deletes all the rows in my table.
If I change it to DELETE from user where user_id = ?, it only deletes the row when it is searched by user_id.
users {user_id, user_name, email}
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, searchTxt.getText());
pst.setString(2, searchTxt.getText());
((DefaultTableModel) userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
With that code you're always producing a complete deletion of the table because you always obtain a TRUE in your WHERE clause
If searchTxt.getText() is "hello", the prepared statement will be
DELETE from user where hello = hello
Which is equivalent to
DELETE from user where true
Or
DELETE from user
You just have to differentiate between searchTxt and columnName
private void deleteSelectedRows(){
try {
String sql = "DELETE from user where ? = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, columnName);
pst.setString(2, searchTxt.getText());
((DefaultTableModel) userTable.getModel()).removeRow(userTable.getSelectedRow());
pst.execute();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Actually i'm using oracle jdbc type4 thin driver. And I'm creating registration form in swing with eclipse with following columns pid,name,addrs.
the problem is i'm getting only string value which method is ps.setString=(2,JTextfiled.getText());
but i'm not able get int value like ps.setInt(1.getxxx());
can anyone guide me how to insert int value to database.
//prepare query
String query1 ="insert into employee values(?,?,?,?,?)";
//create preapare Statement
ps = con.prepareStatement(query1);
//set params
ps.setString(1,textField.getText());
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
ps.setString(4,textField_3.getText());
ps.setString(5, textField_4.getText());
//execute query
int count = ps.executeUpdate();
if(count==0)
{
JOptionPane.showMessageDialog(null, "Record not Inserted");
}
else
{
JOptionPane.showMessageDialog(null, "Record inserted into database successfuly");
}
Use Integer.parseInt to convert your string to an int, then use PreparedStatement#setInt to set it on the statement for insertion. E.g.:
ps.setInt(1, Integer.parseInt(textField.getText()));
You'll want to catch NumberFormatException in case the values in the text fields are not valid integers.
I'm making a java program using Netbeans, I want to insert data into my "data supplier" table. I cannot post my JFrame picture as my reputation is not enough.
I've set "Kode Supplier" as PRIMARY_KEY and NOT_NULL, and allow the rest to be NULL
In the code below, telpField and hpField will show an error if I didn't type anything in it's textbox
Is it possible because it is INT type?
This is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "INSERT INTO datasupplier (`Kode Supplier`, `Nama Supplier`, `Contact Person`,"
+ " `Alamat`, `NoTelp`, `NoHP`, `Bank Account`, `A/C Info`, `A.N.`, `Keterangan`)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pst = conn.prepareStatement(sql);
//Get value from the textboxes
pst.setString(1, codeField.getText());
pst.setString(2, nameField.getText());
pst.setString(3, cpField.getText());
pst.setString(4, addressField.getText());
pst.setString(5, telpField.getText());
pst.setString(6, hpField.getText());
pst.setString(7, bankField.getText());
pst.setString(8, acField.getText());
pst.setString(9,anField.getText());
pst.setString(10, ketField.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Tabel Telah Di Update");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Data Invalid");
}
DataSupplierTable();
}
//Set JComboBox First Diplayed Item
private void setTableCombo(){
tableCombo.setSelectedItem("Data Supplier");
}
//Bind the table and databarang.datasupplier
private void DataSupplierTable(){
String sql = "SELECT * FROM datasupplier";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
supplierTable.setModel(DbUtils.resultSetToTableModel(rs));
supplierTable.isCellEditable(0,0);
}catch(Exception e){
}
}
This is my table (using MySQL Community Server Database, InnoDB)
Kode Supplier INT(30) PRIMARY_KEY NOT_NULL,
Nama Supplier CHAR(45),
Contact Person VARCHAR(20),
Alamat VARCHAR(45),
NoTelp INT(30),
NoHP INT(30),
Bank Account CHAR(30),
A/C Info VARCHAR(45),
A.N. CHAR(45),
Keterangan VARCHAR(100)
Yes, this is because your Kode Supplier, NoTelp and NoHP columns are integer columns. For integer columns, you should be using the setInt method rather than setString.
But the setInt method only accepts an primitive int for the value of the field. So the first thing you'll need to do is convert the String value of the field to int. This is done with a statement like:
int telpVal = Integer.parseInt(telpField.getText());
But this means you have to decide what to do in the following cases:
The user entered a value in the GUI field which is not an integer, like ABC, 1.2 or 123456789123456789. If that happens, then the statement I gave would throw a NumberFormatException.
You could decide to display an error message and not call the insert statement when this happens. Or you may decide to insert a NULL. Or you may decide to insert a default value like 0.
The user entered no value in the GUI field - it is an empty string. Note that there is a difference between an empty string and a null. You may decide to handle this case the same way you handle the previous one. Or you may decide to handle it separately.
Suppose you decide that:
If the user entered an illegal number, you'll show an error message and will not insert the row.
If the user did not enter a value and left the field empty, you want to insert a null.
Then you'll need to handle it like this:
String fieldName;
try {
String sql = "INSERT INTO datasupplier (`Kode Supplier`, `Nama Supplier`, `Contact Person`,"
+ " `Alamat`, `NoTelp`, `NoHP`, `Bank Account`, `A/C Info`, `A.N.`, `Keterangan`)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pst = conn.prepareStatement(sql);
//Get value from the textboxes
// Kode supplier is integer, but is not allowed to be null
// so don't handle an empty field case, just let parseInt
// throw the exception.
fieldName = "Kode Supplier";
pst.setInt(1, Integer.parseInt(codeField.getText()));
pst.setString(2, nameField.getText());
pst.setString(3, cpField.getText());
pst.setString(4, addressField.getText());
// Handle the NoTelp field - if empty, insert null. If not,
// parse the number. Handle illegal number values in catch.
fieldName = "NoTelp";
if ( telpField.getText().isEmpty() ) {
pst.setNull(5, Types.INTEGER);
} else {
pst.setInt(5, Integer.parseInt(telpField.getText());
}
// Handle the NoHP field
fieldName = "NoHP";
if ( hpField.getText().isEmpty() ) {
pst.setNull(6, Types.INTEGER);
} else {
pst.setInt(6, Integer.parseInt(hpField.getText());
}
pst.setString(7, bankField.getText());
pst.setString(8, acField.getText());
pst.setString(9,anField.getText());
pst.setString(10, ketField.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Tabel Telah Di Update");
}
catch (NumberFormatException nfe) {
// Display error to the user
JOptionPane.showMessageDialog(null, "Invalid number in field " + fieldName)
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, "Data Invalid");
}
Notes
I handled Kode Supplier differently than NoTelp and NoHP because it is not allowed to be null. If the field is empty, NumberFormatException will be thrown from parseInt and will go to the catch part.
I kept a fieldName variable which I set before trying each parseInt. If an exception is thrown, we can use it for displaying the specific field where the error occurred in the dialog box. You can do other things like keeping the JTextField that you are currently handling, and in the catch highlighting it and giving it focus.
When you use setNull, you have to pass the type of the field as the second parameter. All the types are in java.sql.Types. So remember to import java.sql.Types.
Don't use a catch (Exception e). It's too broad. In this case we expect only NumberFormatException and SQLException. If any other exception happens, especially a runtime exception, you want to know about it and see the stack trace. If you have catch (Exception e) you'll just get a dialog box that says "Data Invalid" and that is not helpful. "Catch all" is bad.