I'm new to Java, Swing and programming, but I need to make an application. I'm using NetBeans for development and here's my question:
If I drag and drop the JTable to my frame and select custom code for the table, I get this code:
appView.java
tblViewData = new javax.swing.JTable();
tblViewData.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Reference No", "Name", "Description"
}
));
jScrollPane1.setViewportView(tblViewData);
What I want to do is populate new Objects[][] with data that I fetch from the appController using ResultSet and the values I set in the appModel for variables ID, Ref, Name and Desc.
Here's a sample code of an insert I attempted to see if I could display a row of data:
new Object [][] {
{ new Integer(model.getID()), model.getRef(), model.getName(), model.getDesc() }
},
This code returns a 0 in the first column of the row.
Am I approaching this problem wrong?
Thanks for the help.
Well I have no idea what the "appController" or "appModel" are. Maybe these are IDE dependent classes? Instead of using the IDE to generate your SQL code I suggest you write your own code and populate the table yourself.
There are plenty of examples on the forum showing how to load a JTable with data from a ResultSet. Just search for examples using those two class names as your keywords.
Or you can check out Table From Database which shows how you can use the DefaultTableModel to load rows of data from the ResultSet.
Related
I am using DBUNIT for exporting my dataset as XML. I wonder is there any "simple" way to get all dependet tables and data by given table name and some criterion?
private void exportDBDepended() throws Exception {
String[] depTableNames = TablesDependencyHelper.getAllDependentTables(connection, "dbo.Users" );
IDataSet depDataset = connection.createDataSet( depTableNames );
FlatXmlDataSet.write(depDataset, new FileOutputStream("dependents.xml"));
}
This gives me all records and dependet data, but I would like to fetch only top 100 records, or some other condition for table.
Thanks in advance,
Dario
I didn't manage to solve my requirement programmatically, but http://jailer.sourceforge.net/ will be more than eneugh for preparing XML DB data.
I created JTable, using Design View - Table.
But, I want the values to come from SQL query, not to be inserted manulally.
So I select on table: model -> Custom Code, then there is: jTable1.setModel();
What I can put there? I tried with methods to return value, but NetBeans tell me, String cannot to be converted to TableModel.
I can't modify the code initComponents(), which is generated from NetBeans, I can only put method there.
So how to get values from SQL or what I can use here setModel() to retrieve the result from SQL.
Table: 3 columns x 7 lines
The code:
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(resultsTable());
jTable1.setToolTipText("");
jScrollPane1.setViewportView(jTable1);
... more code for the frame .....
You could also make your table model by extending AbstractTableModel class and overriding appropriate methods.
Take a look at this https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
I found very easy solution:
https://www.youtube.com/watch?v=fbYxThOFsLI
This is exactly what I want, using Table, generated from NetBeans.
Thanks to everyone!
I am pretty basic to link from Java to Database.
I link item from Database (I use MS.Access) to Java table (JTable)
but when I delete in JTable using this code
int numRows = tblweng.getSelectedRows().length;
for(int i=0; i<numRows ; i++ )
((DefaultTableModel)tblweng.getModel()).removeRow(tblweng.getSelectedRow());
it deletes only in Table but not in Database. So how I can remove both of them at the same time I click "Remove Button".
Please guide me but don't go too deep I am just a basic here. Thank in advance.
1. click Jtable // row selected
2. get data form dep_Table like
int a = dep_Table.getSelectedRow();
String b = String.valueOf(dep_Table.getValueAt(a, 1));
3. What data you want in you get and store in String
4. Connect Database
5. use Delete Query and Delete Data From Database
6. Reload Table Again
These Few basic Step is Enough for You.. I Think..
I work with an MS-Access table in Java using Jackcess:
Database mdb = Database.open(new File(myPath));
Table myTable = mdb.getTable("TableName");
Is there a way to get the table sorted/ordered by one or more column(s)? Couldn't find anything in the docs.
Thanks for any hint.
If you iterate through the Table rows using a Cursor which is backed by an Index, you will get the rows ordered by the relevant Index.
This is an example (using the 1.x API) which iterates the table based on the order of the primary key:
for(Map<String,Object> row : Cursor.createIndexCursor(table, table.getPrimaryKeyIndex())) {
// do something with row here...
}
I was having this same issue here, but it helped.
For the folks that are using the new version of Jackcess (v: 2.1.2) here is the answer:
for (Row row : CursorBuilder.createCursor(table.getIndex("IndexToBeSorted"))){
//Your awesome code with the row here
}
Thanks!
I am attempting to create a test database (based off of my production db) at runtime, but rather than have to maintain an exact duplicate test db i'd like to copy the entire data structure of my production db at runtime and then when I close the test database, drop the entire database.
I assume I will be using statements such as:
CREATE DATABASE test //to create the test db
CREATE TABLE test.sampleTable LIKE production.sampleTable //to create each table
And when I am finished with the test db, calling a close method will run something like:
DROP DATABASE test //delete the database and all its tables
But how do I go about automatically finding all the tables within the production database without having to manually write them out. The idea is that I can manipulate my production db without having to be concerned with maintaining the structure identically within the test db.
Would a stored procedure be necessary in this case? Some sample code on how to achieve something like this would be appreciated.
If the database driver you are using supports it, you can use DatabaseMetaData#getTables to get the list of tables for a schema. You can get access to DatabaseMetaData from Connection#getMetaData.
In your scripting language, you call "SHOW TABLES" on the database you want to copy. Reading that result set a row at a time, your program puts the name of the table into a variable (let's call it $tablename) and can generate the sql: "CREATE TABLE test.$tablename LIKE production.$tablename". Iterate through the result set and you're done.
(You won't get foreign key constraints that way, but maybe you don't need those. If you do, you can run "SHOW CREATE TABLE $tablename" and parse the results to pick out the constraints.)
I don't have a code snippet for java, but here is one for perl that you could treat as pseudo-code:
$ref = $dbh->selectall_arrayref("SHOW TABLES");
unless(defined ($ref)){
print "Nothing found\n";
} else {
foreach my $row_ref (#{$ref}){
push(#tables, $row_ref->[0]);
}
}
The foreach statement iterates over the result set in an array reference returned by the database interface library. The push statement puts the first element of the current row of the result set into an array variable #tables. You'd be using the database library appropriate for your language of choice.
I would use mysqldump : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html
It will produce a file containing all the sql commands needed to replicate the prod database
The solutions was as follows:
private static final String SQL_CREATE_TEST_DB = "CREATE DATABASE test";
private static final String SQL_PROD_TABLES = "SHOW TABLES IN production";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute(SQL_CREATE_TEST_DB);
SqlRowSet result = jdbcTemplate.queryForRowSet(SQL_PROD_TABLES);
while(result.next()) {
String tableName = result.getString(result.getMetaData().getColumnName(1)); //Retrieves table name from column 1
jdbcTemplate.execute("CREATE TABLE test2." + tableName + " LIKE production." + tableName); //Create new table in test2 based on production structure
}
This is using Spring to simplify the database connection etc, but the real magic is in the SQL statements. As mentioned by D Mac, this will not copy foreign key constraints, but that can be achieved by running another SQL statement and parsing the results.