i want to add all my data from DB to jtable, but using this code i get only the last row from DB, added to the table severelal times.
Can someone tell where is mistake?
public Vector getOrder() throws Exception
{
DbConnection();
Statement st = null;
ResultSet res =null;
String query="Select * From Orders;";
try{
st=connect.createStatement();
res=st.executeQuery(query);
Vector v =new Vector();
Vector<String> record = new Vector<String>();
int i=0;
while(res.next())
{
record.clear();
uzsakNr=res.getString("Uzsakymo_nr");
priemDat=res.getString("Priemimo_data");
irengPav=res.getString("Irenginio_pavadinimas");
model=res.getString("Modelis");
status=res.getString("Statusas");
grazDat=res.getString("Grazinimo_data");
clientId=Long.toString(res.getLong("ClientId"));
//record.addElement(i);
record.addElement(uzsakNr);
record.addElement(priemDat);
record.addElement(irengPav);
record.addElement(model);
record.addElement(status);
record.addElement(grazDat);
record.addElement(clientId);
//record.addElement("");
v.addElement(record);
i++;
}
//Zle vydaji, daji tyko trzy takiesame ostatnie
System.out.println(v);
return v;
}finally {
if(res!=null) res.close();
if(st!=null) st.close();
}
}
in another class
try{
Vector ve=db.getOrder();
String heading[]={"uzsakNr","priemDat","irengPav","model","status","grazDat","ClientID"};
Vector columnHeads= new Vector();
for (int i=0;i<heading.length; i++)
columnHeads.addElement(heading[i]);
table = new JTable(ve,columnHeads);
table.addMouseListener(new TableMouseListener());
scrollPane.setViewportView(table);
UzsakPanel.add(scrollPane);
scrollPane.setBounds(10, 10, 901, 200);
}catch(Exception e2){e2.printStackTrace();}
Firstly,
Replace the line containing clear() with Vector<String> record = new Vector<String>();
Secondly, I think what you're doing is probably correct but your printing is the problem.
Since you have a vector of vectors containing strings, I would print it like so
for(Vector stringVect : v) {
for(String s : stringVect) {
System.out.print(s+ '\t');
}
System.out.println();
}
Related
I am still developing stock management system with netbeans ide using java. In one interface I have three different jtables, one for current materials quantity in stock, one for required materials quantity for fulfill order, and other one for print is the quantity in stock is greater or lesser than the quantity in order. How can I compare this two quantity columns and print results?
/***
these are the codes tried till now
****/
//global variables
Vector v=new Vector();
Object listOrder=new Object();
Vector v1=new Vector();
Object listOrder1=new Object();
Vector v2=new Vector();
Object listOrder2=new Object();
int tranval[];
int stkval[];
//button action for import database values to tables
private void RequiredActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
tranval =new int[20];
stkval =new int[20];
try{
ResultSet rs = new getMatierialDataM().searchItems("SELECT icode,qty from transactiono where oid ='"+jComboBox2_oid.getSelectedItem()+"'");
//define tables
DefaultTableModel dtm = (DefaultTableModel)jTable2_required.getModel(); //required materials
dtm.setRowCount(0);
Vector v = null;
DefaultTableModel dtm1 = (DefaultTableModel)jTable1_availability.getModel();
dtm1.setRowCount(0); //available materials in stock
Vector v1 =null;
while(rs.next()){
String ico=rs.getString("icode");
String q1=rs.getString("qty");
int q11=Integer.parseInt(q1);
ResultSet rs1 = new getMatierialDataM().searchItems("SELECT transactionbom.mid,transactionbom.qty,component.comid,matierial.stockqty from transactionbom,component,matierial where transactionbom.icode ='"+ico+"' AND transactionbom.icode=component.icode AND transactionbom.mid=matierial.mid");
int len=0;
while(rs1.next()){
String q2=rs1.getString("qty");
int q22=Integer.parseInt(q2);
int qty =q11*q22; //calculation
String cid,mid,stq;
cid=rs1.getString("comid");
mid=rs1.getString("mid");
stq=rs1.getString("stockqty");
tranval[len]=qty;
stkval[len]=q22;
len++;
v = new Vector();
v.add(cid);
v.add(mid);
v.add(qty);
dtm.addRow(v);
v1 = new Vector();
v1.add(cid);
v1.add(mid);
v1.add(stq);
dtm1.addRow(v1);
}
}
}
catch (Exception e) {
e.printStackTrace();
//Logger.getLogger(ItemCosting.class.getName()).log(Level.SEVERE, null, e);
}
}
//button action for compare above two tables and get stock status in third table
private void jButton1_checkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultTableModel dtm1 = (DefaultTableModel)jTable1_status.getModel();
dtm1.setRowCount(0);
Vector v2 =null;
int x=0;
int y=3;
int len=jTable1_availability.getRowCount();
v2 = new Vector();
while(x<len){
if(tranval[x]>stkval[x]){
v2.add("mid");
v2.add("OK");
}else{
v2.add("mid");
v2.add("NO");
}
dtm1.addRow(v2);
tranval[x]++;
stkval[x]++;
x++;
}
}
That above codes print only one same result in all rows in third table.
I expected some NO status in few rows but is prints OK in all of the rows.
initComponents();
try {
ResultSet res = statement.executeQuery("SELECT * FROM banh");
ResultSetMetaData RSMD = res.getMetaData();
NumberOfColumns = RSMD.getColumnCount();
AttributeNames = new String[NumberOfColumns];
for(int i=0;i<NumberOfColumns;i++)
AttributeNames[i]=RSMD.getColumnName(i+1);
MyArray=new Object[10000][NumberOfColumns];
int R=0;
while(res.next()) {
for(int C=1; C<=NumberOfColumns;C++)
MyArray[R][C-1]=res.getObject(C);
R++;
}
res.close();
NumberOfRows=R;
Object[][] TempArray=MyArray;
MyArray=new Object[NumberOfRows][NumberOfColumns];
for(R=0;R<NumberOfRows;R++)
for(int C=0;C<NumberOfColumns;C++)
MyArray[R][C]=TempArray[R][C];
TableData.setModel(new MyTableModel());
TableData.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
public void initComponents()
{
model = new DefaultTableModel (new Object [][]
{
{null},
{null},
{null},
{null}
},
new String [] {""}
) {
Class[] types = new Class [] {java.lang.Object.class};
boolean[]canEdit=new boolean[]{false};
public Class getColumnClass(int columnIndex)
{
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return canEdit [columnIndex];
}
};
TableData.setModel(model);
JScrollPane ScrollPane1 = new JScrollPane(TableData);
ScrollPane1.setBounds(30,170,950,290);
Frame.add(ScrollPane1,BorderLayout.CENTER);
}
I show my Database to JTable by this way, I found it on Internet, it's not mine and it's work. But now I don't know how to add row to JTable and Database, I've found many website but no use (PreparedStatement, executeUpdate...). Can anyone help me about this because I've just learnt. Thank You !
That is a poor example to use:
Variable names should NOT start with an upper case character.
Hardcoding the array size to support 10,000 rows is the wrong approach. You can also use Vector which are dynamic.
Instead check out the Table From Database Example code found in Table From Database. This example uses Vectors which will grow depending on the number of rows found in the ResultSet.
I don't know how to add row to JTable and Database
You can use the addRow(...) method of the DefaultTableModel to add data dynamically. Read the API or search the forum/web for examples that use the addRow(...) method.
For database inserts you can start with the tutorial on JDBC Database Access.
initComponents();
try {
ResultSet res = statement.executeQuery("SELECT * FROM banh");
ResultSetMetaData RSMD = res.getMetaData();
NumberOfColumns = RSMD.getColumnCount();
AttributeNames = new String[NumberOfColumns];
for(int i=0;i<NumberOfColumns;i++)
AttributeNames[i]=RSMD.getColumnName(i+1);
MyArray=new Object[10000][NumberOfColumns];
int R=0;
while(res.next()) {
for(int C=1; C<=NumberOfColumns;C++)
MyArray[R][C-1]=res.getObject(C);
R++;
}
res.close();
NumberOfRows=R;
Object[][] TempArray=MyArray;
MyArray=new Object[NumberOfRows][NumberOfColumns];
for(R=0;R<NumberOfRows;R++)
for(int C=0;C<NumberOfColumns;C++)
MyArray[R][C]=TempArray[R][C];
TableData.setModel(new MyTableModel());
TableData.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
public void initComponents()
{
model = new DefaultTableModel (new Object [][]
{
{null},
{null},
{null},
{null}
},
new String [] {""}
) {
Class[] types = new Class [] {java.lang.Object.class};
boolean[]canEdit=new boolean[]{false};
public Class getColumnClass(int columnIndex)
{
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return canEdit [columnIndex];
}
};
TableData.setModel(model);
JScrollPane ScrollPane1 = new JScrollPane(TableData);
ScrollPane1.setBounds(30,170,950,290);
Frame.add(ScrollPane1,BorderLayout.CENTER);
}
I show my Database to JTable by this way, I found it on Internet, it's not mine and it's work. But now I don't know how to add row to JTable and Database, I've found many website but no use (PreparedStatement, executeUpdate...). Can anyone help me about this because I've just learnt. Thank You !
That is a poor example to use:
Variable names should NOT start with an upper case character.
Hardcoding the array size to support 10,000 rows is the wrong approach. You can also use Vector which are dynamic.
Instead check out the Table From Database Example code found in Table From Database. This example uses Vectors which will grow depending on the number of rows found in the ResultSet.
I don't know how to add row to JTable and Database
You can use the addRow(...) method of the DefaultTableModel to add data dynamically. Read the API or search the forum/web for examples that use the addRow(...) method.
For database inserts you can start with the tutorial on JDBC Database Access.
I'm returning errors from JTable inserting a 2D vector and a String[] as header...
try
{
refreshVector();
}
catch (Exception j)
{
throw j;
}
String[] headers = {"ID","Brand", "Item", "Details", "Qty", "Code", "re-order"};
JTable tbl_display = new JTable(data, headers);
JScrollPane scrollpane = new JScrollPane(tbl_display);
scrollpane.setBounds(120,120,600,300);
refreshVector method contains...
public void refreshVector() throws Exception
{
dbconnect conn = new dbconnect();
try
{
conn.connect();
}
catch (Exception p)
{
throw p;
}
rs = conn.getData();
while(rs.next())
{
Vector<Object> vec = new Vector<Object>();
vec.add(rs.getString("ID_product"));
vec.add(rs.getString("brand"));
vec.add(rs.getString("description"));
vec.add(rs.getString("details"));
vec.add(rs.getString("quantity"));
vec.add(rs.getString("product_code"));
vec.add(rs.getString("reorder"));
data.addElement(vec);
}
}
Do I have to use a table model? I'm just trying to create a simple table displaying the results of my search in the database. Is there a way to go about this without going into table models and use the standard table constructor. Thank you.
Do I have to use a table model?
Yes, the relevant tutorial includes several examples. In the particular case of database access, consider SwingWorker, as outlined here.
As an aside, use a layout manager rather than setBounds().
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;
}
}
}