How to display all rows in Java using JTable? [solved] - java

I would like to ask how to display all rows in Java using JTable.
I tried using a while condition inside is a result.next() to be evaluated.
I tried printing it using System.out.println and it display all records however when I tried it on JTable it only displays the last row.
while(results.next()) {
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][]){
{id, date_collected, date_disposed, person_in_charged, status}
},
new String [] {
"ID", "Date collected", "Date disposed", "person in charged",
"status"
}
));
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
}
}
Can you help me? Thanks!
Summary of the solution:
Solved by Usagi Miyamoto and isaace
The solution was to create the List this way
List<Object[]> data = new ArrayList<>()
Reason:
List is an interface, an abstract, and cannot be instantiated directly
ArrayList is a class that implements List
Complete solution of Usagi Miyamoto
// to hold the data
List<Object[]> data = new ArrayList<>();
// loop through the ResultSet
while(results.next())
{
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
// add a new row of data
data.add(new Object[] {id, date_collected, date_disposed, person_in_charged, status});
}
// after the loop: set the data as the model
jTable1.setModel(new javax.swing.table.DefaultTableModel(
// convert from List to array
data.toArray(new Object[][data.size()],
// column headers
new String [] { "ID", "Date collected", "Date disposed", "person in charged", "status" }
));
// other details from your code: moved outside of the loop...
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0)
{
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
}

Try cumulating the data, something like this:
// to hold the data
List<Object[]> data = new ArrayList<>();
// loop through the ResultSet
while(results.next())
{
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
// add a new row of data
data.add(new Object[] {id, date_collected, date_disposed, person_in_charged, status});
}
// after the loop: set the data as the model
jTable1.setModel(new javax.swing.table.DefaultTableModel(
// convert from List to array
data.toArray(new Object[][data.size()],
// column headers
new String [] { "ID", "Date collected", "Date disposed", "person in charged", "status" }
));
// other details from your code: moved outside of the loop...
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0)
{
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(3).setResizable(false);
}

The DefaultTableModel should be created and set outside of the loop.
DefaultTableModel model = new DefaultTableModel();
model.addColumn("you column names");
model.addColumn("another column name");
//you can add all your column headers here
JTable table = new JTable();
table.setModel(model);
while(rs.next())
{
String id = results.getString("id");
String date_collected = results.getString("date_collected");
String date_disposed = results.getString("date_disposed");
String person_in_charged = results.getString("person_in_charged");
String status = results.getString("status");
model.addRow(new Object[]{id, date_collected, date_disposed, person_in_charge, status });
}
and continue with the rest of your code here.

Related

Is It possible to change value of Range key in DynamoDB Table?

