i have jtable with 2 column then i want to insert value of it to database;
i know it can be done with something like ..
int count=table.getRowCount();
for(int i=0;i<count;i++){
Object obj1 = table.getValueAt(i, 0);
Object obj2 = table.getValueAt(i, 1);
the problem is..
getRowCount doesn't know if the row is empty,
then in database, that empty value will still inserted
(and it will generate my auto increment value in database)
my question
how to insert database from jtable, but the empty row will not inserted?
thanks a lot for any kind of help,,
if i asking too much please just give me a clue to handle the empty row ,
forgive my english
here's the broken method to add data to database
public void addToDatabase(){
for (int i=0;i<table.getRowCount();i++){
//#####################################
//maybe need something in here
if(table.getValueAt(i, 0)==null||table.getValueAt(i, 1) ==null){
return;
//and maybe need something not return, but to get the next row (Just.. maybe ...)
//#####################################
}else{
try{
Connection c = getCon("databasez");
PreparedStatement p = c.prepareStatement("INSERT INTO table_data VALUES (?,?)");
p.setString(1, table.getValueAt(i, 0).toString());
p.setFloat (Float.parseFloat(table.getValueAt(i, 1).toString()));
p.executeUpdate();
p.close();
}catch(Exception e){
JOptionPane.showMessageDialog(this, "THERE WAS AN INVALID DATA");
}
}
}
}
Assuming that you're using DefaultTableModel, the result returned by getValueAt() will be null until you edit the corresponding cell.
You can also register a TableModelListener to receive a TableModelEvent that can tell your listener what has changed.
private JTable table = new JTable(1, 2);
...
table.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
System.out.println(""
+ e.getType() + " "
+ e.getFirstRow() + " "
+ e.getLastRow() + " "
+ e.getColumn());
}
});
maybe it will help you.
http://www.exampledepot.com/egs/javax.swing.table/InsertRow.html
first, I just saw getData methods here and I didn't see insert or some alike method you invoked, so I think the code doesn't relate to what you said.
second, also you can learn to search the api about jtable.
if you full know the methods of a class and how to use it in the general ways, I think you understand and use it very well.
and this can also improve your understanding to understand something similar.
and you will become stronger and stronger to learn other difficult things without asking questions.
That's my oppion to learn program.
JAVA swing,SIMPLE WAY TO store jTable DATA in database
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) // swing Button
{
String name[] =new String[4]; // name is array and index 4 means no. of row
String age[]=new String[4]; //age is array and index 4 means no. of row
//loop from 0 row to 4
for(int i=0;i<4;i++)
{
name[i]=table.getValueAt(i,0).toString(); // it get value from 0 row and 0 column
age[i]=table.getValueAt(i,1).toString(); // it get value from 0 row and 1 column
//similarly for more column
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","");
Statement s1=con.createStatement();
int mc=s1.executeUpdate("insert into testtable(Name,Age) values('"+name[i]+"','"+age[i]+"')");
}
catch(Exception ex)
{
javax.swing.JOptionPane.showMessageDialog(null,ex.getMessage().toString());
}
}
Related
I just did a button that adds products from a jComboBox, the quantity we want from a jTextField and the price of the product in a jTable.
I want my button to add the product, and if it's already in the jTable, it just adds the quantity we want to the right column. It works for the first product I have, but not the rest.
String cp = jComboBoxProduit.getSelectedItem().toString();
//CategorieCombo is a class that gives us the id, value or price of a row in a SQL table
CategorieCombo pp = (CategorieCombo) jComboBoxProduit.getSelectedItem();
DefaultTableModel leModel = (DefaultTableModel) jTable4.getModel();
if(jTable4.getRowCount() != 0)
{
for (int i = 0; i < jTable4.getRowCount(); i++)
{
if ((String)jTable4.getValueAt(i, 0) != cp)
{
leModel.addRow(new Object[]{cp, jTextFieldQuantity.getText(), pp.getPrix()});
}
else {
int qte = Integer.valueOf(jTable4.getValueAt(i,1).toString());
qte = qte + Integer.valueOf(jTextFieldQuantity.getText());
jTable4.setValueAt(qte, i, 1);
}
}
}
else
{
leModel.addRow(new Object[]{cp, jTextFieldQuantity.getText(), pp.getPrice()});
}
I think it doesn't work because the following line
leModel.addRow(new Object[]{cp, jTextFieldQuantity.getText(), pp.getPrix()});
it's in the for loop, so maybe it just execute everytime there is a row in my table, but I'd like if I could just execute this line once.
I hope I've been clear enough, thanks if you can help me find the answer !
So I have the following issue.
I have a Java application that connects to a Redshift-DB via jdbc. Executing a simple SELECT-query yields a ResultSet that is not null (I checked).
Now, when I try to extract data from this ResultSet, the method will sometimes return null, even though a previous ResultSet.wasnull() returns false and a manual check in the database also reveals that the record in question does not contain a null value for that attribute.
Sample code:
private void test(){
ResultSet rs = null;
ResultSetMetaData rsmd = null;
String getTable = "SELECT * from myTable"; //
try(PreparedStatement prep = myConnection.prepareStatement(getTable
, ResultSet.TYPE_FORWARD_ONLY
)){
rs = prep.executeQuery();
rsmd = rs.getMetaData();
int columns = rsmd.getColumnCount();
while(rs.next()){ // loop over all rows
for(int col = 1; col <= columns; col++){
if(rs.wasNull())
System.out.println("NULL Value detected!");
System.out.println("Column Name: " + rsmd.getColumnName(col));
System.out.println("Column value: " + rs.getString(col));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
This works most of the time, except for some records the rs.getString(col) will just result in a null (even though the data type in the DB is CHAR or VARCHAR). This does not necessarily happen for all columns (I've seen it happen that a couple of columns were read and printed correctly, until eventually, a null appeared, even though wasnull() returned false.
So far, I have observed this behaviour for ResultSet.getString(), ResultSet.getDate() and ResultSet.getTimestamp(), but never when extracting any sort of number (getInt()...). In all these cases, I checked the DB to make sure the jdbc-method matches the data type.
I tried using different driver versions, I tried using rs.getBytes(col) instead, but the result remains the same: I just cannot get rid of those nulls.
I also successfully did an UNLOAD-operation, unloading the troublesome table to S3 and manually checking the exported csv files. The UNLOAD runs without any issue, the CSVs look fine to me (all values as expected).
Now I could of course manually handle those "unwanted NULLs" by skipping the records in which they occur, but I'd rather avoid glossing over this error like that without understanding its cause.
So my question would be:
Am I doing something fundamentally wrong in my code?
Is there a known issue with jdbc / Redshift that could cause this?
Can someone maybe point me to some sources or give me some ideas on what else I could try?
From the javadoc of ResultSet.wasNull():
Reports whether the last column read had a value of SQL NULL. Note
that you must first call one of the getter methods on a column to try
to read its value and then call the method wasNull to see if the
value read was SQL NULL.
Returns:
true if the last column value read was SQL NULL and false otherwise
In other words, you should use it after reading a column. Be aware that for object types it makes no sense to call wasNull, as the object getters will already return null.
This method is intended to be used when reading columns using the primitive getters (like getInt()), because those will return 0 for null values. You can then use wasNull() to check if the value was really 0 or actually null.
In other words, change your code to:
while(rs.next()){ // loop over all rows
for(int col = 1; col <= columns; col++){
String value = rs.getString(col);
if(value == null)
System.out.println("NULL Value detected!");
System.out.println("Column Name: " + rsmd.getColumnName(col));
System.out.println("Column value: " + value);
}
}
Or, if you really want to use wasNull() (but really, you shouldn't!):
while(rs.next()){ // loop over all rows
for(int col = 1; col <= columns; col++){
String value = rs.getString(col);
if(rs.wasNull())
System.out.println("NULL Value detected!");
System.out.println("Column Name: " + rsmd.getColumnName(col));
System.out.println("Column value: " + value);
}
}
I have a Jtable that I've loaded with values from a .csv file, but it creates a new row for every instance of 5/13/2013 that shows up in the file, like so:
I'd like to remove all rows with this info from the table, but am not sure how to do so. Any suggestions for me?
Here's my code to add the data to the table, if it helps:
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
tableModel.insertRow(tableModel.getRowCount(), values);
}//end of while block`
To reiterate and be completely clear, I want to remove every row that contains "5/13/2013" from the table completely. And I'm using the deafault table model, by the way.
I ended up applying a for loop and an if statement to get this working for me.
//remove rows with instances of "5/13/2013"
for (int i = 0; i < tableModel.getRowCount(); i++) {
if (((String)tableModel.getValueAt(i, 0)).equals("5/13/2013")) {
tableModel.removeRow(i);
}//end of if block
}//end of for block
It's worked well for me and has gotten rid of each of those rows. Hopefully this may help someone else out.
while(i < tableModel.getRowCount()) {
//if the value at (i, 0) match the specified value the row will be removed
/*
if the row removed all row will move up and their index will be changed
so you have to add a condition if the value from the table doesn't match
the specified value the iterator i will iterate by one to jump to the next
row
*/
if (((String)tableModel.getValueAt(i, 0)).equals("5/13/2013")) {
tableModel.removeRow(i);
}else {
++i;
}
}
I have a program that is written to work in conjunction with a JTable and a few other Swing elements in order to display and model a backend for a game. The function is supposed to get the first row selected and the last row selected and store them in an array rows at index 0 and 1 respectively. Thanks for your help and hope to understand what is going on here.
public int[] getRows(JTable table) {
rows = new int [2];
rows[0] = table.getSelectedRow();
rowCount = table.getSelectedRowCount() - 1;
rows[1] = rows[0] + rowCount;
return rows;
}
JTable.getSelectedRows() can you help you in this case. Just take the first and last index from the array it returns. Note that it can return an empty array.
I'm having difficulties getting the following code to preserve the logically selected row in the model if the JTable has been sorted.
It works as intended when no sorting is applied.
private void updateAccountTable() {
accountsTable = guiFrame.getAccountsTable();
// Preserve selected model row
String accountNumber = "";
int selectedRow = accountsTable.getSelectedRow();
if(selectedRow >= 0){
accountNumber = (String)accountsTable.getValueAt(selectedRow, 0);
}
// Preserve sort order
// Keep eclipse happy. better way??
List <? extends SortKey> keys = accountsTable.getRowSorter().getSortKeys();
// Update displayed accounts
DefaultTableModel model = (DefaultTableModel) accountsTable.getModel();
model.getDataVector().clear();
Object[][] tableContents = accountList.getAccountsAsArray(true);
model.setDataVector(tableContents, tableHeaders);
model.fireTableDataChanged();
// reset sort order
accountsTable.getRowSorter().setSortKeys(keys);
// If updated model contains previously selected account, reselect
if (!accountNumber.equals("") && null != accountList.getAccount(accountNumber)){
for (int row=0; row<accountsTable.getRowCount(); row++){
String an = (String)accountsTable.getValueAt(row, 0);
if (an.equalsIgnoreCase(accountNumber)){
accountsTable.setRowSelectionInterval(row, row);
break;
}
}
}
else {
accountsTable.clearSelection();
}
}
Unfortunately setRowSelectionInterval() doesn't updated the selected row as expected, despite being called with the correct view row number. It seems to do nothing.
.....So,
Why is setRowSelectionInterval() failing to updated the selection, or what have I missed?
The row obtained from getSelectedRow() is in view coordinates, while the model coordinates have been changed by the intervening update. Quoting from the relevant tutorial section:
This distinction does not matter unless your viewed data has been rearranged by sorting, filtering, or user manipulation of columns.
You will need to use the conversion methods described near the end of Sorting and Filtering, which suggests:
When using a sorter, always remember to translate cell coordinates.
When you click on Jtable header to sort it, and click on a row (ex. 3rd row), you will get the value of unsorted JTable's row. To avoid this situation, use this LOC.(ik this is irrelvant to what you're trying to do but for others w/ similar problems)
int row = tblUser.getSelectedRow();
//Without below line, the value you get would be the row before sorting
int correctModel = tblUser.convertRowIndexToModel(row);
//Get username and use it to find its corresponding tuple
String username = (tblUser.getModel().getValueAt(correctModel, 1)).toString();
My table looks like this and Im trying to get the username of the selected row and w/o the 2nd LOC, I'd get the unsorted JTable's row value even after sorting it:
---------------------
| id | username |
---------------------
| | |