import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import java.sql.*;
public class DbQueryBean extends JPanel {
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private JTextField textField;
private String url = null;
private String strSql = null;
private String strDriver = null;
private Connection conn = null;
private ResultSet result = null;
private Statement statement = null;
/** * Create the panel */ public DbQueryBean() { super(); setLayout(null);
textField = new JTextField(); textField.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { dbConnection(); dbQuery(); dbClose(); } }); textField.setBounds(10, 10, 365, 25); add(textField);
final JButton button = new JButton(); button.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { dbConnection(); dbQuery(); dbClose(); } }); button.setText("执行"); button.setBounds(405, 10, 60, 25); add(button);
final JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 62, 480, 303); add(scrollPane);
textArea = new JTextArea(); scrollPane.setViewportView(textArea); //
}
public void dbConnection() {
try { Class.forName(strDriver); conn = DriverManager.getConnection(url); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "连接数据库出错", "error!", JOptionPane.ERROR_MESSAGE); } }
public void dbQuery() { strSql = textField.getText().trim(); String strData = ""; try { statement = conn.createStatement(); result = statement.executeQuery(strSql); ResultSetMetaData meta = result.getMetaData(); int colCount = meta.getColumnCount(); // 得到表中的列数
for (int i = 1; i <= colCount; i++) { strData += " " + meta.getColumnName(i).trim(); // 得到标题
// trim()是除去前后的空格
} strData += "\n";
while (result.next()) { for (int i = 1; i <= colCount; i++) { strData += " " + result.getString(i).trim(); // 得到每一行的数据
} strData += "\n"; } } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "数据库查询出错", "error!", JOptionPane.ERROR_MESSAGE); }
textArea.setText(strData); }
public void dbClose() { try { statement.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "关闭数据库出错", "error!", JOptionPane.ERROR_MESSAGE); }
}
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public void clearTextArea() { textArea.setText(""); }
public String getStrDriver() { return strDriver; }
public void setStrDriver(String strDriver) { this.strDriver = strDriver; }
}
|