Using a HashMap to store database table & column names - java

I have some code that retrieves table & column names from a database:
PreparedStatement p = conn.prepareStatement(
"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'SQLUser'");
rs = p.executeQuery();
I was thinking that I could use a HashMap to store this data, where the key is the table name (which is always unique) and an ArrayList to store the list of columns contained within that table.
How can I iterate through the ResultSet so that for each table a new ArrayList is created, populated with related column names and then added to the HashMap using that table name as the key?

You can use something like this:
Map<String, List<String>> map = new HashMap<String, List<String>>();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
String table = rs.getString("table_name"));
ArrayList<String> columns = map.get(table);
if (columns == null) {
columns = new ArrayList<String>();
map.put(table, columns)
}
columns.add(rs.getString("column_name"));
}

Your code should look like this -
Map<String, List<String>> tableMap = new HashMap<String, List<String>>();
ArrayList<String> columnList = new ArrayList<String>();
PreparedStatement p = conn.prepareStatement(
"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'SQLUser'");
ResultSet rs = p.executeQuery();
while (rs.next()) {
String columnName = rs.getString("COLUMN_NAME"));
columnList.add(columnName);
}
tableMap.put("SQLUser", columnList);
Also you can use the ResultSetMetaData to get the column names from a table.
ResultSet resultSet = st.executeQuery("Select * from SQLUser")
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount();
List<String> columnList = new ArrayList<String>();
for (int i = 1; i <= count; i++) {
columnList.add(metaData.getColumnLabel(i)));
}

Related

How to check if a column in TableView is PrimaryKey(ResultSet) and make the cells not editable

How is possible to check if a column taken using ResultSet is a primary or not and if it a Primary than to make cells of this column not editable.Im using JavaFX.
Im using this code but it doesn't work...Thank you!
ObservableList<String> column = FXCollections.observableArrayList();
HashSet<String> set = new HashSet();
DatabaseMetaData meta = conn.getMetaData();
tblTable.getColumns().clear();
ResultSet cols = meta.getColumns(comboDatabase.getValue(), null, cmbTable.getValue(), null);
ResultSet pk = meta.getPrimaryKeys(comboDatabase.getValue(), null,cmbTable.getValue());
while (pk.next()) {
String primarykey = pk.getString("COLUMN_NAME");
set.add(primarykey);
}
while (cols.next()) {
String name = cols.getString("COLUMN_NAME");
TableColumn col = new TableColumn(name);
column.add(name);
tblTable.getColumns().addAll(col);
if(set.contains(column)){
col.setCellFactory(TextFieldTableCell.forTableColumn());
col.setEditable(false);
tblTable.setEditable(true);
System.out.println("1");
}else{
col.setCellFactory(TextFieldTableCell.forTableColumn());
col.setEditable(true);
tblTable.setEditable(true);
System.out.println("2");
}

Iterate 2D array of ResultSet to JTable

I have a resultset class that all of the query operations are stored. My problem is thatI am trying to fill a jtable with resultset data but I am only able to display the data in one column where I have three. This is the snippet of the resultset class:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
List<String> id = new ArrayList<>();
List<String> item = new ArrayList<>();
List<String> supplier = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
//metaData = rs.getMetaData();
//int columnNum = metaData.getColumnCount();
while(rs.next()){
id.add(String.valueOf(rs.getInt("id")));
item.add(rs.getString("ItemDesc"));
supplier.add(rs.getString("Supplier"));
}
values.add(id);
values.add(item);
values.add(supplier);
return values;
}
and this is the jtable method that I am trying for hours to solve:
public static DefaultTableModel loadTable(){
ModelDB model = null;
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Fabric");
tableModel.addColumn("Supplier");
try{
List<String> id = model.getAllFabrics().get(0);
List<String> item = model.getAllFabrics().get(1);
List<String> supplier = model.getAllFabrics().get(2);
//System.out.println(model.getAllFabrics().size()); tableModel.addRow(new Object[]{subRow});
for(List<String> row:model.getAllFabrics()){
tableModel.addRow(new Object[]{id,item,supplier});
}
}catch(SQLException ex){
ex.printStackTrace();
}
return tableModel;
}
I can't find a way to iterate the values to display in their respective column.
Original answer
You are almost there! You only need to change the loop:
for(int i = 0; i < id.size(); i++) {
tableModel.addRow(new Object[] {id.get(i),item.get(i),supplier.get(i)});
}
But as said in the comments, you should consider changing to an array of rows, not columns.
Edit
This is one approach. It is basically same as your code except the rows/columns are interchanged so the method returns a List of rows, not columns:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
List<String> row = new ArrayList<>();
row.add(String.valueOf(rs.getInt("id")));
row.add(rs.getString("ItemDesc"));
row.add(rs.getString("Supplier"));
// Now row contains {id, item, supplier}
values.add(row);
}
return values;
}
Then in your loadTable() method change to:
...
try{
for(List<String> row: model.getAllFabrics()){
tableModel.addRow(row.toArray(new String[row.size()]);
}
...
In your original code you call model.getAllFabrics() multiple times to get the return value. This is not good because every time you do that the method gets called and it needs to make the SQL-request again etc. Store the return value in a variable instead. In this case though as the return value is only accessed once you can equally just do as I described above.
Hope this helps :)

ResultSet to Array

I have a Result set returned using a query:
String query = "select Bookname, SubjectName from books join Subjects on Subjects.SubjectID = Books.subjectID where classID = '1a'";
ResultSet temp = null;
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
temp = rs;
}
I was just wondering is it possible to turn the Resultset into two seperate arrays: eg BookName[] and BookSubject[] so I can show them in a list view later on? Relatively new to resultset and this concept in android
You should be able to easily iterate through the results on the result set, populating each array with the results as you interate.
Something like this:
...
ResultSet rs = st.executeQuery(query);
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> subjects = new ArrayList<String>();
while (rs.next()) {
names.add(rs.getString(1));
subjects.add(rs.getString(2));
}
// finally turn the array lists into arrays - if really needed
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
String[] subjectArr = new String[subjects.size()];
subjectArr = subjects.toArray(subjectArr);
Hope that helps!

