📄 preparequery.java
字号:
import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
public class PrepareQuery extends JFrame
implements ActionListener {
JTextField tfDepartment=new JTextField();
JLabel lbDepartment=new JLabel("系别");
JButton btnQuery=new JButton("查询");
JPanel panel=new JPanel();
JTextArea taInfo=new JTextArea();
public PrepareQuery() {
super("预编译语句");
setSize(350,260);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
panel.setLayout(new BorderLayout());
panel.add(lbDepartment,BorderLayout.WEST);
panel.add(tfDepartment,BorderLayout.CENTER);
panel.add(btnQuery,BorderLayout.EAST);
btnQuery.addActionListener(this);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(panel,BorderLayout.NORTH);
getContentPane().add(taInfo);
}
public void getRecord(String strDepartment)throws SQLException {
Connection con=null;
try {
//加载驱动程序
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex){
taInfo.setText(ex.getMessage());
System.exit(-1);
}
try {
//试图通过ODBC建立一个与学生管理数据库的连接
String URL = "jdbc:odbc:学生信息管理";
con = DriverManager.getConnection(URL);
//定义带参数的预编译语句
String SQL="SELECT 学号,姓名,年龄,系别 FROM 学生信息表"
+" WHERE 系别=?";
PreparedStatement preSt = con.prepareStatement(SQL);
//为参数指定值
preSt.setString(1,strDepartment);
ResultSet rs=preSt.executeQuery();
taInfo.setText("");//清空文本框
while (rs.next()) {
//将结果集中的数据添加到文本框中
taInfo.append(rs.getString("学号") + "\t");
taInfo.append(rs.getString("姓名") + "\t");
taInfo.append(rs.getString("年龄") + "\t");
taInfo.append(rs.getString("系别") + "\n");
}
rs.close();
preSt.close();
}
catch(SQLException ex){
taInfo.setText(ex.getMessage());
}
finally{
con.close();
}
}
public static void main(String[] args) {
PrepareQuery frame = new PrepareQuery();
frame.show();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() ==btnQuery){
String str=tfDepartment.getText();
try{
getRecord(str);
}
catch(SQLException ex){
taInfo.setText(ex.getMessage());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -