问题
I try to insert values from my java application and values from table1 into table2. I get the following error(db2 z/os):
Exception in thread "main" com.ibm.db2.jcc.am.SqlIntegrityConstraintViolationException: DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=1;DB2T.TSOZ360_WV_AUSGANG, DRIVER=3.66.46
PreparedStatement _prep = con.prepareStatement("INSERT INTO DB2T.TABLE2 (column1, column2, column3 , column4, column5, column6) SELECT ?, ?, ?, ?, column5, column6 FROM DB2T.TABLE1 WHERE column1 = ? column2 = ? AND column3 = ?");
_prep.setString(1,"HELLO");
_prep.setString(2,"H");
_prep.setString(3,"1234567890");
_prep.setString(4,"Hsdfdsffdssdfsdfd");
_prep.setLong(5,9876543210l);
_prep.setInt(6,1);
_prep.setInt(7,12345678);
Table1:
column1, column2, column3 , column4, column5, column6
Table2
column1, column2, column3 , column4, column5, column6
So I want to insert values I generated in the java application into TABLE2 and two values from TABLE1. Without import this two values into the application. What I'm doing wrong?
回答1:
The sql exception you got suggests that you're trying to insert 2 identical values into a column that accepts unique values (did you use this insert with the same parameter values more than once?).
However, your design is still bad so I would suggest that you split your query/statement into a select and an insert (2 queries/statements instead of just 1). This would make the code more readable as well as easier to debug. Second, you shouldn't use column names as parameters (?) in a PreparedStatement (a PreparedStatement is meant to be reusable, however, if column names are parameterized, the database can't reuse the statement).
This means that it's wrong to do something like
String sql = "SELECT ?, ?, ?, ?, column5, column6 FROM DB2T.TABLE1 WHERE column1 = ? column2 = ?
_prep.setString(1, colName1);
_prep.setString(2, colName2);
....
You will have to specify the column names in your query (select a,b,c from T where x=?). If they need to be obtained dynamically you can use string concatenation (this is potentially prone to sql injection if you don't sanitize user input etc )
String dynamicColNames = getColumnNames();//just some method to get the names as one string
String sql = "SELECT "+dynamicColNames + " FROM ....";//
//dynamicColNames may contain col1, col2, col3 etc
来源:https://stackoverflow.com/questions/39637102/insert-with-select-give-sql-error-sqlcode-803-sqlstate-23505db2-z-os