开发者

How I can make a table in database having variable columns in Java?

I have a Java web application. I have to create a table, and I am using JDBC.

I don't know in my list tag how many values will be there, so for each value tag, I need a corresponding column in my table. These values are fetched from some other application.

So I can create a table having n number of columns where n can开发者_开发技巧 be different every time.

<list>
<value>Name</value>
<value>Address</value>
<value>Contact No</value>
..
.
.
</list >

How can I achieve this?


You should use n rows to store the values, not n columns. Columns are somehow 'fixed' in a database, while it is easy to add/delete/modify rows.


You need to deal with your table structure dynamically. Several solutions exist.

With JDBC, simply query Oracle and retrieve the columns of your table.

String myTable = "FOO_TABLE";
String query = "Select COLUMN_NAME from USER_TAB_COLUMNS where TABLE_NAME=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, myTable);
//
Set<String> existingColumns = new HashSet<String>();
ResultSet rs = ps.executeQuery();

while (rs.next())
{
    existingColumns.add(rs.getString(1));
}

Now you know which column exists or not and you can ALTER your table as you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