I'm trying to update a SQL table where the workout_date is my primary key. I'm getting an error message about the date format. I've tried everything I can think of but still stuck. Here's the relevant code:
public static Boolean updateWorkout(String date, float totalWorkout, float walkTime,
float runTime, float distance, float average, String rate,
Integer workoutID) throws SQLException {
Locale loc = new Locale("en", "US");
PreparedStatement sqlCommand = DBConnection.getConnection().prepareStatement("UPDATE " +
"progress_table SET totalTime=?, timeWalking=?, timeRunning=?, totalDistance=?, " +
"avgPace=?, workoutRating=?, workoutID=? WHERE workout_date=?");
sqlCommand.setString(1, date);
sqlCommand.setFloat(2, totalWorkout);
sqlCommand.setFloat(3, walkTime);
sqlCommand.setFloat(4, runTime);
sqlCommand.setFloat(5, distance);
sqlCommand.setFloat(6, average);
sqlCommand.setString(7, rate);
sqlCommand.setInt(8, workoutID);
try {
sqlCommand.executeUpdate();
sqlCommand.close();
return true;
} catch (SQLException e) {
e.printStackTrace();
sqlCommand.close();
return false;
}
}
And my error message:
com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Incorrect date value: '10' for column 'workout_date' at row 1
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:104)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1098)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1046)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1371)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1031)
at Model.Progress.updateWorkout(Progress.java:121)
at Controller.editView.saveRun(editView.java:157)```
Insights will be greatly appreciated!
Edit to add a sample of the data I'm working with. I'm testing with the last line.
[![Data][1]][1]
[1]: https://i.stack.imgur.com/5Lqh5.png
Your parameters are not in order:
PreparedStatement sqlCommand = DBConnection.getConnection().prepareStatement("UPDATE " +
"progress_table SET totalTime=?, timeWalking=?, timeRunning=?, totalDistance=?, " +
"avgPace=?, workoutRating=?, workoutID=? WHERE workout_date=?");
sqlCommand.setFloat(1, totalWorkout);
sqlCommand.setFloat(2, walkTime);
sqlCommand.setFloat(3, runTime);
sqlCommand.setFloat(4, distance);
sqlCommand.setFloat(5, average);
sqlCommand.setString(6, rate);
sqlCommand.setInt(7, workoutID);
sqlCommand.setString(8, date);
Additionally, if you are assigning a primary key to a table, it MUST be unique rather than most likely to be. Primary keys indicate that no matter what, this value references this row in this table and no other. Consider adding a true auto incrementing primary key or setting up a clustered index/combination key. A great option would be a combination of workout_date and workout_id for example.
Related
I'm trying to add designation and its salary using a JDBC transaction.
The problem is this throws an exception about duplicate key.
This is the first time I put some invalid data in salary columns and after that everything is correct. It shows duplicate key exception for designation id
but the designation id is not stored already and not even for first attempt.
The first transaction that is invalid is rolled back, but storing on next time it shows duplicate key exception.
Below is my code:-
public boolean addDesignation(ObservableList nodeList) throws SQLException {
Connection demo = getConnection();
demo.setAutoCommit(false);
Savepoint savePoint = demo.setSavepoint("savePoint");
try {
PreparedStatement addDesig = demo.prepareStatement(
"INSERT INTO `designation`(`desig_id`,`dept_id`,`desig_name`,`desig_desc`) VALUES (?,?,?,?)");
PreparedStatement addSal = demo.prepareStatement("INSERT INTO `salary` "
+ "(`desig_id`, `basic`, `house_rent`, `conveyance`, `medical`, `dearness`,`others_allowances`,"
+ " `income_tax`, `pro_tax`, `emp_state_insu`, `absence_fine`, `others_deductions`, `month`)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
addDesig.setString(1 , nodeList.get(0).toString());
addDesig.setString(2, nodeList.get(1).toString());
addDesig.setString(3, nodeList.get(2).toString());
addDesig.setString(4, nodeList.get(3).toString());
addDesig.executeUpdate();
addSal.setString(1, nodeList.get(0).toString());
addSal.setInt(2, Integer.parseInt(nodeList.get(4).toString()));
addSal.setInt(3, Integer.parseInt(nodeList.get(5).toString()));
addSal.setInt(4, Integer.parseInt(nodeList.get(6).toString()));
addSal.setInt(5, Integer.parseInt(nodeList.get(7).toString()));
addSal.setInt(6,Integer.parseInt(nodeList.get(8).toString()));
addSal.setInt(7,Integer.parseInt(nodeList.get(9).toString()));
addSal.setInt(8, Integer.parseInt(nodeList.get(10).toString()));
addSal.setInt(9, Integer.parseInt(nodeList.get(11).toString()));
addSal.setInt(10, Integer.parseInt(nodeList.get(12).toString()));
addSal.setInt(11, Integer.parseInt(nodeList.get(13).toString()));
addSal.setInt(12, Integer.parseInt(nodeList.get(14).toString()));
addSal.setString(13, nodeList.get(15).toString());
addSal.executeUpdate();
demo.commit();
return true;
} catch (SQLException ex) {
demo.rollback(savePoint);
Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
these are two tables and im trying to add that data in my first attempt failed but not store due roll back
There are 2 INSERT statements in your code.
The 1st for designation table:
"INSERT INTO `designation`(`desig_id`,`dept_id`,`desig_name`,`desig_desc`) VALUES (?,?,?,?)"
here it looks like desig_id is the primary key (maybe autoincrement in which case you must not supply a value at all).
Are you sure the value that you supply for this column does not already exist in the table?
The 2nd for the salary table:
"INSERT INTO `salary` " + "(`desig_id`, `basic`, `house_rent`, `conveyance`, `medical`, `dearness`,`others_allowances`," + " `income_tax`, `pro_tax`, `emp_state_insu`, `absence_fine`, `others_deductions`, `month`)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
in this case it is not clear since you did not post the CREATE statement of the table, which is the primary key.
So you have to check, if the value (or values if it's a multi column key), violate the uniqueness of the key.
I am working on a option in a Menu function that posts the car for the sale in a database. The option asks for the user to enter the year, make, condition and price, which is then inserted into the table car_sale in the database. However, a unique listing_no must also be generated during this option. I cannot define my tables to uniquely generate the 10 digit number the option but I must code the program to insert uniquely generated listing_no. Below you will find the code of me trying to do this, however the code only works in Oracle but I cannot use Oracle. I can only PostGreSQL and Java. Therefore, my problem arises as the functions and relations I am using cannot be used in PostGre.
Code to Generate Listing No:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(sysdate,'yyyymmdd')||AUDIT_SEQ.NEXTVAL)valnext from dual");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Code in The Option Function to insert the lisitng_no generated from generateListingNo()
public void option() throws SQLException
{
int listing_no = generateListingNo();
// insert information into books_for_sale table
sql_insert = "INSERT INTO car_sale VALUES(" + listing_no +", "
+ "'" + year + "'" + ", " +
"'" + make + "'" +", " +
"'" + condition + "'" + ", "
+ price + ")";
Erros I am Getting:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: relation "dual" does not exist
Position: 69 at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:318)
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:281)
Creating the car_sale table
create table car_sale(
listing_no int not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
Change you query for generateListingNo as below:
select q from (select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ') )q )sq
or
select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval
or on your cocde:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Since you dont have sequence :
Either create sequence using below query:
CREATE SEQUENCE public."AUDIT_SEQ"
INCREMENT 1
START 1
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 1;
or use UUID:
public String generateListingNo() throws SQLException
{
return UUID.randomUUID().toString();
}
your table structure will need to change :
create table car_sale(
listing_no varchar not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
For PostgreSQL, you have to call query this way from java :
SELECT nextval('ACCOUNT_TRANSACTION_NO')
I am trying to insert data from ArrayLists into a mysql table in Java, however I keep getting the following error: java.sql.SQLException: Data truncated for column 'AAL' at row 1.
Here is some of the code:
stmt = conn.createStatement();
sql = "CREATE TABLE IF NOT EXISTS stocks "
+ "(id INTEGER not NULL AUTO_INCREMENT, date LONGBLOB , " + "time LONGBLOB, "
+ " PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
for (int i = 0; i < stockList.size(); i++) {
System.out.println(stockList.get(i).getName() + i);
sql = "ALTER TABLE stocks ADD " + stockList.get(i).getName() + " DOUBLE";
stmt.executeUpdate(sql);
}
for (int i = 0; i < stockList.size(); i++) {
System.out.println(i);
sql = "INSERT INTO stocks (id, date, time, " + stockList.get(i).getName() + ") VALUES (NULL, '" + stockList.get(i).getDate() +
"', '" + stockList.get(i).getTime() + "', '" + stockList.get(i).getPrice() + "')";
stmt.executeUpdate(sql);
}
Any help is much appreciated.
You indicated that stockList.get(i).getPrice() is a string, and you are putting quotes around the value in the insert. So you are effectively trying to insert a string value into a DOUBLE column. Normally MySQL will auto convert strings to doubles, however, my suspicion is that at least some of your getPrice() values are not valid doubles. You can try this instead:
... "', " + Double.parseDouble(stockList.get(i).getPrice()) + ")";
..but if some of the prices are not valid doubles, this will fail as well.
There are some issues with your table and query design:
Use DATE, TIME, or DATETIME types for storing dates and times. LONGBLOB is not meant for this.
The data that is truncated is actually the price you're trying to insert into the DOUBLE column. If getPrice() is returning a string, you need to check decimal and thousant separators. MySQL uses . (point) as decimal and , (comma) as thousant separator by default. And do not use quotes in your query.
When dealing with prices, consider using DECIMAL as type. FLOAT and DOUBLE may not be exact.
I have the following problem:
I have two tables in one data base which consist of the same columns besides the name of the last column. I want to write data into them using Java.
I want to use the same preparedStatement for both tables, where I check with an if-command whether it is table1 or table2. table2 has amount10 as the name for the last column, table1 has amount20 for it. This number is stored in a variable within my code.
Below you can see a (simplified) example and how I tried to let the column name variable but it doesn't work. Is there any way to fix this without copying the whole statement and manually changing the number variable?
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount`+"number") VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount`+"number" = ? ; ";
PreparedStatement insertDataStmt;
This will not work since variables number and table are not going to be magically injected into your insertData string while you are changing them.
I'd to a method prepareInsertstatement(String table, String number) that would return correct PreparedStatement:
public void prepareInsertStatement(Connection conn, Strint table, String number) {
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount+"number"') VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount+"number"' = ? ; ";
PreparedStatement insertDataStmt = conn.prepareStatement(insertData);
return insertDataStmt;
}
Just remember to close the PreparesStatement when you don't need it any more.
I suppose that reason for that is invalid syntax. When you concatenate string for last column name you use code 'amount' + number. If your number value is 20, than concat result will be
'amount'20 that cause invalid syntax exception. Just move one extra ' after number.
"'amount" + number + "'"
Note: log, or just error that appears during this statement execution would be very useful to find right answer for your question.
I've narrowed down my problem to these lines of code and I know it has something to do with the syntax. The error i get is: [Microsoft][ODBC Microsoft Access Driver] Syntax error in field definition the section of code I get the error from is:
try {
System.out.println("Creating StockTrades table...");
stmt.executeUpdate("CREATE TABLE StockTrades (userID TEXT(20) CONSTRAINT FK1_StockTrades REFERENCES "
+ "Users (userID), symbol TEXT(8), CONSTRAINT FK2_StockTrades FOREIGN KEY (symbol) "
+ "REFERENCES Stocks (symbol), numStocks INT, pricePerStock DECIMAL(5, 2), "
+ "stocksPurchased INT, stocksSold INT, totalCashPaid DECIMAL(9, 2), "
+ "totalCashReceived DECIMAL(9, 2))");
} catch(Exception ex) {
System.out.println("Exception creating StockTrades table: " + ex.getMessage());
}
try {
System.out.println("Creating StockTrades table primary key index...");
stmt.executeUpdate("CREATE UNIQUE INDEX PK_StockTrades ON StockTrades (userID, symbol) "
+ "WITH PRIMARY DISALLOW NULL");
} catch(Exception ex) {
System.out.println("Exception creating StockTrades index: " + ex.getMessage());
}
Solution: To save people from reading through all the comments, this issue was solved by switching from a Decimal field type to the Currency type. The underlying issue was never identified or solved for those who can't switch away from the decimal type.
If I were to guess, I'd say it's this line:
symbol TEXT(8), CONSTRAINT FK2_StockTrades FOREIGN KEY
It seems you have an extra comma between text(8) and the constraint.
Edit: I had posted this just before the other poster then voted to delete. After researching it, you can do it either way, with or without the comma. However, you have it done both ways in consecutive lines. Perhaps that's the issue?
CREATE TABLE StockTrades (userID TEXT(20) CONSTRAINT FK1_
^---
missing comma?