问题描述
publicvoidtableChanged(TableModelEvente){System.out.println(e.getFirstRow()+":"+e.getColumn());//e.getColumn()==-1,表示插入新行,在后面可以写对新行的操作,这里就不废话了if(e.getColumn()!=-1){Objecto;//这两列是几个费用,修改后更新总费用和几个判断if(e.getColumn()==3||e.getColumn()==6||e.getColumn()==9||e.getColumn()==10){//获取某个格的数据o=tabData.getValueAt(e.getFirstRow(),3);doubleb=0.00;b=Double.valueOf(o.toString());System.out.println(b);doublea=0.00;//空检查很重要if(o!=null){a=Double.valueOf(o.toString());}o=tabData.getValueAt(e.getFirstRow(),6);doublec=0.00;c=Double.valueOf(o.toString());System.out.println(c);if(o!=null){a+=Double.valueOf(o.toString());}o=tabData.getValueAt(e.getFirstRow(),9);doubled=0.00;d=Double.valueOf(o.toString());System.out.println(d);if(o!=null){a+=Double.valueOf(o.toString());}o=tabData.getValueAt(e.getFirstRow(),10);if(o!=null){a+=Double.valueOf(o.toString());}System.out.println(a);//设置某个格的数据//tabData.setValueAt(b,e.getFirstRow(),3);//tabData.setValueAt(c,e.getFirstRow(),6);//tabData.setValueAt(d,e.getFirstRow(),9);tabData.setValueAt(a,e.getFirstRow(),11);//booleanb=a>=120;//tabData.setValueAt(b,e.getFirstRow(),12);}o=tabData.getValueAt(e.getFirstRow(),0);if(o!=null||rs!=null){{//转换到模型行intselect=e.getFirstRow();if(select==-1){return;}select=tabData.getRowSorter().convertRowIndexToModel(select);try{rs.beforeFirst();rs.absolute(select+1);//更新数据集中某个位置的内容rs.updateObject(e.getColumn()+1,tabData.getValueAt(e.getFirstRow(),e.getColumn()));//将内容更新到数据库rs.updateRow();//rs.close();}catch(SQLExceptionex){Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE,null,ex);}}}//执行以后报诸如下面这样的错误但有时是可以运行并且不报错的。2009-10-1317:54:52SQLC.ConnectionSQLtableChanged严重:nulljava.sql.SQLException:[Microsoft][SQLServer2000DriverforJDBC]Rowupdatefailed.atcom.microsoft.jdbc.base.BaseExceptions.createException(UnknownSource)
解决方案
解决方案二:
顶下怎么依然没有人关注
解决方案三:
在线等答案
解决方案四:
看你的rs應該是寫在Class里的全局變量。ConnectionSQLtableChanged連接SQL的表被改變了。是不是你這個類的其他mothed把rs改變了?
解决方案五:
楼上的说的很对我的RS是全局变量这个代码很奇怪的一点是:总费用可以随着单个费用的更新而更新数据库中的总费用并且可以保存但是这个做更改的单个费用却不能中更改数据库中的数据
解决方案六:
packageSQLC;importjava.sql.*;importjava.util.*;importjava.util.logging.*;importjavax.swing.*;importjavax.swing.event.*;importjavax.swing.table.*;publicclassConnectionSQLextendsjavax.swing.JFrameimplementsTableModelListener{//连接字符串StringconnectionUrl="jdbc:sqlserver://localhost:1433;"+"databaseName=WYMS;user=sa;password=123456;";Connectioncon;Statementstmt;ResultSetrs;ResultSetMetaDatarsm;String[]columnNames=null;//列标题Object[][]data=null;//数据项DefaultTableModelmodel;//表格模型JLabellabel=null;//显示修改字段位置/**CreatesnewformConnectionSQL*/publicConnectionSQL(){initComponents();this.setLocationRelativeTo(null);}//<editor-folddefaultstate="collapsed"desc="GeneratedCode">//GEN-BEGIN:initComponentsprivatevoidinitComponents(){cmdConnection=newjavax.swing.JButton();jScrollPane1=newjavax.swing.JScrollPane();tabData=newjavax.swing.JTable();cmdAddRow=newjavax.swing.JButton();cmdDelRow=newjavax.swing.JButton();cmdClose=newjavax.swing.JButton();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);setTitle("SQL操作实例--ByNull");cmdConnection.setText("连接/显示");cmdConnection.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){cmdConnectionActionPerformed(evt);}});tabData.setModel(newjavax.swing.table.DefaultTableModel(newObject[][]{{null,null,null,null},{null,null,null,null},{null,null,null,null},{null,null,null,null}},newString[]{"Title1","Title2","Title3","Title4","Title5","Title6","Title7","Title8","Title9","Title10","Title11","Title12"}));jScrollPane1.setViewportView(tabData);cmdAddRow.setText("添加行");cmdAddRow.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){cmdAddRowActionPerformed(evt);}});cmdDelRow.setText("删除行");cmdDelRow.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){cmdDelRowActionPerformed(evt);}});cmdClose.setText("关闭");cmdClose.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){cmdCloseActionPerformed(evt);}});javax.swing.GroupLayoutlayout=newjavax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(6,6,6).addComponent(cmdConnection).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cmdAddRow).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cmdDelRow).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cmdClose,javax.swing.GroupLayout.PREFERRED_SIZE,66,javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(203,Short.MAX_VALUE)).addComponent(jScrollPane1,javax.swing.GroupLayout.Alignment.TRAILING,javax.swing.GroupLayout.DEFAULT_SIZE,918,Short.MAX_VALUE));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(cmdConnection).addComponent(cmdAddRow).addComponent(cmdDelRow).addComponent(cmdClose)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT_SIZE,272,Short.MAX_VALUE)));pack();}
解决方案七:
privatevoidcmdConnectionActionPerformed(java.awt.event.ActionEventevt){//GEN-FIRST:event_cmdConnectionActionPerformed//TODOaddyourhandlingcodehere://连接并初始化表格try{//获取驱动,这里使用的是sqljdbc_1.2.2828.100_chs.exe,不同版本的驱动,语句有所不同Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");}catch(ClassNotFoundExceptionex){Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE,null,ex);}try{Stringusername="sa";Stringpassword="123456";con=DriverManager.getConnection(connectionUrl,username,password);//设置数据集可以滚动,可以更新stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);//查询语句rs=stmt.executeQuery("SELECTfang_number,yuefen,j_type,wuye_money,b_shui_ds,shui_ds,shui_money,b_dian_ds,dian_ds,dian_money,zn_money,count_moneyfromshoufeiInformation");rsm=rs.getMetaData();//判断时候可以实现对数据库的更新if(rs.getConcurrency()==ResultSet.CONCUR_UPDATABLE){System.out.println("CanUPDATABLE");}else{System.out.println("OnlyReady");}//获取列标题columnNames=newString[rsm.getColumnCount()];for(inti=0;i<rsm.getColumnCount();i++){columnNames[i]=rsm.getColumnName(i+1);}introw=0;intcolum=0;intcolumCount=rsm.getColumnCount();//获取行数,没有直接的方法,这里先移动到纪录结尾,获取行号,即为行数,然后再移回来rs.last();introwCount=rs.getRow();rs.beforeFirst();//读取数据到数据项变量data=newObject[rowCount][columCount];while(rs.next()){for(colum=0;colum<rsm.getColumnCount();colum++){data[row][colum]=rs.getObject(colum+1);}row++;}}catch(SQLExceptionex){Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE,null,ex);}//初始化数据模型model=newDefaultTableModel(data,columnNames){/****/privatestaticfinallongserialVersionUID=1L;/***重写getColumnClass*可以使表格自动识别数据类型*/@OverridepublicClassgetColumnClass(intc){//这里要对空数据集进行检验if(dataVector.isEmpty()==false&&getValueAt(0,c)!=null){returngetValueAt(0,c).getClass();}else{returnObject.class;}}};//记得implementsTableModelListener,才能获取tableChanged(TableModelEvente)事件model.addTableModelListener(this);//设置表格的模型tabData.setModel(model);//单击标题栏排序,如果需要排序,这个少不了RowSorter<DefaultTableModel>sorter=newTableRowSorter<DefaultTableModel>(model);tabData.setRowSorter(sorter);/**设置编辑器*//**JComboBoxc=newJComboBox();c.addItem("工资");c.addItem("现金");tabData.getColumnModel().getColumn(1).setCellEditor(newDefaultCellEditor(c));*/}//GEN-LAST:event_cmdConnectionActionPerformedprivatevoidcmdAddRowActionPerformed(java.awt.event.ActionEventevt){//GEN-FIRST:event_cmdAddRowActionPerformed//添加新行try{//在数据模型中加入一个空的Vector,就能实现空行的显示model.addRow(newVector<Object>());//数据集的添加rs.moveToInsertRow();//初始化行数据,这里我的第一列是非空的,所以随机产生一个数据//现实使用的时候可以弹出对话框要求用户输入,或者写一个新建,让用户输入完数据后一次插入rs.updateObject(1,(int)(System.currentTimeMillis()%10000));//将新行写到数据库rs.insertRow();}catch(SQLExceptionex)//GEN-LAST:event_cmdAddRowActionPerformed{Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE,null,ex);}}privatevoidcmdDelRowActionPerformed(java.awt.event.ActionEventevt){//GEN-FIRST:event_cmdDelRowActionPerformed//由于使用了排序,当前选择的行和数据集中对应的行可能序号不同//需要转换一下,看如下代码intselect=tabData.getSelectedRow();if(select==-1){return;}//转换表格选择的行号到数据模型的行号select=tabData.getRowSorter().convertRowIndexToModel(select);try{//定位到绝对行号,这个的内容和数据模型同步rs.absolute(select+1);rs.deleteRow();model.removeRow(select);}catch(SQLExceptionex)//GEN-LAST:event_cmdDelRowActionPerformed{Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE,null,ex);}}privatevoidcmdCloseActionPerformed(java.awt.event.ActionEventevt){//GEN-FIRST:event_cmdCloseActionPerformedtry{//关闭连接拉,rs.close();stmt.close();con.close();}catch(SQLExceptionex){Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE,null,ex);}}//GEN-LAST:event_cmdCloseActionPerformed/***@paramargsthecommandlinearguments*/publicstaticvoidmain(Stringargs[]){java.awt.EventQueue.invokeLater(newRunnable(){publicvoidrun(){try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch(Exceptione){}newConnectionSQL().setVisible(true);}});}//Variablesdeclaration-donotmodify//GEN-BEGIN:variablesprivatejavax.swing.JButtoncmdAddRow;privatejavax.swing.JButtoncmdClose;privatejavax.swing.JButtoncmdConnection;privatejavax.swing.JButtoncmdDelRow;privatejavax.swing.JScrollPanejScrollPane1;privatejavax.swing.JTabletabData;//Endofvariablesdeclaration//GEN-END:variablespublicvoidtableChanged(TableModelEvente){System.out.println(e.getFirstRow()+":"+e.getColumn());//e.getColumn()==-1,表示插入新行,在后面可以写对新行的操作,这里就不废话了if(e.getColumn()!=-1){Objecto;//这两列是4个费用,修改后更新总分和几个判断if(e.getColumn()==3||e.getColumn()==6||e.getColumn()==9||e.getColumn()==10){//获取某个格的数据o=tabData.getValueAt(e.getFirstRow(),3);//doubleb=0;//b=Double.valueOf(o.toString());//System.out.println(b);doublea=0;//空检查很重要if(o!=null){a=Double.valueOf(o.toString());}o=tabData.getValueAt(e.getFirstRow(),6);//doublec=0;//c=Double.valueOf(o.toString());//System.out.println(c);if(o!=null){a+=Double.valueOf(o.toString());}o=tabData.getValueAt(e.getFirstRow(),9);//doubled=0;//d=Double.valueOf(o.toString());//System.out.println(d);if(o!=null){a+=Double.valueOf(o.toString());}o=tabData.getValueAt(e.getFirstRow(),10);if(o!=null){a+=Double.valueOf(o.toString());}System.out.println(a);//设置某个格的数据//tabData.setValueAt(b,e.getFirstRow(),3);//tabData.setValueAt(c,e.getFirstRow(),6);//tabData.setValueAt(d,e.getFirstRow(),9);tabData.setValueAt(a,e.getFirstRow(),11);//booleanb=a>=120;//tabData.setValueAt(b,e.getFirstRow(),12);}o=tabData.getValueAt(e.getFirstRow(),0);if(o!=null||rs!=null){{//转换到模型行intselect=e.getFirstRow();if(select==-1){return;}select=tabData.getRowSorter().convertRowIndexToModel(select);try{rs.beforeFirst();rs.absolute(select+1);//更新数据集中某个位置的内容rs.updateObject(e.getColumn()+1,tabData.getValueAt(e.getFirstRow(),e.getColumn()));//将内容更新到数据库rs.updateRow();//rs.close();}catch(SQLExceptionex){Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE,null,ex);}}}}}}