MySql Data truncated for column 'advance' at row 1 - java

In my project I used txtAdvance 's key event.
double gtotal = Double.parseDouble(txtGtotal.getText());
double ad = Double.parseDouble(txtAdvance.getText());
double due = gtotal - ad;
txtDue.setText(String.valueOf(due));
And after last line run, I add a save button to save those data. Given below is that query.
public void saveInvoice(JTextField txtgtotal, JTextField txtAdvance, JTextField txtDue, JTextField txtInID) {
try {
db.putData("INSERT INTO indetails(inid, gtotal, advance, due) VALUES( '" + txtInID.getText() + "' ,'" + txtgtotal.getText() + "' , '" + txtAdvance.getText() + " ' " + " , '" + txtDue.getText() + "') ");
JOptionPane.showMessageDialog(null, txtAdvance.getText());
JOptionPane.showMessageDialog(null, "Invoice details saved");
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, this.getClass().getName() + " first " + e);
}
}
I'm having MySql Data truncated for column 'advance' at row 1 . advance's data type is Double. But I can't find a way to put length.
(As an example
Column Name : iid, Data type : Int(18) {Primary key}
Column Name : inid, Data type : Int(18)
Column Name : gtotal, Data type : Double
Column Name : advance, Data type : Double
Column Name : due, Data type : Double
)
I'm using MySQL query browser . Question is when I'm adding 0 value to txtAdvance I'm having this error.

If the data you are trying to save have decimal points then change the datatype for advance as double with length 10,3 where 10 denotes number of digits and 3 denotes the number of decimal digits.
Use this query,
db.putData("INSERT INTO indetails(inid, gtotal, advance, due) VALUES(" + txtInID.getText() + "," + txtgtotal.getText() + "," + txtAdvance.getText() + "," + txtDue.getText()+")");

Instead of creating your query by hand, you should use db driver for it:
PreparedStatement putData = con.prepareStatement("INSERT INTO indetails(inid, gtotal, advance, due) VALUES(?,?,?,?)");
double gtotal = Double.parseDouble(txtGtotal.getText());
double ad = Double.parseDouble(txtAdvance.getText());
double due = gtotal - ad;
putData.setInt(1, inid);
putData.setDouble(2, gtotal);
putData.setDouble(3, ad);
putData.setDouble(4, due);
try {
putData.execute();
JOptionPane.showMessageDialog(null, txtAdvance.getText());
JOptionPane.showMessageDialog(null, "Invoice details saved");
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, this.getClass().getName() + " first " + e);
}

Related

float and double data type in mysql not storing the full digits required for my java program

I'm storing some values in my mysql database using my java swing app but it doesn't store the full amount of the inputted number. For example if I use float as the data type for the column of the mysql database, it only store 6 digits, if I put in 123456.56, it would only store 123456.00 or if I input 12345.67 it would store only 12345.60. Same when I changed the data type of mysql to double it only stores 8 digits, so if I input 1234567.89 it would only store 1234567.90 only and it would round up the 8th digit. What's wrong with my coding? Thanks. I would like to store the full amount in the database such as millions and hundreds of thousands, ex. 12345678.55 or 445874.44 in full without it turning it into an exponent amount or cutting it short. How do I do that?
if(source == btn_confirm)
{
dbconnect connect = new dbconnect();
String page = text_page.getText();
String line = text_line.getText();
String refpage = text_refpage.getText();
String refline = text_refline.getText();
String transaction_date = text_transdate.getText();
String description = text_desc.getText();
String account_code = text_accountcode.getText();
String code_type = text_codetype.getText();
String issue_date = text_issuedate.getText();
String amount = text_amount.getText();
System.out.println(amount);
try
{
connect.addTransaction(page, line, refpage, refline, transaction_date, description, account_code, code_type, issue_date, amount);
connect.close();
}
catch (Exception x)
{
System.out.println(x);
}
text_page.setText("");
text_line.setText("");
text_refpage.setText("");
text_refline.setText("");
text_transdate.setText("");
text_desc.setText("");
text_accountcode.setText("");
text_codetype.setText("");
text_issuedate.setText("");
text_amount.setText("");
text_page.requestFocus();
}
the text_amount is the textfield containing the number to be passed to a string amount. string used to be a float but I opted to use a string instead as I thought it wouldn't make much of a difference when passing it into a sql statement. I used to use parsefloat.
the method addTransaction adds a transaction to the mysql database as so:
public void addTransaction(String page, String line, String refpage, String refline, String transaction_date, String description, String account_code, String code_type, String issue_date, String amount) throws Exception
{
try
{
connect();
statement = conn.createStatement();
statement.executeUpdate("insert into transaction (page, line, refpage, refline, transaction_date, description, account_code, code_type, issue_date, amount) values ('" + page + "', '" + line + "', '" + refpage + "', '" + refline + "', '" + transaction_date + "', '" + description + "', '" + account_code + "', '" + code_type + "','" + issue_date + "', " + amount + ")");
System.out.println("Inserted transaction of page: " + page + " and line: " + line);
}
catch (Exception e)
{
throw e;
}
}
FLOAT has only 24 bits of precision. That equates to about 7 decimal digits. So, it is impossible to store more than what you are seeing.
FLOAT(12,2) has no use that I can figure. It rounds twice -- once to decimal, once to binary. Either use DECIMAL(12,2) or plain FLOAT or DOUBLE.
DOUBLE gives you about 16 digits of precision. Again, don't use (m,n) with it, and don't expect more digits that it can hold in 53 bits.
MySQL can handle 65 decimal digits: DECIMAL(65, ...). It is, however fixed in that you specify a constant number of places after the decimal point.
How have you initialized the column? If you're storing as float, you can store it in the following format - FLOAT(M,D) where M is the total number of digits and D is the number of digits after the decimal point.
If you have already created your table and don't want to lose information already stored in it, then you can modify the column type with the following query:
ALTER TABLE tableName
ALTER COLUMN columnName FLOAT(M,D);
Replace, M and D accordingly.
Source

