JDBC 详谈

来源:互联网 发布:淘宝申请全球购要求 编辑:程序博客网 时间:2024/05/18 03:21

 

  
14.1 ODBC和JDBC
14.2 java.sql package简介
14.3 准备工作
   (
1import java.sql.*;   //导入必要的包   (2)Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //加载适当的驱动程序
   (3)利用odbc创建数据源tablesource
   (
4)创建与数据库的连接
        Connection con
=DriverManager.getConnection(“jdbc:odbc:tablesource”);
   (
5)用con创建语句,执行查询、增删改
        Statement stmt
=con.CreateStatement();
        ResultSet result
=stmt.executeQuery(“select * from myTable”);
     
14.4 驱动程序管理员-DriveManager类
DriverManager是用来管理驱动程序的类
用Class类的forName方法来加载驱动程序。可以一次加载多个驱动程序,将来要与数据库连接的时候,DriverManager会根据你的程序挑选适当的驱动程序。
   
14.4.1 DriveManager类的构造函数
       没有构造函数,整个程序只需一份DriverManager,他的方法全部是静态的。
   
14.4.2 DriveManager 类的方法
public static Connection getConnection(String url) throws SQLException
用url所表示的数据源来创建连接。url的格式如下:
jdbc:
<subprotocol>:<sourcename>
 
public static Connection getConnection(String url,String user,String password) throws SQLException
 
public static Enumeration getDrivers()
返回所有已经向DriverManager注册过的驱动程序
 
public static int getLoginTimeout()
返回驱动程序登录数据库时所能等待的最大时间,以秒为单位
public static void setLoginTimeout()
 
public static PrintWriter getLogWriter()
返回一个Writer组件,可以将一些信息?(log)写得输出流中。
 
Public 
static void println(String message)
用setLogWriter设置的Writer组件将message写到输出流中。
 
Public 
static void registerDriver(Driver driver) throws SQLException
向DriverManager注册一个数据库驱动程序
 
public static void deregisterDriver(Driver driver) throws SQLException
 
例:加载JDBC
-ODBC驱动程序
import java.io.*;
import java.util.*;
import java.sql.*;
public class DriverManagerTest
{
   
public static void main(String args[])
   
{
      
try
      
{
         PrintWriter logWriter
=new PrintWriter(new FileWriter("database.log"));
         DriverManager.setLogWriter(logWriter);
         
try
         
{
 
           Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
           
for (Enumeration e=DriverManager.getDrivers();e.hasMoreElements();)
             System.out.println(e.nextElement().toString());
           DriverManager.println(
"load JDBC-ODBC driver successfully.");
          }

 
        
catch (ClassNotFoundException excl)
        
{
          DriverManager.println(
"load jdbc-odbc diver fail.");
         }

        logWriter.close();
      }

      
catch (IOException exc2)
      
{ System.out.println("can't create log file.");
      }

 
   }

 
}

 
 
14.5 Connection interface
   Connection是DriverManager与数据库之间的桥梁,通过Connection创建Statement,CallableStatement或PreparedStatement组件才能执行SQL某命令。
   
14.5.1 Connection interface的方法
public void close() throws SQLException
关闭与数据库的连接,同时释放占用的资源
 
public Statement createStatement() throws SQLException
创建一个Statement组件,用来执行SQL指令
 
public String getCatalog() throws SQLException
返回Connection当前所连接的数据库的实际文件名。
 
Public 
int getTransactionIsolation() throws SQLException
返回Connection的isolation level。
 
Public bool isClosed() 
throws SQLException
检查Connection是否已经关闭与数据库的连接
 
public bool isReadOnly() throws SQLException
检查Connection是否为只读状态
 
public PreparedStatement prepareStatement(String sql) throws SQLException
创建一个PreparedStatement组件,所执行的指令为sql
 
public PreparedStatement preparestatement(String sql, int resultSetType, int resulSetConcurrency) throws SQLException
创建一个PreparedStatement组件,所执行的指令为sql,并且设置好它将返回的ResultSet组件的特性
例:
 
import java.sql.*;
public class ConnectionTest
{
   
public static void main(String args[])
   
{
      
try
      
{
         Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con
=DriverManager.getConnection("jdbc:odbc:tablesource","scott","tiger");
         System.out.println(con.getCatalog());
         con.close();
      }

      
catch (Exception e)
      
{
        System.out.println(e);
      }

   }

 
}

 
 
14.6 Statement interface
 Statement是用来执行SQL指令的interface,如果指令返回结果,将产生一个ResulSet。一个Statement组件一次只能产生一组查询结果(ResultSet),即它只能保留最近产生的结果,如果要想保留两个结果,必须用两个Statement组件。
 
   
14.6.1 statement interface的方法
public void cancel() throws SQLException
取消Statement组件的动作
 
public void close()throws SQLException
释放Statement所占用的资源,释放ResultSet
 
public ResultSet executeQuery(String sql) throws SQLException
执行一个SQL的查询指令,并产生ResultSet
 
public int executeUpdate(String sql) throws SQLException
执行一个sql的insert,update或delete指令,返回值为插入、删除或更新的数据行数
 
public int getMaxRows()throws SQLException
返回ResultSet最多能够容纳的数据个数,0代表没有上限。当sql指令返回的数据个数超过这个值时,多出来的数据会被忽略。
 
Public ResultSet getResultSet()
throws SQLException
返回Statement最近所产生的ResultSet。
例:
import java.sql.*;
public class StatementTest
{
   
public static void main(String args[])
   
{
     
try
     
{
        Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con
=DriverManager.getConnection("jdbc:odbc:tablesource","scott","tiger");
        Statement stmt
=con.createStatement();
        
//创建数据表
        stmt.executeUpdate("create table booktable (Title varchar2(30),author varchar2(20),price integer)");
       
//添加两个数据
       stmt.executeUpdate("insert into booktable values('data structure','eric',600)");
       stmt.executeUpdate(
"insert into booktable values('computer DIY','Mr.Lin',500)");
 
       
//查询数据
       ResultSet result=stmt.executeQuery("select * from booktable");
       
//列出查询结果
       System.out.println("Title author Price");
       System.out.println(
"====================");
       
while (result.next())
       
{
         System.out.print(result.getString(
1)+" ");
         System.out.print(result.getString(
2)+" ");
         System.out.println(result.getInt(
3));
         }

       stmt.close();
       con.close();
     }

     
catch (Exception e)
     
{
       System.out.println(e);
     }

   }

}

14.7 PreparedStatement interface继承了Statement的特性,当要执行类似的指令,用?代替参数,可重复执行。
    PreparedStatement
   
14.7.1 PreparedStatement interface的方法
public void clearParameters() throws SQLException
将所有的参数清除
 
public ResultSet executeQuery()throws SQLException
执行查询指令,返回一个ResultSet
 
public int executeUpdate() throws SQLException
执行insert、update和delete指令,返回更动的个数
 
public void setBoolean(int index,Boolean x) throws SQLException
将第index个参数设置成x。其它类似的还有setByte,setDate,setDouble,setFloat,setInt,setLong,setShort,setString,setTime等,第一个参数代表参数的索引,第二个表示数据类型,index从1开始。
例:
import java.sql.*;
public class PreparedStatementTest
{
   
public static void main(String args[])
   
{
      String[] title
={"Matlab 5.3","Linux &xwindow","photoshop 5.0"};
      String[] author
={"Roger","Gao","Sue"};
      
int[] price={550,530,480};
      
try
      
{
         Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
         Connection con
=DriverManager.getConnection("jdbc:odbc:tablesource","scott","tiger");
         PreparedStatement pstmt
=con.prepareStatement("insert into booktable values(?,?,?)");
         
//添加三个数据
         for (int i=0;i<3;i++)
         
{
            pstmt.setString(
1,title[i]);
            pstmt.setString(
2,author[i]);
            pstmt.setInt(
3,price[i]);
            pstmt.executeUpdate();
         }

         pstmt.close();
         Statement stmt
=con.createStatement();
         ResultSet result
=stmt.executeQuery("select * from booktable");
         System.out.println(
"Title author Price");
      System.out.println(
"====================");
      
while (result.next())
      
{
         System.out.print(result.getString(
1)+" ");
         System.out.print(result.getString(
2)+" ");
         System.out.println(result.getInt(
3));
      }

     stmt.close();
        con.close();
      }

      
catch (Exception e)
      
{
        System.out.println(e);
      }

   }

}

 
14.8 ResultSet interface
   ResultSet有两个特性:光标的移动方式及是否允许数据被更改(concurrency)。
   光标的移动方式有:
   TYPE_FORWARD_ONLY:光标只能前进不能后退
   TYPE_SCROLL_SENSITIVE:允许光标前进或后退,会感应到其它ResultSet的光标的移动情形。
   TYPE_SCROLL_INSENSITIVE:允许光标前进或后退,对于其它ResultSet的光标的移动情形感觉不到。
 
 Concurrency有两个常数代表:
   CONCUR_READ_ONLY:表示数据只能只读,不能更改
   CONCUR_UPDATEABLE:表示数据允许被更改
Connection在创建Statement或PreparedStatement时可以加入这两个参数,如:
Statement stmt
=con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
 或
 PreparedStatement stmt
=con.createStatement(“insert into booktable values(?,?,?)”,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
 
   如果createStatement或prepareStatement没有加那两个参数,默认值为TYPE_FORWARD_ONLY及CONCUR_READ_ONLY。
 
   
14.8.1 ResultSet interface的方法
public void close() throws SQLException
将ResultSet所占用的资源释放
 
public int findColumn(String columnName) throws SQLException
找出名称是columnName的字段是位在第几栏,返回值的范围从1开始
 
public boolean getBoolean(int index) throws SQLException
返回第index个字段的值,index的范围从1开始。其它的方法还有:getByte…
 
public boolean next() throws SQLException
将ResultSet的光标移到下一个数据上,执行后若光标位在合法的数据上则返回true,若位在最后一个数据的后面则返回false。一开始,光标在第一个记录的前面。
 
Public 
boolean wasNull() throws SQLException
判断最近一次使用getXXX方法所得到的数据是否为SQL NULL。
 
Public bool absolute(
int row) throws SQLException
将光标移到第row个数据上,当row
>0,表示移到从第一个数据算起的第row个;若row<0,表示移到从最后一个算上来的第-row个。
 
Public 
void afterLast() throws SQLException
将光标移到最后一个数据的后面
 
public void beforeFirst() throws SQLException
将光标移到第一个数据的前面
 
public void deleteRow() throws SQLException
将ResultSet及数据库中当前这一个数据删除
 
public void first() throws SQLException
将光标移到到第一个数据上,若成功返回true,否则返回false
 
public getConcurrency() throws SQLException
返回ResultSet的concurrency属性,可能是CONCUR_READ_ONLY或CONCUR_UPDATABLE。
 
Public 
int getRow() throws SQLException
返回当前光标位在第几个数据上,如果在第一个前面或最后一个后面则返回0。
 
Public Statement getStatement() 
throws SQLException
返回产生这个ResultSet的Statement,如果ResultSet不是由Statement产生而是由其它方式产生,则返回false.
 
Public 
int getType() throws SQLException
返回光标的移动方式,可能是
TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE
或TYPE_SCROLL_SENSITIVE
 
public boolean isAfterLast() throws SQLException
检查光标是否位在最后一个数据的后面,是则返回true
 
public boolean isFirst() throws SQLException
检查光标是否在第一个数据上
 
public boolean isBeforeFirst() throws SQLException
检查光标是否在第一个数据的前面
 
public boolean isLast() throws SQLException
检查光标是否在最后一个数据上
 
public boolean previous() throws SQLException
将光标移到上一个数据上,执行后若光标位在合法的数据上则返回true,若位在第一个数据的前面则返回false
 
public boolean relative(int rows) throws SQLException
若rows
>0则将光标往下移动rows个,若rows<0则将光标往上移动-rows个,如果移动后光标位在合法的数据上则返回true,否则返回false
 
public void updateBoolean(int index,boolean x) throws SQLException
将当前这个数据的第index个字段的值换成x。这个方法只会更改到ResultSet中的数据,并不会更改数据库中的数据,除非调用updateRow方法。其它类似的方法还有updateByte、updateDate、updateDouble….
 
Public 
void updateRow() throws SQLException
将ResultSet对当前这个数据所做的更改写到数据库里面。
 
Public cancelRowUpdates() 
throws SQLException
将ResultSet对当前这个数据所做的更改动作通知取消,但如果已经执行过updateRow方法,这个方法就没有作用了。
14.9 数据库实例
实例:学生的成绩记录系统,数据库表格有四个字段:学生的学号、学生姓名、期中考试成绩与期末考试成绩,类型分别是String,String,Integer与Integer。用一个Jtable组件来显示数据库中的数据,除了前面四个字段以外,最后又加了一个“平均”的字段表示期末与期中成绩的平均值,此字段不记录在数据库里。
实例程序总共有四个文件,MainFrame.java是主程序、PasswordDialog.java是用来输入账号密码的对话框、AddStudentDialog.java是用来添加学生的对话框、MyTableModel.java是用来设置Jtable数据的表格模型。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame extends JFrame implements ActionListener
{
   
private Container content;
   
private MyTableModel tableModel;
   
private JTable table;
   
private JButton btAdd,btDel;
   
private AddStudentDialog studentDialog;
   
public static void main(String args[])
   
{
      MainFrame mainFrame
=new MainFrame(); //创建主窗口
      if (mainFrame.makeTable()) //表格设置成功
      {
         mainFrame.setSize(
400,500);
         mainFrame.setVisible(
true);
      }

      
else //表格设置失败
      {
         System.exit(
0);
      }

   }

 
   
public MainFrame() //构造函数
   {
      setTitle(
"学生成绩数据");
      JPanel panel
=new JPanel();
      panel.add(btAdd
=new JButton("添加"));
      panel.add(btDel
=new JButton("删除"));
      btAdd.addActionListener(
this);
      btDel.addActionListener(
this);
      content
=getContentPane();
      content.add(panel,BorderLayout.SOUTH);
      addWindowListener(
new AppCloser());
      studentDialog
=new AddStudentDialog(this); //添加学生的对话框
   }

 
   
public void actionPerformed(ActionEvent e) //实现ActionListener
   {
      
int selectedRow;
      String id,name;
      
if (e.getSource()==btAdd) //按下“添加”按钮
      {
         studentDialog.setVisible(
true); //显示添加学生的对话框
         if (studentDialog.addOK) //确定添加
         {
            id
=studentDialog.tfID.getText().trim(); //学号
            name=studentDialog.tfName.getText().trim(); //姓名
            tableModel.addStudent(id,name); //加进数据库
         }

      }

      
//按下“删除”按钮,而且有在表格上选择一个数据
      else if ((selectedRow=table.getSelectedRow())!=-1)
      
{
         tableModel.delStudent(selectedRow); 
//从数据库中删除
         
//如果删除的是最后一个数据
         if (selectedRow>=tableModel.getRowCount())
            selectedRow
--;
         table.setRowSelectionInterval(selectedRow,selectedRow);
      }

   }

 
 
public boolean makeTable() //设置表格
 {
       
//创建账号密码对话框
       PasswordDialog pwdDialog=new PasswordDialog(this);
       tableModel
=new MyTableModel(); //创建表格模型
       while (true)
       
{
              pwdDialog.setVisible(
true); //显示账号密码对话框
              if (pwdDialog.cancel) //取消账号与密码的输入
                 return (false);
              String user
=pwdDialog.tfUser.getText(); //账号
              String pwd=new String(pwdDialog.pfPwd.getPassword()); //密码
              if (tableModel.readDatabase(user,pwd)) //读取数据库成功
               break;
              
else //读取数据库失败
               JOptionPane.showMessageDialog(this,"账号或密码错误");
 
 
       }

       table
=new JTable(tableModel); //创建表格
       
//设置成只能选一个数据
       table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
       content.add(
new JScrollPane(table),BorderLayout.CENTER);
       
return (true);
 }

}

 
 
class AppCloser extends WindowAdapter
{
       
public void windowClosing(WindowEvent e)
       
{
              System.exit(
0);
       }

}

 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PasswordDialog extends JDialog implements ActionListener
{
   
public JTextField tfUser; //用来输入账号
   public JPasswordField pfPwd; //用来输入密码
   private JButton btOk,btCancel;
   
public boolean cancel; //是否取消输入
   public PasswordDialog(Frame owner) //构造函数
   {
     
super(owner,"请输入账号密码",true); //设置独占式对话框
     Container content=getContentPane();
     content.setLayout(
new BorderLayout());
     JPanel panel1
=new JPanel();
     panel1.setLayout(
new GridLayout(2,2,0,10));
     panel1.add(
new JLabel("账号",JLabel.CENTER));
     panel1.add(tfUser
=new JTextField(10));
     panel1.add(
new JLabel("密码",JLabel.CENTER));
     panel1.add(pfPwd
=new JPasswordField(10));
     JPanel panel2
=new JPanel();
     panel2.add(btOk
=new JButton("确定"));
     panel2.add(btCancel
=new JButton("取消"));
     btOk.addActionListener(
this);
     btCancel.addActionListener(
this);
     content.add(panel1,BorderLayout.CENTER);
     content.add(panel2,BorderLayout.SOUTH);
     setSize(
300,200);
 
   }

 
   
public void actionPerformed(ActionEvent e)
   
{
          
//实现ActionListener
          cancel=e.getSource()==btCancel; //是否按下“取消”按钮
          setVisible(false); //关闭对话框
   }

}

 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class AddStudentDialog extends JDialog implements ActionListener
{
   
public JTextField tfID,tfName; //用来输入学号与姓名
   private JButton btOK,btCancel;
   
public boolean addOK; //添加是否成功
   public AddStudentDialog(Frame owner)
   
{
          
super(owner,"添加学生",true); //独占式对话框
          Container content=getContentPane();
          content.setLayout(
new BorderLayout());
          JPanel panel1
=new JPanel();
          panel1.setLayout(
new GridLayout(2,2,0,10));
          panel1.add(
new JLabel("学号:",JLabel.CENTER));
          panel1.add(tfID
=new JTextField(10));
          panel1.add(
new JLabel("姓名:",JLabel.CENTER));
          panel1.add(tfName
=new JTextField(10));
          JPanel panel2
=new JPanel();
          panel2.add(btOK
=new JButton("确定"));
          panel2.add(btCancel
=new JButton("取消"));
          btOK.addActionListener(
this);
          btCancel.addActionListener(
this);
          content.add(panel1,BorderLayout.CENTER);
          content.add(panel2,BorderLayout.SOUTH);
          setSize(
300,200);
   }

 
   
public void actionPerformed(ActionEvent e)
 
   
{
      
if (e.getSource()==btOK) //按下“确定”按钮
      {
               
//检查tfID与tfName上的字符串去掉头尾空白后,长度是否皆大于0
               if (tfID.getText().trim().length()>0 &&
                    String.valueOf(tfName.getText()).trim().length()
>0)
                    
{
                             addOK
=true//添加成功
                             setVisible(false); //关闭对话框
                      }

               
else
                  JOptionPane.showMessageDialog(
this,"数据不能是空的");
      }

      
else //按下“取消”按钮
      {
               addOK
=false//添加失败
               setVisible(false); //关闭对话框
 
      }

   }

 
   
public void setVisible(boolean b)
   
{
          
if (b) //如果显示对话框,先将tfID与tfName清干净
          {
                 tfID.setText(
"");
                 tfName.setText(
"");
          }

          
super.setVisible(b);
 
   }

 
}

 
import java.util.*;
import javax.swing.table.*;
import java.sql.*;
public class MyTableModel extends AbstractTableModel
{
   
private Connection connect;
   
private Statement stmt;
   
private PreparedStatement pstmt;
   
private ResultSet result;
   
private Vector rowField;
   
private Vector rowData;
 
   
private String[] columnNames={"学号","姓名","期中考","期末考","平均"};
   
public boolean readDatabase(String user,String pwd)
   
{
      
//读取数据库
      connect=null;
      
try
     
{
               Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
               
//加载驱动程序
      }

      
catch (ClassNotFoundException e1)
      
{
               System.exit(
1);
        }

        
try
        
{
               connect
=DriverManager.getConnection("jdbc:odbc:tablesource",user,pwd);
      }

      
catch (SQLException e2)
      
{
               
return (false);
        }

        
try
        
{
               stmt
=connect.createStatement();
               
//创建数据库表格
               stmt.executeUpdate("create table student(ID varchar2(6),Name varchar2(8),MIDEXAM integer,FINALEXAM integer");
 
      }

      
catch (SQLException e3)
      
{
               
//表格已存在
        }

        
try
        
{
         
int midExam,finalExam;
         result
=stmt.executeQuery("select * from student");
         
//取得索引数据
         rowField=new Vector();
         rowData
=new Vector();
         
while (result.next())
         
{
                      rowField.clear();
                      rowField.add(result.getString(
1)); //学号
                      rowField.add(result.getString(2)); //姓名
                      midExam=result.getInt(3);
                      rowField.add(
new Integer(midExam)); //期中成绩
                      finalExam=result.getInt(4);
                      rowField.add(
new Integer(finalExam)); //期末成绩
                      rowField.add(new Float((midExam+finalExam)/2.0));
                      rowData.add(rowField.clone());
                      
//将roeField复制一份加进rowData
               }

               result.close(); 
//释放ResultSet占用的资源
               
//创建一个PreparedStatement共将来使用
               pstmt=connect.prepareStatement("insert into student values (?,?,?,?)");
 
        }

        
catch (SQLException e4)
        
{
               System.out.println(e4);
        }

        
return (true);
 
   }

 
   
public Class getColumnClass(int col)
   
{
          
//覆盖AbstractTableModel的方法
          return (getValueAt(0,col).getClass()); //返回字段类型
   }

 
   
public int getColumnCount()
   
{
           
//覆盖AbstractTableModel的方法
           return (columnNames.length); //返回字段个数
   }

 
 
   
public String getColumnName(int col)
   
{
           
//覆盖AbstractTableModel的方法
           return (columnNames[col]); //返回字段名称
 
   }

 
  
public int getRowCount()
   
{
           
//覆盖AbstractTableModel的方法
          return (rowData.size()); //返回数据个数
   }

 
 
   
public Object getValueAt(int row,int col)
   
{
           
//覆盖AbstractTableModel的方法
           
//返回第row个第col个字段的值
           return (((Vector)rowData.get(row)).get(col));
   }

 
    
//覆盖AbstractTableModel的方法
    public boolean isCellEditable(int row,int col)
    
{
              
//允许编辑期中考试和期末考试成绩这两个字段
          return (col==2||col==3);
       }

 
        
//覆盖AbstractTableModel的方法
        public void setValueAt(Object value,int row,int col)
        
{
               Integer newValue;
               Vector currentRow
=(Vector)rowData.get(row); //第row个数据
               try
               
{
                      newValue
=Integer.valueOf((String)value);
               }

               
catch (NumberFormatException e1)
               
{
                      newValue
=new Integer(0);
               }

               String id
=(String)currentRow.get(0);
               String columnName
=col==2 ? "MIDEXAM" : "FINALEXAM";
               
try
               
{
                      
//修改数据库
                      stmt.executeUpdate("update srudent set "+columnName+"="+newValue+" where ID='"+id+"'");
                      currentRow.set(col,newValue); 
//修改rowData中的数据
                      
//计算平均分
                      float average=(((Integer)currentRow.get(2)).intValue()+
                                     ((Integer)currentRow.get(
2)).intValue())/(float)2.0;
                      currentRow.set(
4,new Float(average));
                      
//修改rowData中的数据
                      
//更新表格上面显示的数据
                      fireTableCellUpdated(row,4);
               }

               
catch (SQLException e2)
               
{
                      System.out.println(e2);
               }

 
 
        }

   
public void addStudent(String id,String name)
   
{
          
//添加一名学生
          try
          
{
                 pstmt.setString(
1,id);
                 pstmt.setString(
2,name);
                 pstmt.setInt(
3,0);
                 pstmt.setInt(
4,0);
                 pstmt.executeUpdate(); 
//添加一个数据到数据库
                 rowField.clear();
                 rowField.add(id);
                 rowField.add(name);
                 rowField.add(
new Integer(0));
                 rowField.add(
new Integer(0));
                 rowField.add(
new Float(0));
                 rowData.add(rowField.clone()); 
//添加一个数据到rowData
                 
//更新表格上面显示的数据
               fireTableRowsInserted(rowData.size(),rowData.size());
        }

        
catch (SQLException e)
        
{
               System.out.println(e);
        }

 
   }

   
public void delStudent(int row)
   
{
          
//删除一名学生
        String id=(String)((Vector)rowData.get(row)).get(0); //学号
        try
        
{
               stmt.executeUpdate(
"delete from student where ID='"+"'");
               rowData.remove(row); 
//从rowData中删除一个数据
               fireTableRowsInserted(row,row); //更新表格上上面显示的数据
        }

        
catch (SQLException e)
        
{
               System.out.println(e);
        }

   }

}

 
 
原创粉丝点击