I have the below JDBC code:
public int addItem(String name, String price, String count, String isPR, String img) {
int result = 0;
try {
String query = "INSERT INTO T001_ITEM"
+ "(ITEM_NO,ITEM_NM,UNIT_PRICE,STOCK_COUNT,RECORD_DATE,IS_PR,ITEM_IMAGE_FILE_PATH)"
+ "VALUES(TABLE_SEQ.NEXTVAL,'" + name + "','" + price + "','" + count + "', sysdate,'" + isPR
+ "','" + img + "')";
pstmt = conn.prepareStatement(query);
result = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
It throws the below error:
java.sql.SQLSyntaxErrorException: ORA-01722.
How is this caused and how can I solve it?
Do not concatenate your values into your query like you do now with '" + name + "'
, and to avoid SQL injection, I suggest you use a prepared statement with parameters:
String query = "INSERT INTO T001_ITEM "
+ "(ITEM_NO, ITEM_NM, UNIT_PRICE, STOCK_COUNT, RECORD_DATE, IS_PR, ITEM_IMAGE_FILE_PATH) "
+ "VALUES(TABLE_SEQ.NEXTVAL, ?, ?, ?, sysdate, ?, ?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, price);
pstmt.setString(3, count);
pstmt.setString(4, isPR);
pstmt.setString(5, img);
Note
Make sure the type of your attributes is same in your table, you set all your values as String. I don't think that the price
can be a String or isPR
seems to be a Boolean
not a String
, and the count
can be a number not a String
so check your types carefully.
If you can't change the type outside your method then you can cast it to the right type but you should to test them , this can make another problem.
So for example
int countN = Integer.parseInt(count);
or
pstmt.setInt(3, Integer.parseInt(count));
and so on for all the other type.
Like what this documentation says here :
What causes this error?
An ORA-01722 ("invalid number") error occurs when an attempt is made to convert a character string into a number, and the string cannot be converted into a valid number. Valid numbers contain the digits '0' through '9', with possibly one decimal point, a sign (+ or -) at the beginning or end of the string, or an 'E' or 'e' (if it is a floating point number in scientific notation). All other characters are forbidden.
So like I said before, check if the type is exact in your table, you can't set a String in the place of Number
Sorry i don't have enough reputations to add this as comment,
ORA-01722: Simply means it is unable to convert the String values to the integer.
By looking at your what i can understand is you are passing price and count as string to the DB, can you check what is the declaration of the fields in DB. You need to convert them to int and then you can try insertion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.