7

我有一些JDBC代码如下:

String selectSQL = "SELECT * FROM DBUSER WHERE USER_ID = ? and PASSWORD = ?";

Integer userId = 1000;
char[] passwordString = new char[] { 't', 'e', 's', 't' };

PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
preparedStatement.setArray(2,... ??? // how to do this part?

// execute select SQL statement
ResultSet rs = preparedStatement.executeQuery();

如何调用preparedStatement.setArray设置查询中的第二个参数?我不想在这里使用字符串参数来保护密码。

注意我正在使用 Hypersonic DB,但如果有用的话,我计划转移到 MySql。

4

4 回答 4

9

PreparedStatement#setArray收到一个java.sql.Array 首先你应该使用 JDBC Conncetion 的createArrayOf方法来创建数组,然后你才能将它传递给setArray.

由于该方法只接受Object[]您应该创建一个数组Character而不是 char。

例如:

Character[] passwordString = new Character[] { 't', 'e', 's', 't' };
Array sqlArray = con.createArrayOf("CHAR", passwordString);
preparedStatement.setArray(2, sqlArray);
于 2012-12-20T13:30:42.813 回答
3

If you want to pass an array in prepared statement just call

preparedStatemtn.setArray(index,array);

But what you must assure first is that in your DB the column is also a ARRAY. For more detail please see Aviram Sagal answer.


But your base idead it to protect the password.

This solution will protect only from reading the passoword from Java string pool. This is very ratre type of attact anyway. Ans passoword is transmited as plain text.

My sugestion is that instead of complicating the db schema, you should use some benefits of cryptography. Instaed of passing the password value, you should pass password digest.

A simplyfied example of digest function.

public static String getDigest(byte[] password) {

  return new String(Hex.encodeHex(new MessageDigest.getInstance("SHA").digest(password)));

}

Then you store in db the digest with is safe and you use simple string in queries.

于 2012-12-20T13:55:57.880 回答
1

看看这段代码

final PreparedStatement statement = connection.prepareStatement(
        "SELECT my_column FROM my_table " + 
        "where search_column IN (SELECT * FROM unnest(?))"
);
final String[] values = getValues();
statement.setArray(1, connection.createArrayOf("text", values));
final ResultSet rs = statement.executeQuery();
try {
    while(rs.next()) {
        // do some...
    }
} finally {
    rs.close();
}

也请看这篇文章以供参考http://people.apache.org/~djd/derby/publishedapi/java/sql/PreparedStatement.html

于 2012-12-20T13:30:02.040 回答
0

另一种选择是使用 aCharArrayReader并调用statement.setCharacterStream.

char[] passwordString = new char[] { 't', 'e', 's', 't' };
statement.setCharacterStream(1, new CharArrayReader(passwordString));
于 2013-08-15T13:26:51.093 回答