I know it may be a very silly question, but I am new to DynamoDB.
My doubt is is it possible to update the value of a Range Key in DynamoDB.
Suppose My Table is "TEST"
{
ID : PK/HK
Date : RK
Name : GSI
Add : LSI
}
I want to modify Date Attribute.
Initial Values in Table was:
{
ID = "344"
Date = "5656"
Name = "ABC"
}
Running this code below. I am able to change the Name Attribute which is GSI.
Map<String,AttributeValue> item = new HashMap<String,AttributeValue>();
item.put("ID", new AttributeValue("344"));
item.put("Date", new AttributeValue("5656"));
Map<String,AttributeValueUpdate> item1 = new HashMap<String,AttributeValueUpdate>();
AttributeValueUpdate update = new AttributeValueUpdate().withValue(new AttributeValue("AMIT")).withAction("PUT");
item1.put("Name", update);
UpdateItemRequest updateItemreq = new UpdateItemRequest("Test",item,item1);
UpdateItemResult updateItemres = dynamoDBUSEast.updateItem(updateItemreq);
But When I change this line
item1.put("Name", update);
with
item1.put("Date", update);
I am getting some error as
Exception in thread "main" com.amazonaws.AmazonServiceException: One or more parameter values were invalid: Cannot update attribute Date. This attribute is part of the key (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: HRRP24Q7C48AMD8ASAI992L6MBVV4KQNSO5AEMVJF66Q9ASUAAJG)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:820)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:439)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:245)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:2908)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:1256)
So Is it possible to change the range Key value?
No, like the exception message states, you Cannot update attribute Date. This attribute is part of the key.
You can also see this under the AttributeUpdates documentation:
The names of attributes to be modified, the action to perform on each,
and the new value for each. If you are updating an attribute that is
an index key attribute for any indexes on that table, the attribute
type must match the index key type defined in the AttributesDefinition
of the table description. You can use UpdateItem to update any nonkey
attributes.
The documentation states that you can update any attribute for "an attribute that is an index key attribute for any indexes on that table", which means that when you update an attribute that is projected onto an index, even it is is part of that indexes key, that index will also be updated to reflect the original item.
From the docs of AttributeValueUpdate
You cannot use UpdateItem to update any primary key attributes.
Instead, you will need to delete the item, and then use PutItem to
create a new item with new attributes.
It's a little buried but in docs for UpdateItem it says:
"You can use UpdateItem to update any nonkey attributes."
So, currently the only way to update the primary key of an item is to delete the old item and write a new one.
Here is my implementation of updating id in .net by deleting the item and then recreating it with the new id. I assume java is very similar:
// Based on https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemsExample.html
public class UpdateId
{
private static string tableName = "MyTableName";
private static AmazonDynamoDBClient client = new AmazonDynamoDBClient();
private static bool isVerbose = false;
public static void ChangeId(string currentId, string newId)
{
try
{
var deletedItem = DeleteItem(currentId);
if (deletedItem.Count == 0)
{
Console.WriteLine($"ERROR: Item to delete not found: {currentId}");
return;
}
deletedItem["Id"] = new AttributeValue
{
S = newId
};
CreateItem(deletedItem);
var updatedItem = RetrieveItem(newId);
if (updatedItem.Count > 0 && updatedItem["Id"].S == newId)
{
Console.WriteLine($"Item id successfully changed from ({currentId}) to ({newId})");
}
else
{
Console.WriteLine($"ERROR: Item id didn't change from ({currentId}) to ({newId})");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("To continue, press Enter");
Console.ReadLine();
}
}
private static void CreateItem(Dictionary<string, AttributeValue> item)
{
var request = new PutItemRequest
{
TableName = tableName,
Item = item
};
client.PutItem(request);
}
private static Dictionary<string, AttributeValue> RetrieveItem(string id)
{
var request = new GetItemRequest
{
TableName = tableName,
Key = new Dictionary<string, AttributeValue>()
{
{ "Id", new AttributeValue {
S = id
} }
},
ConsistentRead = true
};
var response = client.GetItem(request);
// Check the response.
var attributeList = response.Item; // attribute list in the response.
if (isVerbose)
{
Console.WriteLine("\nPrinting item after retrieving it ............");
PrintItem(attributeList);
}
return attributeList;
}
private static Dictionary<string, AttributeValue> DeleteItem(string id)
{
var request = new DeleteItemRequest
{
TableName = tableName,
Key = new Dictionary<string, AttributeValue>()
{
{ "Id", new AttributeValue {
S = id
} }
},
// Return the entire item as it appeared before the update.
ReturnValues = "ALL_OLD",
// ExpressionAttributeNames = new Dictionary<string, string>()
// {
// {"#IP", "InPublication"}
// },
// ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
// {
// {":inpub",new AttributeValue {
// BOOL = false
// }}
// },
// ConditionExpression = "#IP = :inpub"
};
var response = client.DeleteItem(request);
// Check the response.
var attributeList = response.Attributes; // Attribute list in the response.
// Print item.
if (isVerbose)
{
Console.WriteLine("\nPrinting item that was just deleted ............");
PrintItem(attributeList);
}
return attributeList;
}
private static void PrintItem(Dictionary<string, AttributeValue> attributeList)
{
foreach (KeyValuePair<string, AttributeValue> kvp in attributeList)
{
string attributeName = kvp.Key;
AttributeValue value = kvp.Value;
Console.WriteLine(
attributeName + " " +
(value.S == null ? "" : "S=[" + value.S + "]") +
(value.N == null ? "" : "N=[" + value.N + "]") +
(value.SS == null ? "" : "SS=[" + string.Join(",", value.SS.ToArray()) + "]") +
(value.NS == null ? "" : "NS=[" + string.Join(",", value.NS.ToArray()) + "]")
);
}
Console.WriteLine("************************************************");
}
}
To call it just do this:
UpdateId.ChangeId("OriginalId", "NewId");

DefaultTableModel doesn't show columns

I have problem with DefaultTableModel it won't show me my columns in table, there is a part of code:
JTable table = new JTable() {
public boolean isCellEditable(int data, int columnNames) {
return false;
}
};
String columnNames[] = new String[] { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian", "asd", "asd" };
DefaultTableModel dtm = new DefaultTableModel(0, 0);
dtm.setColumnIdentifiers(columnNames);
table.setModel(dtm);
for (Reservation r : reservation) {
rez.add(new Reservation(r.getID(), r.getA(), r.getB(), r.getC(), r.getD(), r.getE(), r.getF()));
}
for (int i = 0; i < rez.size(); i++) {
int id = rez.get(i).getID();
String l = rez.get(i).getA();
String w = rez.get(i).getB();
String z = rez.get(i).getC();
String o = rez.get(i).getD();
String d = String.valueOf(rez.get(i).getE());
String g = rez.get(i).getF();
dtm.addRow(new Object[] { id, l, w, z, d,o,g });
}
JScrollPane sp = new JScrollPane(dtm);
add(table);
}
Im trying to make a dynamic table. Data will be from data base (posgreSQL) using hibernate, and thats fine, it work's but I cant see a column names from
String columnNames[] = new String[] { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian", "asd", "asd" };
Don't care about names of columns and name of getters i changed it for this post.
In addition I can't make it scrollable:
JScrollPane sp = new JScrollPane(dtm);
I'm not sure how this would be able to compile
JScrollPane sp = new JScrollPane(dtm);
add(table);
dtm is an instance of DefaultTableModel so it should never be possible to pass it to a JScrollPane,
Instead you should be using
JScrollPane sp = new JScrollPane(table);
add(sp);
See How to Use Tables and How to Use Scroll Panes for more details
Add the table rather than the TableModel to the JScrollPane
add(new JScrollPane(table));

How to use Column Generators in a Table Vaadin 7?

I have a problem in implementing ColumnGenerator in Vaadin. I am reading the Book of Vaadin, at chapter 5.21.5. Generated Table Columns, but it seems to be a little bit of lack of instructions in how actually you can implement such functionality.
The book says you need to use generated columns when e.g. you have a column which value is given by values of the other columns, or when you want to format table columns in a particular way, then it makes an incomplete example where only an implementation of a single ColumnGenerator is given without actually showing how when this generator is used when rows are added to the table.
So I tried to implement such functionality by myself, here is what I got:
// Generated Table columns
Table tableWithGeneratedCol = new Table();
tableWithGeneratedCol.addContainerProperty(
"date", Date.class, null, "Date", null, null);
tableWithGeneratedCol.addContainerProperty(
"quantity", Double.class, null, "Quantity (l)", null, null);
tableWithGeneratedCol.addContainerProperty(
"price", Double.class, null, "Price (e/l)", null, null);
tableWithGeneratedCol.addContainerProperty(
"total", Double.class, null, "Total (e)", null, null);
tableWithGeneratedCol.addGeneratedColumn("date", new DateColumnGenerator());
tableWithGeneratedCol.addGeneratedColumn("quantity", new ValueColumnGenerator("%.2f l"));
tableWithGeneratedCol.addGeneratedColumn("price", new PriceColumnGeneretor());
tableWithGeneratedCol.addGeneratedColumn("total",new TotalColumnGenerator("%.2f e", "quantity", "price"));
// adding some fake rows
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(), // date column
new Double(10), // quantity column
new Double(10), // price column
// nothing here // total column
}, 1); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(16.2), // quantity column
new Double(21.2), // price column
// nothing here // total column
}, 2); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(10), // quantity column
new Double(22), // price column
// nothing here // total column
}, 3); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(10), // quantity column
new Double(20), // price column
// nothing here // total column
}, 4); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(15), // quantity column
new Double(19.12), // price column
}, 5); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(10), // quantity column
new Double(20.30), // price column
// nothing here // total column
}, 6); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(50), // quantity column
new Double(32.89), // price column
// nothing here // total column
}, 7); // itemId
tableWithGeneratedCol.setVisibleColumns(new Object[] {"date", "quantity", "price", "total"});
tableWithGeneratedCol.setPageLength(tableWithGeneratedCol.size());
layout.addComponent(tableWithGeneratedCol);
This is a snippet from a UI's init() method. As you can see, I create a table with 4 columns, Date, Quantity, Price, and Total (which is given by multiplying Quantity * Price).
I add some fake rows and for the total column I actually don't add any value because it's value should be determined by quantity and price while the table rows are created (the book doesn't tell how you actually do that, so I am guessing how it should work).
Here are the Table.ColumnGenerator implementations (I use a DateColumnGenerator for the Date column, ValueColumnGenerator for the quantity, PriceColumnGenerator for the price column, TotalColumnGenerator for the total column). So in order:
DateColumnGenerator:
public class DateColumnGenerator implements ColumnGenerator {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Component generateCell(Table source, Object itemId, Object columnId) {
Property<?> prop = source.getItem(itemId).getItemProperty(columnId);
if (prop.getType().equals(Date.class)) {
Date date = (Date) prop.getValue();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy, HH:mm:ss");
return new Label(sdf.format(date));
}
return null;
}
}
ValueColumnGenerator (actually this is the only column generator implementation made by the book):
/** Formats the value in a column containing Double objects. */
class ValueColumnGenerator implements Table.ColumnGenerator {
/**
*
/
private static final long serialVersionUID = 1L;
String format; / Format string for the Double values. */
/**
* Creates double value column formatter with the given
* format string.
*/
public ValueColumnGenerator(String format) {
this.format = format;
}
/**
* Generates the cell containing the Double value.
* The column is irrelevant in this use case.
*/
public Component generateCell(Table source, Object itemId,
Object columnId) {
// Get the object stored in the cell as a property
Property<?> prop = source.getItem(itemId).getItemProperty(columnId);
if (prop.getType().equals(Double.class)) {
Label label = new Label(String.format(format, new Object[] { (Double) prop.getValue() }));
// Set styles for the column: one indicating that it's
// a value and a more specific one with the column
// name in it. This assumes that the column name
// is proper for CSS.
label.addStyleName("column-type-value");
label.addStyleName("column-" + (String) columnId);
return label;
}
return null;
}
}
I have just copied their code. So let's move forward.
PriceColumnGenerator:
public class PriceColumnGeneretor implements ColumnGenerator {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Component generateCell(Table source, Object itemId, Object columnId) {
Property<?> prop = source.getItem(itemId).getItemProperty(columnId);
if (prop.getClass().equals(Double.class)) {
Double price = (Double) prop.getValue();
String priceStr = String.format("%.2 €", price);
return new Label(priceStr);
}
return null;
}
}
And finally, PriceColumnGenerator:
public class TotalColumnGenerator implements Table.ColumnGenerator {
/**
*
*/
private static final long serialVersionUID = 1L;
protected String format;
protected String quantityId;
protected String priceId;
public TotalColumnGenerator(String format, String quantityId, String priceId) {
this.format = format;
this.quantityId = quantityId;
this.priceId = priceId;
}
#Override
public Component generateCell(Table source, Object itemId, Object columnId) {
Double quantity = (Double) source.getItem(itemId).getItemProperty(this.quantityId).getValue();
Integer price = (Integer) source.getItem(itemId).getItemProperty(this.priceId).getValue();
String res = String.format(this.format, new Double(quantity * price));
return new Label(res);
}
}
But the result is this beautiful empty table, as you can see from the screenshot:
Now, how can I actually make this column generators work?
Thank you for the attention!
Don't add properties with the same name as the generated columns.
This should be enough
// Generated Table columns
Table tableWithGeneratedCol = new Table();
tableWithGeneratedCol.addGeneratedColumn("date", new DateColumnGenerator());
tableWithGeneratedCol.addGeneratedColumn("quantity", new ValueColumnGenerator("%.2f l"));
tableWithGeneratedCol.addGeneratedColumn("price", new PriceColumnGeneretor());
tableWithGeneratedCol.addGeneratedColumn("total",new TotalColumnGenerator("%.2f e", "quantity", "price"));
// adding some fake rows
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(), // date column
new Double(10), // quantity column
new Double(10), // price column
// nothing here // total column
}, 1); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(16.2), // quantity column
new Double(21.2), // price column
// nothing here // total column
}, 2); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(10), // quantity column
new Double(22), // price column
// nothing here // total column
}, 3); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(10), // quantity column
new Double(20), // price column
// nothing here // total column
}, 4); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(15), // quantity column
new Double(19.12), // price column
}, 5); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(10), // quantity column
new Double(20.30), // price column
// nothing here // total column
}, 6); // itemId
tableWithGeneratedCol.addItem(new Object[] { new GregorianCalendar().getTime(),
new Double(50), // quantity column
new Double(32.89), // price column
// nothing here // total column
}, 7); // itemId
tableWithGeneratedCol.setVisibleColumns(new Object[] {"date", "quantity", "price", "total"});
tableWithGeneratedCol.setPageLength(tableWithGeneratedCol.size());
layout.addComponent(tableWithGeneratedCol);
There is problem with calling method addItem. If you use ColumnGeneretor do not add item into column which is generated by ColumnGenerator. This item must "generate" ColumnGenerator.