How can i pass output associative array of pl/sql to java?

For Nested table i have done it in follwing way?
This is pl/sql stored procedure.
CREATE or REPLACE PROCEDURE TEST(
activationStartDate IN DATE,
activationEndDate IN DATE,
deActivationStartDate IN DATE,
deActivationEndDate IN DATE
Out_Entity OUT TEST1.RefCsr
)
AS
FirstNameListTable LIST_TABLE;
{--COMMENT :LIST_TABLE is nested table :create or replace TYPE "LIST_TABLE" as table of varchar2(20);-----Nested Table Declaration
/
}
totalSameFirstName NUMBER;
j NUMBER := 1;
BEGIN
SELECT first_name BULK COLLECT INTO FirstNameListTable FROM Employee where start_date between activationStartDate AND activationEndDate
MINUS
SELECT first_name FROM Employee where start_date between deActivationStartDate AND deActivationEndDate
OPEN Out_Entity FOR SELECT * FROM TABLE(
CAST (
FirstNameListTable AS LIST_TABLE
)
) Nos;
END;
/
My JavaCode is
--First getConnection
--prepare sql string : sql = "{ Call Test(?,?,?,?,?) } ";
--Use prepareCall function on Connection object and passed this sql string and retrived CallableStatement class object.
stmt.setTimestamp(1,activationStartDate);
stmt.setTimestamp(2,activationEndDate);
stmt.setTimestamp(3,deActivationStartDate);
stmt.setTimestamp(4,deActivationEndDate);
stmt.registerOutParameter(5,-10);
stmt.execute();
List result = new ArrayList();
ResultSet rs = (ResultSet)stmt.getObject(5);
int i=0;
while (rs.next())
{
System.out.println(i+". "+rs.getString(1));
i++;
}
Then what if i want to select more than one column from EMPLOYEE and pass to my javaCode......How my javaCode and Pl/Sql will look like?
you need to use nest loop
for example in the result set get the column count value
and try like this
List<List> result = new ArrayList()<List>;
List col = new ArrayList();
ResultSet rs = (ResultSet)stmt.getObject(5);
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
while (rs.next())
{
col = new ArrayList();
for(int j=1;j<numberOfColumns;j++)
col.add(rs.getString(j);
result.add(col);
}
here first loop for getting the rows and the nested loop to getting the columns value
this value are store in the col list object and need to each time create new object

Resultset To List

I want to convert my Resultset to List in my JSP page. and want to display all the values. This is my query:
SELECT userId, userName
FROM user;
I have executed that using preparedstatement and got the Resultset. But how to convert it as a List and want to display the result like this:
userID userName
------------------
1001 user-X
1006 user-Y
1007 user-Z
You need to iterate over the ResultSet object in a loop, row by row, to pull out each column value:
List ll = new LinkedList();
ResultSet rs = stmt.executeQuery("SELECT userid, username FROM USER");
// Fetch each row from the result set
while (rs.next()) {
int i = rs.getInt("userid");
String str = rs.getString("username");
//Assuming you have a user object
User user = new User(i, str);
ll.add(user);
}
You could always use Commons DbUtils and the MapListHandler. From the doc:
ResultSetHandler implementation that
converts a ResultSet into a List of
Maps
so it'll take a lot of boilerplate code out of your hands.
A ResultSet should never get as far as a JSP. It should be mapping into a data structure or object and closed inside the method scope in which it was created. It's a database cursor, a scarce resource. Your app will run out of them soon if you persist with such a design.
var rs = stmt.executeQuery();
List<Map<String, Object>> result = new ArrayList<>();
while (rs.next()) {
Map<String, Object> resMap = new HashMap<>();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
resMap.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
}
result.add(resMap);
}
You can make a list of lists.
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
List row = null;
List table = new List();
while(rs.next())
{
for(int i = 0; i < n; i++)
row.add(rs.next(i);
tabla.add(row)
}

Categories

Resources