Fill array list with object of String[] with SQL table - java

I'm currently trying to fill an array list with an object of String[] with a SQL table. I was able to get the headers of my tables using this code.
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
int i = 1;
while (colCount >= i) {
String header = rsmd.getColumnName(i);
field.add(header);
i++;
However, when I'm trying to create my rows to fill the table, the array is not adding to the array list.
while (rs.next()) {
String[] row = new String[colCount];
for (int j = 0; j <= colCount; j++) {
row[j] = rs.getString(j+1);
}
data.add(row);
}
} catch (SQLException ex) {
}
System.out.println(data.size());
For some reason when I put the "data.add(row);" statement in the for loop, it only shows the same row however many times it loops. But it doesn't work outside of the for (I want to put it after the for loop inside the while). I'm outputting the size of the list to the console and it just returns 0.

String[] row = new String[colCount];
for (int j = 0; j <= colCount; j++) {
row[j] = rs.getString(j+1);
}
data.add(row);
Dear my friends, why did you decided to write "j <= colCount" meanwhile you had created "j = 0". So your code is going to throw "SqlException". Because index of last element of result set is "colCount", but your loop passed index equals to j + 1. it means equal "colCount + 1".
As you know, you try catch SQLException but you don't do anything. So your code has been failed when first row of resultset and j = colCount + 1. It can't add anything.

Related

Read excel and Assign cell Value by column to an array

Using apache.poi, I am trying to read an Excel sheet and using the below code, I am printing all the values inside Excel..
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
// Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
// Print Excel data in console
String location = (row.getCell(j).getStringCellValue()+ "");
System.out.println(location);
}
When I print the location System.out.println(location);, it prints my all Excel sheet data. I haven't any control over there. I am trying divide the value by the column.
Suppose I have 3 cells and I want to get a value like firstname[],lastname[],age[] so that I can do any operation by the indexing. I am not getting any solution.
Here is my full code
https://codeshare.io/anNwy3
Create a 2D String array. When iterating store the contents into the array
String[][] excelData = new String[numColumns][searcsheet.getLastRowNum()];
//numColumns is the number of columns in the excel sheet.
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
String data = (row.getCell(j).getStringCellValue()+ "");
excelData[j][i] = data;
}
}
This transpose data when storing it into the array (note: excelData[j][i] and not excelData[i][j]).
With this, you can get all the contents of the first column as excelData[0].

Displaying the string values of 2 dimensional Object array

I am trying to display the contents of an array after iterating through rows and columns of a JTable. I tried Arrays.toString(myTwoDimensionalArrayVariable) but it won't display the string values.
My goal is to check duplicates for every column per row of a destination JTable when user tries to add row values from a source JTable that's why I want to display the contents of the array.
The values on columns are combination of double, String, and int.
int myRowCount = aJTableParameter.getRowCount();
int myColumnCount = aJTableParameter.getColumnCount();
Object[][] myRowValues = new Object[myRowCount][myColumnCount];
for (int j = 0; j < myRowCount; j++) {
for(int i = 0; i< myColumnCount; i++){
myRowValues[j][i] = aDestinationTable.getValueAt(j, i);
}
}
System.out.println(Arrays.toString(myRowValues));
if (Arrays.asList(myRowValues).contains(column1Value)
&& Arrays.asList(myRowValues).contains(column2Value)
&& Arrays.asList(myRowValues).contains(column3Value)
&& Arrays.asList(myRowValues).contains(column4Value)) {
JOptionPane.showMessageDialog(null, "Duplicate, try again.");
}else{
//do something else
}
I only get this output:
run:
Successfully recorded login timestamp
[]
[[Ljava.lang.Object;#35fa3ff2]
[[Ljava.lang.Object;#407c448d, [Ljava.lang.Object;#1e78a60e]
Is there any other alternative than using 2 Dimensional Arrays?
I'd appreciate any help.
Thanks.
IFF your JTable cells contain only Strings, you can define your array as String[][] instead of Object[][] and fill it with your JTable contents using aDestinationTable.getValueAt(j, i).toString().
EDIT: since that's not the case (as per your comment), it's probably better to use a List, like this:
List<List<Object>> objectList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
objectList.add(j, new ArrayList<>());
for (int i = 0; i < 2; i++) {
if (i==0) objectList.get(j).add("string" + j + i);
if (i==1) objectList.get(j).add((double) 37.8346 * j * i);
}
}
System.out.println("OBJECT LIST: "+objectList);
Output:
OBJECT LIST: [[string00, 0.0], [string10, 37.8346]]
Your code should look like this, then:
List<List<Object>> myRowValues = new ArrayList<>();
for (int j = 0; j < myRowCount; j++) {
myRowValues.add(j, new ArrayList<>());
for (int i = 0; i < myColumnCount; i++) {
myRowValues.get(j).add(aDestinationTable.getValueAt(j, i));
}
}
System.out.println(myRowValues);

Displaying duplicate results in arraylist java

I am using JDBC to run a SQL query in Java. I want to take the result of the query and store it in an arraylist so that I can display the data in a graph of some sort. I'm getting the same line printing out the same number of times as columnCount. Here is my code.
ArrayList <String[]> result = new ArrayList<String[]>();
int columnCount = rset.getMetaData().getColumnCount();
if(rset!=null)
{
while(rset.next())
{
found=true;
String[] row = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = rset.getString(i + 1);
row[i] = rset.getString("Date") + " "
+ rset.getString("Hour");
System.out.println(row[i]);
}
result.add(row);
}
Your second row[i] rewrites the value of the column. Just remove it and you'll see your records:
...
for (int i = 0; i < columnCount; i++) {
row[i] = rset.getString(i + 1);
}
System.out.println(Arrays.toString(row));
result.add(row);
...

How to get ResultSet for loop to be more efficient

In a ResultSet from either Oracle,MySQl or MSSQL, how can you make the resultset for loop quicker?
while (rs.next()) {
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
rs.getString(i)
}
}
This works great as long as you don't have to many columns, but as soon as you have for example 90 columns and 100 000 rows, then this for loops goes trough 100 000 rows 90 times.
One thing to try would be to just get the column count once:
int colCount = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 0; i < colCount; i++) {
rs.getString(i)
}
}

