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))
Related
I'm trying to compare elements in an array. When I use a variable within a loop, I get an out of bounds error. Yet when I use explicit values in place of the variables, with the same value, it works fine.
What am I missing?
The problem line is:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
But if I use this, it works (values should be identical):
int result = (myList[0]).compareToIgnoreCase(myList[1]);
Have searched high and dry for this. Other posters had different issues. Would appreciate any input! Here's the example with dummy content:
public class methodSortTest
{
public static void main(String[] args)
{
// Create and load data into array
String[] myList = new String[2];
myList[0] = "Charlie";
myList[1] = "Bravo";
// Compare, positive/negative
for (int j = 0; j < myList.length; j++)
{
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
System.out.println("Result is: " + result);
}
}
}
Try this:
change this:
for (int j = 0; j < myList.length; j++)
to this:
for (int j = 0; j < myList.length-1; j++)
problem is inside this statement:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
because you are accessing the j+1
Simple Helping material:
https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/
When j equals 1, myList[j + 1] evaluates to myList[2] which throws an ArrayIndexOutOfBoundsException. There is no item at index 2 because you have only inserted items at index 0 and 1.
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
Change your for loop from
for (int j = 0; j < myList.length; j++)
To
for (int j = 0; j < myList.length-1; j++) // note the "-1"
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);
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);
...
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.
Please give me a hand to tell me why second for loop 'row' could not be found in the printSeating Method.
public void printSeating()
{
for (int row = FIRST_ROW_NUMBER; row <= firstClass.length; row++)
{
if (row < 10)
System.out.print(" ");
System.out.print(row);
System.out.println(":" + firstClass[row - FIRST_ROW_NUMBER]);
}
int firstEconomyRowNumber = FIRST_ROW_NUMBER + firstClassRowCount;
int lastEconomyRowNumber = firstEconomyRowNumber + economyRowCount - 1;
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++);
{
if (row < 10)
System.out.print(" ");
System.out.print(row);
System.out.println(":" + economy[row - firstEconomyRowNumber]);
}
}
When declaring the FOR loop, you put a semicolon after the loop, like this:
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++);{
//..insert code here
}
This declares a FOR loop without a body, so when you access the variable row after this statement, it cannot find the variable because it can only be used in the non-existent body of the FOR loop. To fix this, you would need to delete the semicolon, like so:
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++){
//...insert code here
}
This is your error.
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++);
get rid of that ; after the for loop and it should work.