jTable get data from filtered rows

I want to retrieve some data from a filtered row.
This is how i filter my table :
String makeText = makeFilterCombo.getSelectedItem().toString();
if (makeText == "All") {
makeText = "";
}
String numar = getEssRegex();
String impact = impactBox.getSelectedItem().toString();
if (impact == "All") {
impact = "";
}
TableModel model;
model = jTable1.getModel();
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
jTable1.setRowSorter(sorter);
List<RowFilter<Object, Object>> rfs = new ArrayList<RowFilter<Object, Object>>(2);
rfs.add(RowFilter.regexFilter(makeText, 2));
rfs.add(RowFilter.regexFilter(numar, 5));
rfs.add(RowFilter.regexFilter(impact, 9));
RowFilter<Object, Object> af = RowFilter.andFilter(rfs);
sorter.setRowFilter(af);
And this is how i try to get a value from a filtered row:
int f = search(connectedCarIndex);
connectedImage1 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 10).toString();
connectedImage2 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 11).toString();
connectedImage3 = jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(f), 12).toString();
System.out.println(connectedImage1 + "-------" + connectedImage2 + "------" + connectedImage3);
But none of this works ?
Can anybody help me ?
The code works and i can see the connected image name if the rows are shown
int f = search(connectedCarIndex);
I have no idea what the search(...) method does.
If you are searching the data that is displayed in the table then you would just use:
table.getValueAt(...);
If you are searching all the data that is stored in the TableModel then you would use:
table.getModel().getValueAt(...);
there is no need to convert the index if you know what you are searching.

Single thread writing to different database with different connection parameters

I am working on a project in which I have three tables in a different database with different schemas. So that means I have three different connection parameters for those three tables to connect using JDBC-
Let's suppose-
For Table1-
Username:- A
Password:- B
URL: C
Columns-
ID1 String
Account1 String
For Table2-
Username:- P
Password:- Q
URL:- R
Columns-
ID2 String
Account2 String
For Table3-
Username:- T
Password:- U
URL:- V
Columns-
ID3 String
Account3 String
And I am supposed to insert in all the three tables or any one of them using JDBC.
Below are the three use cases I have-
From the command prompt if suppose I am passing Table1 only, then I am suppose to insert only in Table1 columns by making connection to
Table1.
And if I am passing Table1, Table2 from the command prompt then I am suppose to insert in both Table1 and Table2 columns by making
connection to Table1 and Table2.
And if I am passing Table1, Table2 and Table3 then I am suppose to enter in all the three tables using there respective connection
parameter
I am not able to understand how to write code for the above particular scenario in such a cleaner way so that it can be extended in near future as well if I come up with four tables. I can have a one constant file which can store the SQL that needs to be executed for any of the three tables and some other constant thing as well.
public static void main(String[] args) {
}
class Task implements Runnable {
private Connection dbConnection = null;
private PreparedStatement preparedStatement = null;
public Task() {
}
#Override
public void run() {
dbConnection = getDbConnection();
//prepare the statement and execute it
}
}
private Connection getDBConnection() {
Connection dbConnection = null;
Class.forName(Constants.DRIVER_NAME);
dbConnection = DriverManager.getConnection( , , );
return dbConnection;
}
Can anyone provide some thoughts on this how should I proceed forward?
Note:-
Column in each table will differ a lot. Like in some tables, column can be 10 and in some other table, column can be 20.
Create databases.properties file with content like this:
# Table 1
table1.url: jdbc:mysql://localhost:3306/garden
table1.user: gardener
table1.password: shavel
table1.table: fruits
table1.column.id: fruitID
table1.column.color: fruitColor
table1.column.weight: fruitWeight
# ... More fruit columns here ...
# Table 2
table2.url: jdbc:mysql://otherhost:3306/forest
table2.user: forester
table2.password: axe
table2.table: trees
table2.column.id: treeID
table2.column.height: treeHeight
# ... More tree columns here ...
# ... More tables here ...
Then do something like this:
public static void main (String [] args)
{
Properties databasesProperties = new Properties ();
databasesProperties.load ("databases.properties");
for (String arg: args)
{
String url = databasesProperties.get (arg + ".url");
String user = databasesProperties.get (arg + ".user");
String password= databasesProperties.get (arg + ".password");
String table = databasesProperties.get (arg + ".table");
String columnPrefix = arg + ".column."
Map <String, String> columns = new HashMap <String, String> ();
for (String key: databasesProperties.stringPropertyNames ())
{
if (key.startsWith (columnPrefix))
columns.put (
key.substring (columnPrefix.length ()),
databasesProperties.get (key));
}
doInsert (url, user, password, table, columns);
}
}
Later you can always add more tables into your databases.properties file.
Save your Database properties in a class file DBPropery.java.
final class DBProperty
{
static String[] urls = {
"C",
"R",
"V"
}; //You can add more URLs here.
static String[] driver= {
"Driver1",
"Driver2",
"Driver3"
};//You can add more drivers string
static String[] table = {
"Table1",
"Table2",
"Table3"
};//You can add more table names here According to URLs mentioned in urls array.
static String[] user = {
"A",
"P",
"T"
};//You can add more user names here according to URls mentioned in urls array.
static String[] pwd = {
"B",
"Q",
"U"
};//You can add more Password here according to URls mentioned in urls array.
static String[] queries = {
"Query for Table1",
"Query for Table2",
"Query for Table3",
};//You can add more queries here for more tables according to URls mentioned in urls array.
static int[] columns ={
2,
2,
2
};//You can change the column numbers according to need . 0th index belongs to Table1 , 1 to table2....so on.
//If you add more tables , add corresponding columns count to next index.
static String[] columnValues ={
"1^John",
"34^Vicky",
"65^Ethen"
};//String at each index represents a row in corresponding table in table[] array. each column is seperated by delimiter "^".
}
Make all Changes in DBProperty.java file.
Then proceed with following class file
import java.sql.*;
import java.util.*;
class MultiTableInsert implements Runnable
{
Map<String,Integer> columnsInTable;
Map<String,String> tableDriver;
Map<String,String> rowForTable;
Map<String,String> queryForTable;
Map<String,String> urlForTable;
Map<String,String> userForTable;
Map<String,String> pwdForTable;
String[] tables ;
public MultiTableInsert(String... tables)//Loading all Database Settings here..
{
this.tables = tables;
columnsInTable = new LinkedHashMap<String,Integer>();
rowForTable = new LinkedHashMap<String,String>();
tableDriver = new LinkedHashMap<String,String>();
urlForTable = new LinkedHashMap<String,String>();
userForTable= new LinkedHashMap<String,String>();
pwdForTable = new LinkedHashMap<String,String>();
for (int i = 0 ; i < DBProperty.urls.length ; i++ )
{
try
{
tableDriver.put(DBProperty.table[i],DBProperty.driver[i]);
queryForTable.put(DBProperty.table[i],DBProperty.queries[i]);
columnsInTable.put(DBProperty.table[i],DBProperty.columns[i]);
rowForTable.put(DBProperty.table[i],DBProperty.columnValues[i]);
urlForTable.put(DBProperty.table[i],DBProperty.urls[i]);
userForTable.put(DBProperty.table[i],DBProperty.user[i]);
pwdForTable.put(DBProperty.table[i],DBProperty.pwd[i]);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
#Override
public void run()
{
insertIntoTable(tables);
}
private void insertIntoTable(String... tables)
{
for (String tble : tables )
{
Connection con = null;
PreparedStatement pStmt = null;
try
{
Class.forName(tableDriver.get(tble));
con = DriverManager.getConnection(urlForTable.get(tble),userForTable.get(tble),pwdForTable.get(tble));
pStmt = con.prepareStatement(queryForTable.get(tble));
int columns = columnsInTable.get(tble);
String sRow = rowForTable.get(tble);
StringTokenizer tokenizer = new StringTokenizer(sRow,"^");
for (int i = 0; i < columns ; i++)
{
pStmt.setString(i+1,(String)tokenizer.nextElement());
}
pStmt.execute();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
con.close();
}catch (Exception ex){}
try
{
pStmt.close();
}catch (Exception ex){}
}
}
}
public static void main(String[] args)
{
int length = args.length;
int THREAD_COUNTS = 10;//Number of threads you want to start.
switch (length)
{
case 0:
System.out.println("Usage: javac MultiTableInsert Table1/Table2/Table3 <Table1/Table2/Table3> <Table1/Table2/Table3>");
System.exit(0);
case 1:
for (int i = 0 ; i < THREAD_COUNTS ; i++)
{
MultiTableInsert mti = new MultiTableInsert(args[0]);
Thread th = new Thread(mti,"Thread"+i);//Create New Thread
th.start(); //Start Thread
}
break;
case 2:
for (int i = 0 ; i < THREAD_COUNTS ; i++)
{
MultiTableInsert mti = new MultiTableInsert(args[0],args[1]);//Create New Thread
Thread th = new Thread(mti,"Thread"+i); //Start Thread
th.start();
}
break;
default:
for (int i = 0 ; i < THREAD_COUNTS ; i++)
{
MultiTableInsert mti = new MultiTableInsert(args[0],args[1],args[2]);//Create New Thread
Thread th = new Thread(mti,"Thread"+i); //Start Thread
th.start();
}
break;
}
}
}

Categories

Resources