添加数组时准备语句错误

时间:2013-03-21 22:12:07

标签: java sql arrays spring

我正在使用SPRING famework,我正在尝试在创建新条目(行)时向我的数据库添加一个数组。相关列称为“关键字”。所以这是我的sql初始化代码(对我来说很好看)

CREATE TABLE IF NOT EXISTS Email (
    Email_Id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    Sender_Email VARCHAR(255) NOT NULL,
    Recipient_Email VARCHAR(255) NOT NULL,
    Subject VARCHAR(255) NOT NULL,
    Body TEXT,
    Attachment_Path VARCHAR(255) NOT NULL,
    Creation_Date DATETIME NOT NULL,
    MaxKeywords INT UNSIGNED NOT NULL,
    Keywords VARCHAR(255) NOT NULL,
    Primary Key(Email_Id)
);

以下是我的添加功能中崩溃和刻录的代码:

public boolean add(final MessageDto emailDto){
    boolean result = false;
    int rowsAffected;
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final String sql;

    sql = "INSERT INTO email (Sender_Email, Recipient_Email, Subject, Body, Attachment_Path, Creation_Date, MaxKeywords, Keywords) " +
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    try{
        rowsAffected = getJdbcTemplate().update(
                  new PreparedStatementCreator() {
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement statement = 
                                    connection.prepareStatement(sql, new String[] {"emailId"});

                            String[] foo = {"A","B"};

                            statement.setString(1, emailDto.getFrom());
                            statement.setString(2, emailDto.getTo());
                            statement.setString(3, emailDto.getSubject());
                            statement.setString(4, emailDto.getBody());
                            statement.setString(5, emailDto.getAttachmentPath());
                            statement.setTimestamp(6, new Timestamp(emailDto.getCreationDate().getMillis()));
                            statement.setInt(7, emailDto.getMaxKeywordCount());
                            statement.setArray(8, connection.createArrayOf("varchar", foo));

                            return statement;
                        }
                      }, keyHolder);

        if(rowsAffected > 0){
            emailDto.setEmailId(keyHolder.getKey().intValue());
            result = true;
        }
    } catch (Exception e){
        throw new RuntimeException(e);
    }

    return result;
}

抛出的错误是:

org.springframework.dao.InvalidDataAccessApiUsageException: PreparedStatementCallback; SQL []; null; nested exception is java.sql.SQLFeatureNotSupportedException

帮助?

1 个答案:

答案 0 :(得分:0)

如果您决定放弃setArray方法,则可以执行此操作。使用您自己的逻辑将数组转换为字符串。无论如何,您将它存储在varchar中,因此您必须“展平”阵列。

    String[] foo = {"A","B"};
    StringBuilder sb = new StringBuilder();
    for (String bar : foo) {
        sb.append(bar);
        sb.append("\t");
    }
    statement.setArray(8, sb.toString());