Java访问数据库sql server 增删改查 第六篇

chaxun.java

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;

import javax.swing.*;

class chaxun extends JDialog implements ActionListener
{
   JLabel bq1;
   JTextField wbk1;
   JButton an1;
   JPanel mb1,mb2;
   JTable bg1;
   JScrollPane gd1;
   
   Vector ziduan,jilu;//集合类:hengshu
	PreparedStatement ps=null;//作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能
	Connection ct=null;
	ResultSet rs=null;
	
	
   public chaxun(Frame fck,String ckm,Boolean msck)
   {
	   super(fck,ckm,msck);
	   bq1=new JLabel("   学号: ");
	   wbk1=new JTextField(5); 
	   
	   an1=new JButton("查询");
	   an1.addActionListener(this);
	   an1.setActionCommand("cx");
	   
	   mb1=new JPanel();
	   mb2=new JPanel();
	  
	   
	   mb1.setLayout(new GridLayout(1,2));
	 
	   
	   mb1.add(bq1);  mb1.add(wbk1); mb2.add(an1);
	   
	   Vector ziduan,jilu;//集合类:hengshu
		ziduan=new Vector();
		ziduan.add("学号");
		ziduan.add("姓名");
		ziduan.add("性别");
		ziduan.add("年龄");
		
		jilu=new Vector();
		 try{
			  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			  ct=DriverManager.getConnection("jdbc:odbc:sql server");
			  ps=ct.prepareStatement("select * from Table_3");
			  rs=ps.executeQuery();
			  
			  while(rs.next()){
				  Vector hang=new Vector();
				  hang.add(rs.getString(1));
				  hang.add(rs.getString(2));
				  hang.add(rs.getString(3));
				
				  hang.add(rs.getString(4));
				  
				  jilu.add(hang);
			  }
		 }catch(Exception e){}
		 finally{
				try{
					if(rs!=null)
					{
						rs.close();
					}
					if(ps!=null)
					{
						ps.close();
					}
					if(ct!=null)
					{
						ct.close();
					}
				}catch(Exception e){}
		 }
		
		 bg1=new JTable(jilu,ziduan);
		 gd1=new JScrollPane(bg1);
	   this.add(gd1);
	   this.add(mb1,BorderLayout.NORTH);
	   this.add(mb2,BorderLayout.SOUTH);
	  	   
	  	this.setSize(370,270);
		this.setLocation(401,281);
		this.setResizable(false);
		//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);		   
   }
   public void actionPerformed(ActionEvent e)
   {
	   if(e.getActionCommand().equals("cx"))
	   {
		   PreparedStatement ps=null;
		   Connection ct=null;
		   ResultSet rs=null;
		   Statement sm=null;
		   
		   try {
				String xueh=this.wbk1.getText().trim();
				String sql="select * from Table_3 where xuehao='"+xueh+"'";
				xsxx xsxx2=new xsxx(sql);
				bg1.setModel(xsxx2);
				 				  
			} catch (Exception e2){}
		    finally
		    {
		    	try {
		    		if(rs!=null)
					{
						rs.close();
					}
		    		if(ps!=null)
					{
						ps.close();
					}
					if(ct!=null)
					{
						ct.close();
					}
					
				} catch (Exception e3){}		
		    }
	   }
	   else if(e.getActionCommand().equals("quxiao"))
	   {
		   this.dispose();
	   }
   }
}
Java访问数据库sql server 增删改查 第六篇_第1张图片

你可能感兴趣的:(Java访问数据库sql server 增删改查 第六篇)