📄 studentquery.java
字号:
/*查询学生信息程序StudentQuery.java*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class StudentQuery extends JFrame implements ActionListener
{ JTextField [] value=new JTextField[6]; //一次可显示6个学生信息
JTextField condition=new JTextField(10); //输入查询条件框
JButton queryButton,exitButton; //查询按钮和退出按钮
JPanel panel1,panel2; //panel1放置条件输入框和按钮panel2显示学生信息
OperateDatabase op1=new OperateDatabase("students","sa","");//操作对象
public StudentQuery(String cond) //构造方法,参数为查询条件
{ Container content=this.getContentPane(); //获得JFrame的容器
content.setLayout(new GridLayout(2,1)); //以上下在容器上摆放两个JPanel
if(cond!=null) //如果带条件串构造对象
{ condition.setText(cond); //则不需要再输入条件,将参数条件串设置为条件
condition.setEditable(false); //设置条件框是不可输入的
}
for(int i=0;i<value.length; i++) value[i] = new JTextField(30);
queryButton = new JButton("查询");
exitButton = new JButton("退出");
panel1=new JPanel(new GridLayout(4,1)); //以4行1列在panel1上摆放构件
panel2=new JPanel(new GridLayout(7,1)); //以7行1在panel2上摆放构件
panel1.add(new JLabel("输入条件如:学号='20060132102'或入学成绩>600等"));
panel1.add(condition); //在panel1上摆放
panel1.add(queryButton); //
panel1.add(exitButton); //
panel2.add(new JLabel("---------- 学号---------姓名--出生年月--性别--入学成绩-备注")); //在panel2上摆放构件
for(int i=0;i<value.length; i++) panel2.add(value[i]); //
content.add(panel1); //将panel1摆放到JFrame的容器上
content.add(panel2); //将panel2摆放到JFrame的容器上
queryButton.addActionListener(this); //注册按钮的监听对象
exitButton.addActionListener(this); //
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent evt) //实现单击按钮事件方法
{ Object obj = evt.getSource(); //获得事件源对象
if(obj == queryButton)
{panel1.setVisible(false); //隐藏panel1上构件的功能,保证本查询完成
try
{ String cond=condition.getText().trim();//获得查询条件
if(cond.length()>1) cond=" where "+cond; //若输入有条件,则相应处理
String sqlstr="select * from login "+cond;//组成SQL查询串
ResultSet rs=op1.query(sqlstr); //执行查询,返回结果集
int count=0; //设置显示计数
while(rs.next()) //当结果集中有数据时,逐行输出
{ String str="";
for(int i=1; i<=6; i++)
{ String temp=rs.getString(i); //处理读出的字段值
if(temp==null) temp=" "; //处理空指针内容
str=str+temp.trim()+" "; //形成输出串
}
value[count].setText(str); //输出一个学生的信息
count++; //计数加1
if(count>=value.length) //已达到最大计数,即输出位置已满
{ count=0; //计数重新开始,输出剩余的记录
JOptionPane.showMessageDialog(null,"下一屏!","提示信息",JOptionPane.PLAIN_MESSAGE); //输出提示信息,按键继续剩余记录的输出
}
}
for(;count<value.length;count++) value[count].setText("");//清除重叠
}
catch(Exception e) { System.out.println("Error:"+e); }
panel1.setVisible(true);
}
else { System.exit(0); }
}
public static void main(String [] args) //main()方法
{ new StudentQuery(null); } //main()方法结束
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -