Dynamically displaying result set on a HTML page in a table - java

I have a webpage which accepts a query from the user, and passes it to a servlet. This servlet calls my java functions which run the query and get the resulting table. I now have this result set, but I wish to display this result set in a table on my webpage. The problem is I don't know what the query is before hand or the schema of the table it will run on. I wanted to know if there is a way to dynamically present the result set contents on a table on my webpage. Since I don't know the schema, don't have the option of creating a java model object. I'm using HTML, JSP and obviously Java

I hope my memory about JSP is good. I suppose you have do a select with '*' to have all columns. In the result you can have the number of columns, so know how much column you have to create, and a "for" on column names, give you the column names. With this you should be able show select result without knowing in advance the column name in table. May be its only possible only on result set from JDBC. Sorry if not apply for you

Use getMetaData() on your resultset object to get the details of resultset like number of columns and names of the column. Using size() method get the size of the resultset.
Next using the size() you can compute how many rows should be there in your html table and using resultset.getMetaData().getColumnCount() you can compute number of columns in your html table. You can use the column names to be headings of your table columns.
Let me know if you need further help.
sample code retrieve metadata from you resultset.
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
for (int i = 1; i <= numberOfColumns; i++) {
System.out.println("column MetaData ");
System.out.println("column number " + i);
// get the column's name.
System.out.println(rsMetaData.getColumnName(i));
}

Related

Migrate ResultSet between two MySQL tables without specifying columns in Java

I have a MySQL database on server #1 and I need to migrate it to server #2. The database is very large and methods like mysqldump or MySQL Workbench Migration didn't work for me, so I wanted to write my own Java application, that would perform the following steps:
get all table names from the source database schema
for each table, it would select a batch of records (let's say 10.000 at a time) and insert them in the corresponding table in destination database. The schema is already prepared with correctly defined tables.
repeat until there are no rows left for current table.
repeat for each table.
The problem is, AFAIK, when using JDBC, it is needed to iterate through ResultSet and specify all column types and names, like this:
while (resultset.next()) {
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
I want to do this for all tables and all their columns without specifying their names and types manually. I can't just type manually all these columns, as I have 150 tables and each of them has like 10-50 columns.
Is there any general way how to do this? Maybe taking advantage of the fact that both source and destination schemas are the same (same tables with same column names/types and same foreign keys)?
You can use ResultSetMetaData with ResultSet to get the columnNames, columnCount and few other details.
ResultSet resultSet = ps.executeQuery();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
while (resultSet.next()) {
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
System.out.println(resultSet.getString(i));
}
}
if you need to fetch the type of Column also to make the decision you could use Switch conditions based on the type returned from resultSetMetaData.getColumnTypeName(i) for using something like
resultSet.getString()
resultSet.getInt()
resultSet.getBoolean()
resultSet.getDate()
Many more
On top of #koushlendra answer, you can also use these methods for additional informations(if needed)
resultSetMetaData.getTableName(int column) Returns the column’s table name.
resultSetMetaData.getSchemaName(int column) Returns the name of the schema of the column’s table.

How to display selected columns of database in a Jtable?

I successfully populated my JTable with the contents of my database table but I only want to show selected columns of it. Is there any way of doing this? Or is it even possible to select which column to display in a JTable?
Here is the method of populating my JTable
private void Update_table() {
try {
String sql = "select * from Members";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
Members_Table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
My database table name is "Members". "Members_Table" is the name of my JTable.
You could try changing your sql statement to only select the columns you are interested in. For instance, if Members has the columns "MemberId", "MemberFirstName", "MemberLastName" "MemberAddressFK", and you only wanted to display MemberFirstName and MemberLastName, you could change your sql to be
String sql = "select MemberFirstName, MemberLastName from Members";
You can find more details about the sql select statement at http://beginner-sql-tutorial.com/sql-select-statement.htm
If you're looking for a bit more robust data model on the Java side and want to hide the columns in the JTable, you can use removeColumn from JTable. This does not remove the column from the Table model, only from visible presentation. If you keep track of which columns are hidden or visible, you can easily put the column back in, and its data will still be properly associated.
For example, to remove the first column, you could use:
myTable.removeColumn(myTable.getColumnModel().get(0));
// i don't remember if it's 0-index or 1-index for first column
As an example, I would dynamically fill a JPanel with checkboxes for each column and then checking and unchecking individual boxes would hide and disable those columns. This allows you to keep all the data, but only present those relevant to the user at the time, similar to how hiding columns in Excel works.

how get next autonumber from one column jdbc database?

I am using an access mdb file as my database . Inside the table in my database I use id as autonumber. Now. I wanted to know how can i get the next generated auto number field in access database to put in java JTextField!
To get next number you can insert a "blank" row and use the number that was generated for it.
If your insert statement is stmt:
int nextKey = 0;
ResultSet keys = stmt.getGeneratedKeys();
if (keys.next())
{
nextKey = keys.getInt(1);
}
See statement.getGeneratedKeys()
Alternatively you could generate new id number with
SELECT MAX(id)+1 FROM yourTable
though this doesn't guarantee that the number will stay unused (by some other query) before you do anything with it.

JTable not showing the column names set in the AS part of the SQL prepared statement

I know how to manually set JTable column names, but wondering if there was better way because presently I have a prepared sql statement which selects from DB with column names made to show up as different name using the AS 'New Column Name', but the names in the AS part are not showing up, just the standard DB column names... Is that supposed to work that way or is there a better way apart from manually setting column header names using the getColumnModel().getColumn(2).setHeaderValue("NEW NAME") ... ? Thanks
The ResultSetMetaData method getColumnLabel() should provide the text from a given SELECT AS label. For example,
PreparedStatement ps = conn.prepareStatement("SELECT name AS moniker, …");
ResultSet rset = ps.executeQuery();
while (rset.next()) {
String name = rset.getString(1);
System.out.println(rset.getMetaData().getColumnLabel(1)+ ": " + name …);
}

SQL insert statement without defining data types

I was asked by a local school to write a database export utility to export data from a popular school management program to one that the government requires. The reason being that the government only accepts quarterly reports from its own program.
After ALLOT of hours spent just figuring out the relationships in the poorly written government database I finally compiled my SQL statement requirements but I have a problem.
Due to the poor design and use of data types and columns in the program I am having trouble dynamically putting together the SQL insert statements. Is there a way to create a single SQL statement with the data (formatted correctly) without specifying the data type and insert it into the table?
To give you an Idea there are 192 tables with at least 20 columns each.
Update: This is how my program currently works.
Collect data->Compare required column data type in excel sheet->Format data->Generate SQL Statement->Execute statement
you can quote everything so it will be passed as string. Of course, the data types must mach:
create table testDataType(
myInt int,
myDateTime datetime,
myfloat numeric(5,2))
insert into testDataType values ('1','01/01/2012','5.3')
(1 row(s) affected)
Loop through using the datatypes from the metadata. If it isn't an array of variants and it is string you will have to add in parseInt or something similar.
String selectStatement = "insert into wide_table (b1,b2,b3....) values (?,?,?.....) ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
ResultSet rs = stmt.executeQuery("SELECT top 1 * FROM WIDE_TABLE");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
for(int i =0;i<numerOfColumns;i++)
{
String x = rsmd.getColumnType(numerOfColumns)
if(x.equals("varchar"))
{
prepStmt.setString(numerOfColumns, data[numerOfColumns]);
}
else if(x.equals("int"))
{
prepStmt.setInt(numerOfColumns, data[numerOfColumns]);
}
....
}
ResultSet rs2 = prepStmt.executeQuery();

Categories

Resources