How to read and update rows of a Google Fusion Table using JAVA code

(Edit: This is a question that I had and I answer it in the hopes of helping someone else who had a similar question.)
I am trying to clean up geographic data in my Google Fusion Table and would like to write a Java program to read in select Fusion Table rows, modify columns in each row and write out the modified rows back to the original fusion table.
I have found Christian Junk's example code in the Google API Client Libraries documentation: "fusiontables-cmdline-sample" that shows how to: Authorize access to a users fusion tables, list tables, create a table, insert data into a table, show rows, delete a table.
How do I modify this example to make updates to selected rows in a table? (see answer with code below)
[edit]: I didn't find any good solutions on the Net. I have written the solution in Java and will answer in the answers in the hope that it can help someone else how is trying to do this. I am a novice Java programmer so the code reflects that. I also needed to get nearby big cities based on a gps location and used GeoNames api (citiesJSON) creating a bounding box to do that. This solution uses JSON to access items returned from REST calls.
I have written a Java program that does the row data modification described in the question. It uses Christian Junk's example noted in the question and also calls GeoNames citiesJSON webservice as described in the question (sending bounding box coordinates in the parameters). I'm a novice in Java so the code is what it is. I do a lot of commenting in order to reuse code, like SQL queries, later.
You can find my solution on Github at: FusionTableModifyJava
The primary module of interest is: FusionTableSample.java
Here are the functions that do the getRows and updateRows. Everything else can be seen at github (by Microsoft$):
private static void getRows(String tableId) throws IOException {
View.header("Updating Rows From Table");
/*Sql sql = fusiontables.query().sql("SELECT RowID, 'Area Name', Notes, Number FROM " + tableId +
" Where Manager = '' AND 'Review 1' CONTAINS IGNORING CASE '.fs.' Order by Number ASC LIMIT 3000");*/
/*Sql sql = fusiontables.query().sql("SELECT RowID, 'Area Name', Notes, Number FROM " + tableId +
" Where 'Area Name' CONTAINS IGNORING CASE 'Tioga George' Order by Number ASC LIMIT 3000");*/
/*Sql sql = fusiontables.query().sql("SELECT RowID, 'Area Name', Notes, Number FROM " + tableId +
" Where 'Area Name' ='' Order by Number DESC LIMIT 2000");*/
/*Sql sql = fusiontables.query().sql("SELECT RowID, 'Area Name', Notes, Number FROM " + tableId +
" Where 'Area Name' CONTAINS 'X01' Order by Number DESC LIMIT 1"); */
/*AND 'City (nearest)' DOES NOT CONTAIN IGNORING CASE 'Mexico'*/
/*Sql sql = fusiontables.query().sql("SELECT RowID, 'Area Name', Notes, Number, Location FROM " + tableId +
" Where State = '' Order by Number DESC LIMIT 100");*/
/*Sql sql = fusiontables.query().sql("SELECT RowID, 'Area Name', Notes, Number, Location FROM " + tableId +
" Where State = 'BCS' Order by Number DESC LIMIT 100");*/
Sql sql = fusiontables.query().sql("SELECT RowID, 'Area Name', Notes, Number, Location, State, Codes FROM " + tableId +
" Where State = 'ID' AND 'City (nearest)' = '' Order by Number DESC LIMIT 100");
try {
Sqlresponse response = sql.execute();
// System.out.println(response.toPrettyString());
mylist = response.getRows();
} catch (IllegalArgumentException e) {
// For google-api-services-fusiontables-v1-rev1-1.7.2-beta this exception will always
// been thrown.
// Please see issue 545: JSON response could not be deserialized to Sqlresponse.class
// http://code.google.com/p/google-api-java-client/issues/detail?id=545
}
}
private static void updateRows(String tableId) throws IOException {
// IOException needed ParseException
count = 1;
mylist.forEach((myRow) -> {
try {
// modify fields in table...
//newAreaName = kt.firstpart(myRow.get(NOTES).toString()); //get Notes first sentence
//newAreaName = newAreaName.replace("'", "''");
//newAreaName += " X01";
//String state = getStateFrmLoc(myRow.get(LOCATION).toString());
//String state = "MX-BCS";
float km;
if ( "AK,MT,NV".contains(myRow.get(STATE).toString()) ) {
km = 180f; // 111.85 miles
} else {
km = 80.5f; // 50 miles
}
BigCity big = new BigCity(myRow.get(LOCATION).toString(), km);
String cityState = big.cityName +", "+big.state;
if (big.population < 10000f) {
System.out.println("Skip for low population :"+myRow.get(NUMBER));
} else {
sqlupdate = "UPDATE " + tableId + " " +
"SET 'City (nearest)' = '" + cityState + "' " +
",'Codes' = '" + myRow.get(CODES).toString() + ",#U1' " +
"WHERE ROWID = " + myRow.get(ROW_ID);
System.out.println("[" + count + "]" + myRow.get(NUMBER) + ": " + sqlupdate);
// do the update...
if (!mtest) { // if testing then don't update
sql_doupdate(sqlupdate);
}
count++;
if ((count % 30) == 0) {
System.out.println("waiting 60 seconds");
TimeUnit.SECONDS.sleep(60); //Fusion Tables allows 30 updates then must wait 1 minute.
}
}
} catch(Exception e){
System.out.println(e.getMessage());
}
});
}

Can't figure out why SQL statement isn't woking

I can't understand what's wrong with my statement. Seems right to me, and the cursor should include both rows in my database table. According to SQLite website this formatted date is supported (Also tried with other supported dates).
String statement = "SELECT * FROM " + TABLE_DISTANCE_NAME + " WHERE " + COLUMN_TIME_DISTANCE_ADDED + " BETWEEN " + "2014-07-14" + " AND " + "2014-08-14";
Log.d("statement", statement);
Cursor cur = db.rawQuery(statement, null);
Log.d("cursor amount rows", Integer.toString(cur.getCount()));
if (cur != null) {
cur.moveToFirst();
}
int totalDistance = 0;
while (cur.isAfterLast() == false) {
Log.d("cursor distance value", Integer.toString(cur.getInt(0)));
totalDistance += cur.getInt(0);
cur.moveToNext();
}
Log.d("Total Distance traveled = ", Integer.toString(totalDistance));
This is what the table looks like.
Log:
...statement﹕ SELECT * FROM distanceTraveled WHERE timedistadded BETWEEN 2014-07-14 AND 2014-08-14
com.example.RoadTrip D/cursor amount rows﹕ 0
com.example.RoadTrip D/Total Distance traveled =﹕ 0
Thank you
Date constants need to be enclosed in single quotes:
" WHERE " + COLUMN_TIME_DISTANCE_ADDED + " BETWEEN " + "'2014-07-14'" + " AND " + "'2014-08-14'";
This problem would be more readily apparent if you printed out the SQL statement after the substitution. That is always a good first step in trying to debug this type of problem.
try quoting you query paramaters
e.g.
+ "'2014-07-14'" + " AND " + "'2014-08-14'"
Dates and Strings need to be single quoted as per SQL.

Derby db stating that column does not exist when it does

