3

I have a String Array in a java program. I am using jdbc driver to store data in MySql.

There is a reference variable "pstmt" that refers to a prepared statement

now I want to call the following method:

String [] items = {pen, ball, speaker, mic};  
pstmt.setArray(1, ....);

where "items" refer to String array but the method setArray() takes java.sql.Array instead of String array.

So how can I convert the string array "items" to a java.sql.Array so that I can pass an argument in the above method call.

3 Answers 3

4

Generally when you try to store an array in a RDBM it's an indication that you need further normalization of your data model. I.e. you could set up another table with a foreign-key relationship to your current table and then store each element of the array in the new table.

Sign up to request clarification or add additional context in comments.

1 Comment

I liked your point but my client's requirement is to store all the records only in one table. I know this is very bad approach to manage data.
3

As far as I know, setArray(int i, Array x) and java.sql.Array which is an interface for retrieving and materializing an SQL3 ARRAY data type can't be used in the fashion you want to use it.

By the way, implementing Array is optional according to the JDBC specification and I don't think MySQL's driver provide an implementation.

Comments

2

You do it like this,

String [] items = {pen, ball, speaker, mic};  
pstmt.setArray(1, pstmt.getConnection().createArrayOf("String", items));

1 Comment

Are you sure this works in practice?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.