Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Passing array parameter in prepare statement - getting "java.sql.SQLFeatureNotSupportedException"

I am facing error java.sql.SQLFeatureNotSupportedException in my prepare statement. I am using Mysql database.

Below is my code.

class tmp {
public static void main(String arg[]) {

    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/sample", "root", "root");
        PreparedStatement pst = conn
                .prepareStatement("select * from userinfo where firstname in(?)");

        String[] Parameter = { "user1", "Administrator" };
        Array sqlArray = conn.createArrayOf("VARCHAR", Parameter);
        pst.setArray(1, sqlArray);
        ResultSet rs = pst.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getInt(1));
        }
    } catch (Exception e) {
        e.printStackTrace();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Mysql -

Setting array is not possible in Mysql.

Instead of that you can form a query for (?,?,..) in the loop and same way for setting values.

String[] Parameter = { "user1", "Administrator" };
String query = "select * from userinfo where firstname in (";
String temp = "";

for(i = 0; i < Parameter.length; i++) {
  temp += ",?";
}

temp = temp.replaceFirst(",", "");
temp += ")";
query = query + temp;

PreparedStatement pst = conn.prepareStatement(query);

so query becomes

select * from userinfo where firstname in (?,?)

and pass values also using loop.

For Oracle -

ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("CHAR_ARRAY", conn);
String[] Parameter = { "user1", "Administrator" };
java.sql.Array sqlArray = new oracle.sql.ARRAY(arrayDescriptor, conn, content);
.
.
pstmt.setArray(1, sqlArray);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...