Ok so I have an application that connects to a database that has a customer table. In the customer table I capture a range of different values. VH_ID is a foreign key to the vehicle table and the insurance_ID is also a foreign key to the insurance table.
Any ideas would be appreciated.
Edit
public CustomerInformation getCustomerInfo(String customerName) {
CustomerInformation info = new CustomerInformation();
ResultSet result;
try {
String sqlStatement = "SELECT "
+ DBStrings.C_NAME + ","
+ DBStrings.C_ADDRESS + ","
+ DBStrings.C_PHONENO + ","
+ DBStrings.C_EMAIL + ","
+ DBStrings.C_VH_ID + ","
+ DBStrings.C_VH_MODEL + ","
+ DBStrings.C_VH_YEAR + ","
+ DBStrings.C_VH_REGO + ","
+ DBStrings.C_VH_CHASSIS + ","
+ DBStrings.C_VH_VIN + ","
+ DBStrings.C_INSURANCE
+ " FROM " + DBStrings.CUSTOMER + " WHERE " + DBStrings.C_ID + " = " + this.getCustomerId(customerName);
result = statement.executeQuery(sqlStatement);
while (result != null && result.next()) {
info.setName(result.getString(DBStrings.C_NAME));
info.setAddress(result.getString(DBStrings.C_ADDRESS));
info.setPhoneNumber(result.getString(DBStrings.C_PHONENO));
info.setEmail(result.getString(DBStrings.C_EMAIL));
info.setRego(result.getString(DBStrings.C_VH_REGO) + "");
info.setChassis(result.getString(DBStrings.C_VH_CHASSIS) + "");
info.setVin(result.getString(DBStrings.C_VH_VIN) + "");
info.setVehicleModel(result.getString(DBStrings.C_VH_MODEL) + "");
info.setYear(result.getInt(DBStrings.C_VH_YEAR) + "");
info.setInsurance(this.getInsuranceFromId(result.getInt(DBStrings.C_INSURANCE)));
info.setVehicleMake(this.getVehicleFromId(result.getInt(DBStrings.C_VH_ID)));
}
} catch (SQLException ex) {
Logger.getLogger(Database.class
.getName()).log(Level.SEVERE, null, ex);
}
return info;
}
That is the new code with the ResultSet nested inside the method. Now I am getting the error:
SEVERE: null
java.sql.SQLException: ResultSet not open. Operation 'getInt' not permitted. Verify that autocommit is OFF.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ResultSet.getInt(Unknown Source)
at Database.Database.getCustomerInfo(Database.java:599)
Statement
connection = DriverManager.getConnection(connectionURL, "user", "pass");
statement = connection.createStatement();
Maybe you have column VH_MODEL twice in your query due to a "copy-paste accident" in the constants, i.e. another constant also expands to "VH_MODEL", specifically one of the columns following VH_MODEL in the get sequence. The DBMS would rename the result columns to make them unique in this case I guess. This would explain the strange situation where excuteQuery works while the getString fails.
Essentially the work around that I did to solve this issue was to create another method just specifically for retrieving the vehicle make. Seems a bit pointless but for the life of me I have no idea why it is not accepting it. The method has exactly the same contents for retrieving the data as in the first method.. Seems very odd.
String sqlStatement = "SELECT "
+ DBStrings.C_VH_ID
+ " FROM " + DBStrings.CUSTOMER + " WHERE " + DBStrings.C_ID + " = " + customerId;
rs = statement.executeQuery(sqlStatement);
if (rs != null && rs.next()) {
int vh_id = rs.getInt(DBStrings.C_VH_ID);
vehicle = this.getVehicleFromId(vh_id);
}

Insert Java.sql.Date into Derby Database

I am trying to insert a date object into the database but it says im trying to insert an Integer. Here is my code:
public void insertAssignment(long studentId, String newAssignment, int ptsTotal, int ptsRecieved, String category, Date dueDate, String term, int yr) {
java.sql.Date temp = new java.sql.Date(dueDate.getTime());
try{
s.execute("INSERT INTO Assignments " +
"VALUES (" + studentId + ",'" + newAssignment + "'," + ptsTotal +
"," + ptsRecieved + ",'" + category + "'," + temp
+ ",'" + term + "'," + yr + ")");
System.out.println("Assignment inserted.");
}
catch(SQLException error){
System.err.println("Unable to insertAssignment.");
error.printStackTrace(System.err);
System.exit(0);
}
}
My error:
java.sql.SQLSyntaxErrorException: Columns of type 'DATE' cannot hold values of type 'INTEGER'.
To do this, use a prepared statement instead and use a setter.
Currently you flatten your date to a string value (which needs to be in the right format for the database for this to work) and lose that it is a date so the database needs to parse it. You avoid this using the prepared statement.

Categories