I am stuck in a problem. When I try to send data from jtable to sql database through stored procedure. here what I am doing:
inserting data to jtable
String b= jLabel116.getText(),c=jTextField6.getText(),e=jTextField20.getText(),f=jTextField25.getText(),g=jTextField48.getText();
float x,y,z;
x=Float.parseFloat(jTextField25.getText());
y=Float.parseFloat(jTextField48.getText());
z=x*y;
String total1=String.valueOf(z);
DefaultTableModel df = (DefaultTableModel) jTable5.getModel();
df.addRow(new Object[]{b,c,d,f,g,total1});
int rowsCount = jTable5.getRowCount();
int Price = 0,Qty=0, total=0;
for(int i=0;i<rowsCount;i++){
Price += Integer.parseInt(jTable5.getValueAt(i,3).toString());
Qty += Integer.parseInt(jTable5.getValueAt(i,4).toString());
}
total = Price*Qty;
System.out.println(total);
jTextField26.setText(String.valueOf(total));
jTextField51.setText(String.valueOf(total));
jTextField50.setText(String.valueOf(Qty));
jTable5.setModel(df);
Sending Data to Database
try{
DefaultTableModel df = new DefaultTableModel();
df=(DefaultTableModel) jTable5.getModel();
CallableStatement cs=m.XC.prepareCall("call Prod_SALE (?,?,?,?,?,?,?,?)");
for (int i = 0; i < df.getRowCount(); i++) {
for (int j = 0; j < df.getColumnCount(); j++) {
Object o = df.getValueAt(i, j);
System.out.println("object from table is : " +o);
cs.setString(j+1, (String)o);
cs.addBatch();
}
cs.executeBatch();
cs.clearParameters();
}
}
catch(Exception ex){
ex.printStackTrace();
Error Exception:
java.sql.SQLException: Parameter-Set has missing values.
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.addBatch(JdbcOdbcPreparedStatement.java:1546)
Please help me....I am unable to solve it
You call addBatch in the inner loop (variable j) after you have set one parameter. Obviously this fails since you have 8 parameters. The Javadoc of PreparedStatement.addBatch says:
Adds a set of parameters to this PreparedStatement object's batch of
commands.
You need to move the call to addBatch out of the inner loop.
(And probably the executeBatch should be moved out of the outer loop (variable i) too.
DefaultTableModel df = (DefaultTableModel) jTable5.getModel();
CallableStatement cs=m.XC.prepareCall("call Prod_SALE (?,?,?,?,?,?,?,?)");
for (int i = 0; i < df.getRowCount(); i++)
{
for (int j = 0; j < df.getColumnCount(); j++)
{
Object o = df.getValueAt(i, j);
System.out.println("object from table is : " +o);
cs.setString(j+1, (String)o);
}
cs.addBatch();
}
cs.executeBatch();
As the message says, you have not set all values in your SQL.
Related
I made a Java application on netbeans about ranking the vikor method,
but when going to save the table data to the database, an error appears saying that the count table is mismatch.
I have tried changing the syntax and database settings. But still
Is there anything I missed?
Anything about storing data from table calculations directly to the database?
This is my code:
public void cariperingkat(){
try {
LinkedList mm=new LinkedList();
ResultSet res3 = conn.ambilData("select * from bobot");
tabelmodelPERINGKAT();
while (res3.next()){
mm.add(res3.getString(1));
mm.add(res3.getString(2));
mm.add(res3.getString(3));
mm.add(res3.getString(4));
}
for (int t = 0; t < jTable2.getRowCount(); t++) {
String sql = "delete from data_alternatif WHERE nama= nama";
conn.simpanData(sql);
}
for (int x = 0; x < jTable2.getRowCount(); x++) {
double r1;
double r2;
double r3;
double r4;
double w;
r1=(Float.valueOf(jTable2.getValueAt(x, 1).toString())*Float.valueOf(mm.get(0).toString()));
r2=(Float.valueOf(jTable2.getValueAt(x, 2).toString())*Float.valueOf(mm.get(1).toString()));
r3=(Float.valueOf(jTable2.getValueAt(x, 3).toString())*Float.valueOf(mm.get(2).toString()));
r4=(Float.valueOf(jTable2.getValueAt(x, 4).toString())*Float.valueOf(mm.get(3).toString()));
w=r1+r2+r3+r4;
String sql = "insert into data_alternatif values"+
"('"+jTable2.getValueAt(x, 0).toString()+"', "+
"'"+w+"')";
conn.simpanData(sql);
}
tabelmodelPERINGKAT();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, ex);
}
}
I have a JTable2 in frame1 and JTable1 in frame2. I want to copy and send selected data from table2 to table1. how do i do it ?
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
String sql = "select * from table1 where Bill_No like '"+jTextField2.getText()+"'";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
JFrame NewJFrame2 = new NewJFrame2();
NewJFrame2.setVisible(true);
int i=0;
while(rs.next()) {
Object bno = rs.getString("Bill No");
Object bamount = rs.getString("Bill Amount");
Object btds = rs.getString("TDS");
Object btax = rs.getString("Tax");
Object bpayable = rs.getString("Payable");
jTable1.getModel().setValueAt(bno,i, 0 );
jTable1.getModel().setValueAt(bamount, i, 1);
jTable1.getModel().setValueAt(btds, i, 2);
jTable1.getModel().setValueAt(btax, i, 3);
jTable1.getModel().setValueAt(bpayable, i, 4);
System.out.println(i);
i++;
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Start by having a look at How to Use Tables.
If you want to "copy" the selected data, then you will need to know what rows are selected, see JTable#getSelectedRows.
You're making life difficult for yourself using DbUtils as you've lost the ability to just transfer the objects from one model to another.
The basic idea would be to copy the values from the original table into a new TableModel and pass that to the second window, something like
TableModel original = table.getModel();
DefaultTableModel model = new DefaultTableModel(table.getSelectedRowCount(), original.getColumnCount());
for (int col = 0; col < original.getColumnCount(); col++) {
model.addColumn(original.getColumnName(col));
}
int[] selectedRows = table.getSelectedRows();
for (int targetRow = 0; targetRow < selectedRows.length; targetRow++) {
int row = selectedRows[targetRow];
int modelRow = table.convertRowIndexToModel(row);
for (int col = 0; col < original.getColumnCount(); col++) {
model.setValueAt(original.getValueAt(modelRow, col), targetRow, col);
}
}
for example. Now you just need to pass model to the second window and apply it to the JTable contained within
I have a strange error which I can not get my head around where the .size() method does not appear to return the correct value.
This first bit of code creates the ArrayList.
public void createResultList(String query) {
ArrayList<ArrayList<String>> data = new ArrayList();
try {
ResultSet rs = st.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
for(int i = 0; i < meta.getColumnCount(); i++) {
data.add(i, new ArrayList<String>());
}
int x = 0;
while(rs.next()) {
for(int y = 0; y < meta.getColumnCount(); y++) {
data.get(x).add(rs.getString(y + 1));
}
x++;
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
ResultTable result = new ResultTable(data);
JTable table = new JTable(result);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
refresh();
}
This is my TableModel class which is used to create the table when it's passed to it.
public class ResultTable extends AbstractTableModel {
private ArrayList<ArrayList<String>> data;
public ResultTable(ArrayList<ArrayList<String>> data) {
this.data = data;
}
public int getColumnCount() {
return data.get(0).size();
}
public int getRowCount() {
return data.size();
}
public Object getValueAt(int row, int col) {
return data.get(row).get(col);
}
}
Now the the problem is in the ResultTable class, now for a select query returning one row with 12 columns, the first data.get(0).size() call correctly returns 12, but the 2nd data.size() call incorrectly returns 12 also instead of 1, this is causing out of bounds errors, can anyone please explain this seemingly paradoxical result?
This is something you should've found easily when you debug your code...
public void createResultList(String query) {
ArrayList<ArrayList<String>> data = new ArrayList();
data is an ArrayList of ArrayLists
try {
ResultSet rs = st.executeQuery(query);
A query returning 1 row of 12 columns
ResultSetMetaData meta = rs.getMetaData();
for(int i = 0; i < meta.getColumnCount(); i++) {
For each column in your recordset, being 12, you add an empty ArrayList in data
data.add(i, new ArrayList<String>());
}
resulting in data being an ArrayList of 12 empty Arraylists
This already explains why data.size() == 12
int x = 0;
while(rs.next()) {
for each record in your recordset, being 1
for(int y = 0; y < meta.getColumnCount(); y++) {
for each column in your recordset, being 12, you add a string to the ArrayList with the same index as the recordset
data.get(x).add(rs.getString(y + 1));
}
The first ArrayList in data (data.get(0)) will have 12 Strings
All other ArrayLists in data (data.get(x) where x > 0) will remain empty
x++;
}
Resulting in data being an ArrayList of 12 ArrayLists
of which only the first ArrayList has 12 Strings and the others are empty
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
ResultTable result = new ResultTable(data);
JTable table = new JTable(result);
JScrollPane scrollpane = new JScrollPane(table);
add(scrollpane);
refresh();
}
When you create the data list, you create a sublist to hold the data for each column.
If that is what you want to do, you should add data from each column of the result set to the list that corresponds to it:
while(rs.next()) {
for(int y = 0; y < meta.getColumnCount(); y++) {
data.get(y).add(rs.getString(y + 1));
}
}
In this class, I am trying to only keep one of each value in the JTable. The Data is coming from a Database. I dont need repetative data though.
public JTable getHeute(){
DBconnect verbinden = new DBconnect();
verbinden.erstelleVerbindung();
JTable Habwesend=new JTable();
Habwesend.setBounds(10, 30, 290, 400);
Habwesend.setEnabled(false);
DefaultTableModel dm=new DefaultTableModel();
try {
ResultSet rs= verbinden.sqlStatement.executeQuery("select MA_ID from AB_Spanne where(Date() >= Start and Date() <= Ende)");
ResultSetMetaData rsmd=rs.getMetaData();
//Coding to get columns-
int cols=rsmd.getColumnCount();
String c[]=new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
for (int k = 0; k < c.length; k++) {
dm.addColumn(c[k]);
}
}
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
Habwesend.setModel(dm);
verbinden.schliesseVerbindung();
}
Change your query to:
"SELECT DISTINCT MA_ID from AB_Spanne where(Date() >= Start and Date() <= Ende)"
You can do it in java like (unrecommended and unperformant):
//UNTESTED CODE
List<Object> Objectlist = new List<Object>();
// ...
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
if !(Objectlist.Contains(row)){
dm.addRow(row);
}
}
// I guess in order to the contains methode to work you may need to create own objects in which you override the equality / comparrision methods.
Instead of the List, use a Set and keep the rest of your code the same. That's your java solution, to whit:
// Set dm = new HashSet();
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
Habwesend.setModel(dm);
verbinden.schliesseVerbindung();
How to get row with index i froj JTable ? I looked at member functions but there is nothing like getRowAt . Can anybody help ?
There is no "row" object for a table, so nothing you could get with a getRow method.
You can ask getValueAt() to get the individual values, use it for each column and you have your complete row.
AFAIK, there is no such method. Write something like that:
public String[] getRowAt(int row) {
String[] result = new String[colNumber];
for (int i = 0; i < colNumber; i++) {
result[i] = table.getModel().getValueAt(row, col);
}
return result;
}
P.S - Use table.getValueAt() if you want to respect a rearranged by the user column order.
I recommend to create a TableModel based on a list of POJOs.
It's then easy to add a method like:
MyPojo getData(int index);
Have a look at this sample I wrote some time ago for a starting point:
http://puces-samples.svn.sourceforge.net/viewvc/puces-samples/tags/sessionstate-1.0/sessionstate-suite/sessionstate-sample/src/blogspot/puce/sessionstate/sample/ParticipantTableModel.java?revision=13&view=markup
Try something like this
private void getIndexRow(){
int i;
int row = 0;
int column = 0;
i=Integer.parseInt(myTable.getValueAt(row,column).toString());
}
Another way of doing it is using the table model's getDataVector() method.
DefaultTableModel tm = (DefaultTableModel) table.getModel();
Vector<Object> rowData = tm.getDataVector().elementAt(rowIndex);
private void jTable1MousePressed(java.awt.event.MouseEvent evt) {
int selectedRow;
ListSelectionModel rowSM = jTable1.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
selectedRow = lsm.getMinSelectionIndex();
int numCols = jTable1.getColumnCount();
model = (DefaultTableModel) jTable1.getModel();
System.out.print(" \n row " + selectedRow + ":");
for (int j = 0; j < numCols; j++)
{
System.out.print(" " + model.getValueAt(selectedRow, j));
}
}
});
}
Using this you can get value of whole row where u click on particular row.
This function is working well for me.
private Object[] getRowAt(int row, DefaultTableModel model) {
Object[] result = new Object[model.getColumnCount()];
for (int i = 0; i < model.getColumnCount(); i++) {
result[i] = model.getValueAt(row, i);
}
return result;
}