Welcome to OStack Knowledge Sharing 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 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...