How to detect PreparedStatement.setObject() failures on time?

My program loads a simple CSV into a table. The data in the file is expected to match the table’s layout.

The (simplified) code is:

            String sql = "select * from " + _tableName +
                " where 1 < 0";
            PreparedStatement stmt = _CONN.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            rs.close();
            stmt.close();

            _columnCount = rsmd.getColumnCount();
            sql = "insert into " + _tableName + " values (" +
                "?,".repeat(_columnCount - 1) + "?)";
            stmt = _CONN.prepareStatement(sql);
...
            int line_no = 0;
readingInput:
            for (String line : Files.readAllLines(input,
                StandardCharsets.UTF_8)) {
                line_no++;
                String[] sa = line.split(_inputSeperator, -1);
                int column = 0;
                for (String st : sa) try {
                    column++; /* JDBC numbers columns from 1... */
                    stmt.setObject(column, st,
                        rsmd.getColumnType(column));
                } catch(SQLException e) {
                    logger.error("{}:{} SQL Exception parsing field {} of <<{}>>",
                        _fileName, line_no, column, line);
                    continue readingInput;
                }
                stmt.addBatch();
            }
...
            stmt.executeBatch();

This, actually, works for valid inputs, but one of my tests tries a bogus line — attempting to insert a string into a numeric column.

Such invalid input does generate an error, but only at the stmt.executeBatch() line at the end, where I’m not prepared for it: java.sql.BatchUpdateException: Error converting data type nvarchar to int.

Why wouldn’t the error trigger, when an invalid value is passed to the Statement.setObject() instead — where my code is prepared to report it, skip the bogus input-line and keep going?

All of the PreparedStatment.setFoo() methods are declared as throwing the SQLException — why wouldn’t setObject() actually throw one?

Perhaps, this is done to save time — and there is some option for an immediate validation of values passed to the PreparedStatement, even if it takes longer?

Update: I changed the inner loop to force the conversion into column’s Java-class thus:

            int column = 0;
            for (String st : sa) try {
                column++; /* JDBC numbers columns from 1... */
                int columnType = rsmd.getColumnType(column);
                if (st.isEmpty()) {
                    stmt.setNull(column, columnType);
                    continue;
                }
                Object value;
                try {
                    value = Class.forName(rsmd.
                        getColumnClassName(column)).
                        getConstructor(String.class).newInstance(st);
                } catch(InvocationTargetException e) {
                    /* We want the underlying cause here... */
                    throw(e.getCause());
                }
                stmt.setObject(column, value, columnType);
            } catch(java.lang.Throwable e) {
                logger.error("{}:{} Exception parsing field {} ({}) of <<{}>>: {}",
                    _fileName, line_no, column,
                    rsmd.getColumnName(column), line,
                    e);
                    continue readingInput;
            }

This, actually, works as I want it to — doing, what I expected the underlying setObject to do for me automatically…

The behaviour is driver-specific. Some JDBC drivers will validate the conversion themselves (usually because they need to apply the conversion client-side because the server expects specific datatypes), and then you would get the exception on calling setXXX. Other JDBC drivers will simply send a typed value to the server using the SQL-equivalent datatype of the type you used on set, and on execute, the server will perform the required conversion to the actual column datatype, and that will either succeed or fail if the requested conversion is not possible or fails some other requirement.

The JDBC specification allows for both, because of the great variance between features and behaviours in database server. There is no way for you to require the conversion is applied at a specific point.

Besides, even for drivers that perform or check basic conversion client-side, execute could still fail for the value you set, for example because of primary key, foreign key, CHECK, NOT NULL, or UNIQUE constraints, triggers, etc.

If you want to avoid errors, you could try to inspect the ParameterMetaData from PreparedStatement.getParameterMetaData(), and perform the necessary validation or conversions yourself, but again, that that does not mean a value couldn’t still produce a failure on execute.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật