Chinaunix首页 | 论坛 | 博客
  • 博客访问: 589422
  • 博文数量: 110
  • 博客积分: 8016
  • 博客等级: 中将
  • 技术积分: 1217
  • 用 户 组: 普通用户
  • 注册时间: 2006-06-28 10:14
文章分类

全部博文(110)

文章存档

2008年(1)

2007年(13)

2006年(96)

我的朋友

分类: Java

2007-12-10 12:00:29

package com.cheney.microsoft.sql;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class QueryFrame extends JFrame  implements ActionListener{ 
 JTextField jf = new JTextField(20); 
 String[] value = {"姓名","部门","薪水"}; 
 JComboBox box = new JComboBox(value); 
 JButton find = new JButton("查询");
 JPanel panel_find = new JPanel();
 JPanel panel_content = new JPanel(); 
 Statement stmt = null; 
 
 public QueryFrame() {
  this.setTitle("查询系统");
  Container c = this.getContentPane();
  
  //完成了查找界面的设置
  jf.addActionListener(this);
  find.addActionListener(this);
  panel_find.add(jf);
  panel_find.add(box);
  panel_find.add(find);  
  
  c.add(panel_find,"North");
  c.add(panel_content,"Center");  
  
  this.setSize(400,400);
  this.setLocation(200,100);
  //连接SQL Server数据库
  try{
   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
   Connection conn =
    DriverManager.getConnection("jdbc:microsoft:sqlserver://10.10.20.43:1433;databasename=JAVATest","pap","321654");
   stmt = conn.createStatement();
  }catch(Exception e){
   e.printStackTrace();
  }
  this.setVisible(true);
 }
 
 public void actionPerformed(ActionEvent e){
  panel_content.removeAll();
  String item = (String)box.getSelectedItem();
  //确定用户所选择的查询依据
  if(item.equals("姓名")){
   item = "name";
  }
  if(item.equals("部门")){
   item = "department";
  }
  if(item.equals("薪水")){
   item = "salary";
  }
  //获取用户输入的查询关键字
  String content = jf.getText();
  int i = 0;
  try{
   String sql = "select * from employee";
   if(!content.equals("")){    
    sql = sql +" where "+item+" like '%"+content+"%'"; //组装查询语句
   }
   
   //执行查询语句,并显示查询结果
   ResultSet rs = stmt.executeQuery(sql);   
   
   while(rs.next()){
    int id = rs.getInt(1);
    String name = rs.getString(2);
    String department = rs.getString(3);
    int salary = rs.getInt(4);
    
    JLabel label = new JLabel(id + "  " + name + "  " + department + "  " + salary);      
    
    JPanel panel = new JPanel();
    panel.add(label);        
    panel_content.add(panel);    
    
    i++;
   }
  }catch(Exception e1){
   e1.printStackTrace();
  }
  panel_content.setLayout(new GridLayout(i,1));
  panel_content.validate();
   
 }
 public static void main(String[] args) {
  new QueryFrame();
 }
}
阅读(3234) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~