Error in passing SQL command through a prepared statement via jdbc

I am trying to create table where the program gets the number of rows and columns during runtime.
Here's the code:
String sql =
"CREATE TABLE if not exists itemset (?";
up1 = con.prepareStatement(sql);
for(int j=1; j < ccolumns; j++) {
sql += ",?";
}
sql += ")";
System.out.println(sql);
for(int j=1; j < ccolumns+1; j++) {
System.out.println(j);
up1.setString(j, "item"+j+" TINYINT(10)");
}
up1.executeQuery();
The error is
Parameter index out of range (2 > number of parameters, which is 1)
It occurs in the setString line during the second iteration
Try to move
up1 = con.prepareStatement(sql);
After
System.out.println(sql);
Though I didn't verify it, I believe that Andriy's answer is correct. Additionally, you may want to consider using a StringBuilder for String accumulation, as they are lighter-weight. Updated code below.
StringBuilder sql = new StringBuilder("CREATE TABLE if not exists itemset (?");
for (int j = 1; j < ccolumns; j++) {
sql.append(",?");
}
sql.append(")");
System.out.println(sql.toString());
up1 = con.prepareStatement(sql.toString());
for (int j = 1; j < ccolumns + 1; j++) {
System.out.println(j);
up1.setString(j, "item" + j + " TINYINT(10)");
}
up1.executeQuery();
First thing what you want to fix is please don't use String instance when you want to change it. String intance is immutable and when you modify already created String, new modified instance is created and it is not free.
You should to use StringBuilder for this that have instance methods which allow to modify it without need to create new instance. I recommend to you use always StringBuilder when you modifying String. and second so you call con.prepareStatement(sql) and then you modify its sql field. it's not good is't?
So only add it after your work with String.
String sql =
"CREATE TABLE if not exists itemset (?";
for(int j=1; j < ccolumns; j++) {
sql += ",?";
}
sql += ")";
System.out.println(sql);
up1 = con.prepareStatement(sql);
for(int j=1; j < ccolumns+1; j++) {
System.out.println(j);
up1.setString(j, "item"+j+" TINYINT(10)");
}
up1.executeQuery();
You cannot call prepareStatement with given String and then modify it.
But more cleaner and faster try to do it like this
StringBuilder sqlStatement = new StringBuilder(
"CREATE TABLE if not exists itemset (?");
for(int j=1; j < ccolumns; j++) {
sqlStatement.append(",?");
}
sqlStatement.append(")");
up1 = con.prepareStatement(sqlStatement.toString());
for(int j=1; j < ccolumns+1; j++) {
System.out.println(j);
up1.setString(j, "item"+j+" TINYINT(10)");
}
up1.executeQuery();
PreparedStatement can't be used for DDL queries like the CREATE TABLE in the question.
The values passed to setString() get escaped in the resulting SQL, resulting in an invalid query sent to the database.
When only the number of columns is given, just create the CREATE TABLE statement (use a StringBuilder as others suggested) and execute it with a plain Statement, no need for a PreparedStatement:
String getCreateTableSql(int columns) {
StringBuilder sql = new StringBuilder("CREATE TABLE IF NOT EXISTS itemset (");
for (int i = 0; i < columns; i++) {
if (i > 0) {
sql.append(", ");
}
sql.append("item").append(i + 1).append(" TINYINT(10)");
}
sql.append(")");
return sql.toString();
}
For 4 columns, this will output:
CREATE TABLE IF NOT EXISTS itemset (item1 TINYINT(10), item2 TINYINT(10), item3 TINYINT(10), item4 TINYINT(10))

Categories