Store array of strings in MySql via java?

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" which refers to the prepared statement

now I want to call the following method:

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

      

where "elements" refers to a String array, but the setArray () method accepts a java.sql.Array instead of a String array.

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

+2


source to share


3 answers


You do it like this,



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

      

+1


source


Typically, when you try to store an array in RDBM, it indicates the need to further normalize your data model. That is, you can set up another table with a foreign key relationship to your current table and then store each element of the array in a new table.



+4


source


As far as I know, setArray(int i, Array x)

and java.sql.Array

which is the interface to retrieve and materialize the ARRAY SQL3 datatype cannot be used the way you want to use it.

By the way, the Array implementation is optional as per the JDBC spec and I don't think the MySQL driver provides the implementation.

+2


source







All Articles