A java point of sale system that connects to a mysql database - java

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.

Related

How to Count all row in the table using java and mysql

I want to Count all the rows in the table using java and display the count of all the rows in the textfield. I need the count of employee from the table. I have attached below the code and the query used to achieve this. I received the error of the below code Column 'id' not found. error displayed
public void Customer()
{
try {
pst = con.prepareStatement("SELECT COUNT(*) FROM customer");
ResultSet rs = pst.executeQuery();
while(rs.next())
{
String id1 = rs.getString("id");
txtmsg.setText(id1);
}
} catch (SQLException ex) {
Logger.getLogger(gsm.class.getName()).log(Level.SEVERE, null, ex);
}
}
There clearly is no "id" column in your select. You could either get the result by column number like so:
int count = rs.getInt(1);
Or you could use an alias for the column and get result by that name, eg.:
pst = con.prepareStatement("SELECT COUNT(*) AS customerCount FROM customer");
int count = rs.getInt("customerCount");

Getting "An error occurred while converting the nvarchar value to JDBC data type DOUBLE."

I'm trying to run the method getAllCoupons() which reads the coupons table and sends it back to an angular service, but i get this message
An error occurred while converting the nvarchar value to JDBC data type DOUBLE.
I dont see any field that is wrong.
I initally thought that the date is the problem so i made it a comment, but i still get a problem
My DBDAO code:
public ArrayList<Coupon> getAllCoupon() throws CouponException {
ArrayList<Coupon> coupons = new ArrayList<>();
Connection con = pool.getConnection();
try {
PreparedStatement st = con.prepareStatement("select * from coupons");
ResultSet rs = st.executeQuery();
while (rs.next()) {
long id = rs.getLong(1);
String title = rs.getString(2);
String message = rs.getString(3);
String image = rs.getString(4);
// Date startDate = rs.getDate(5);
// Date endDate = rs.getDate(6);
int amount = rs.getInt(5);
double price = rs.getDouble(6);
Coupontypes type = Coupontypes.valueOf(rs.getString(7));
coupons.add(new Coupon(id, title, message, image, amount, price, type));
}
return coupons;
} catch (SQLException e) {
throw new CouponException(e.getMessage());
} finally {
pool.returnConnection(con);
}
}
My table:
CouponID bigint
Title nvarchar(50)
StartDate date
EndDate date
Amount int
Type nvarchar(50)
Message nvarchar(MAX)
Price float Unchecked
Image nvarchar(50)
I expect to get a coupon object back so i can display it on an angular website with *ngFor
Your trying java.lang.String to cast to java.lang.Double. If you are storing double as a String, then you can do double price = new Double(rs.getString(6)). Make sure your column won't be null and it will always return double value to avoid exception.

MySQL DATA Truncation Error occuring from Java GUI application but not directly on MySQL

Using a java program, am trying to update 3 colums in a table (the same table) on click of a button but when i try, to run it, it generates an error.
This is the error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'javax.swing.jTextField[,20,34,14x29,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,borde'
And heres my code
private void SaveBTNActionPerformed(java.awt.event.ActionEvent evt) {
// method for treating patient
try{
String sql = "UPDATE `iClinic`.`Treatment` SET `ProblemDesc` = ?,`Comments` = ?,`RescheduleDate` = ? WHERE `Treatment`.`RegID` ='"+PRegIDTF+"'";
pst=conn.prepareStatement(sql);
pst.setString(1, descriptionTA.getText());
pst.setString(2, CommentsTF.getText());
String value = ScheduleDateDT.getDate().toString();
pst.setString(3, value);
pst.execute();
JOptionPane.showMessageDialog(null, "saved");
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
The mistake/ problem was that in the SQL statement, i had only included the name of the jtextfield withoud including the command or method to fetch d result o value in that jtextfield. so the solution/ correction would be as below;
String sql = "UPDATE iClinic.Treatment SET ProblemDesc = ?,Comments = ?,RescheduleDate = ? WHERE Treatment.RegID = '"+PRegIDTF.getText()+"'";

How to get integer value from JTextField of Swing?

How to get integer value from JTextField of Swing as we get string value via getText() method?
try {
String sql = "insert into employeeinfo (username,password,obtainmark) values(?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txt_username.getText());
pst.setString(2, txt_password.getText());
pst.setInt(3, txt_obtainmark.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "data inserted");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
I am not able to insert integer data type value from the JTextField, but able to insert only string or varchar type data.
You can do Integer.parseInt(string) to get Integer value.
pst.setInt(Interger.parseInt(txt_obtainmark.getText()));

Retrieving the maximum value from an Integer column in an Access table

I have a textfield in a NetBeans frameform. I added a "Generate" button, and when I click it the program should find the largest value from the column "book_code" in a table named "books" and should display "generated value+1" in the textfield.
I use a class method to connect to my database so you won't find any code for connecting the database.
I have tried some coding but I am not able to generate the maximum value from book_code column of table books. Here is what I did:
String b_code="select max(Book_code) from books";
try
{
pst = conn.prepareStatement(b_code);
rs=pst.executeQuery();
int a=rs.getInt(b_code);
System.out.println("Book code is "+a);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null , e);
}
The maximum value in book_code column is 103, and when I click the "generate" button I would like to see 104 in the textfield.
There are at least two (2) issues with your code:
You create your ResultSet but you don't call rs.next() before you try to retrieve the value.
When you do try to retrieve the value you use the variable that contains the SQL string, and there is no column in the ResultSet that matches
This should work better:
String b_code="select max(Book_code) from books";
try {
pst = conn.prepareStatement(b_code);
rs = pst.executeQuery();
rs.next();
int a = rs.getInt(1);
System.out.println(String.format("max(Book_code) is %d", a));
} catch(Exception e) {
JOptionPane.showMessageDialog(null , e);
}

Categories

Resources