简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM