📄 connecttodbframe.java
字号:
package connecttodb;import java.awt.*;import java.awt.event.*;import java.sql.*;import java.util.*;import javax.swing.*;import javax.swing.table.*;/** * Title: 使用不同方式进行数据库连接 * Description: 教学示范 * Copyright: Copyright (c) 2003 * Company: 北京师范大学计算机系 * @author 孙一林 * @version 1.0 */public class connectToDbFrame extends JFrame { private JPanel contentPane; private Button connectODBCButton = new Button(); private Button connectMySQLButton = new Button(); String[] title = {"学号", "姓名", "年龄", "性别", "系名"}; //定义显示数据表格的标题 Connection connection = null; //定义与数据库进行连接的Connection对象 ResultSet rs = null; //定义数据库查询的结果集 Statement statement = null; //定义查询数据库的Statement对象 boolean lastQuery = false; //上次查询是否成功 Vector vector; //定义存储结果集数据的数组 AbstractTableModel tm; //定义显示数据表格的抽象类 JScrollPane scroll; //定义装载数据表格的容器 public connectToDbFrame() { enableEvents(AWTEvent.WINDOW_EVENT_MASK); try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { contentPane = (JPanel) this.getContentPane(); connectODBCButton.setLabel("使用ODBC连接Access数据库"); connectODBCButton.setBounds(new Rectangle(111, 335, 201, 28)); connectODBCButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { connectODBCButton_actionPerformed(e); } }); contentPane.setLayout(null); this.setSize(new Dimension(422, 438)); this.setTitle("连接各种数据库"); connectMySQLButton.setLabel("连接MYSQL数据库"); connectMySQLButton.setBounds(new Rectangle(111, 369, 201, 28)); connectMySQLButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { connectMySQLButton_actionPerformed(e); } }); contentPane.add(connectMySQLButton, null); contentPane.add(connectODBCButton, null); } void initTable() { //初始化显示数据集结果的表格 JTable table; vector = new Vector(); tm = new AbstractTableModel() { //实现表格抽象类的接口 public int getColumnCount() { return title.length; } public int getRowCount() { return vector.size(); } public Object getValueAt(int row, int column) { if(!vector.isEmpty()) { return ((Vector)vector.elementAt(row)).elementAt(column); } else { return null; } } public void setValueAt(Object value, int row, int column) { } public String getColumnName(int column) { return title[column]; } public Class getColumnClass(int c) { return getValueAt(0,c).getClass(); } public boolean isCellEditable(int row, int column) { return false; } }; table = new JTable(tm); table.setToolTipText("Display Query Result"); table.setAutoResizeMode(table.AUTO_RESIZE_SUBSEQUENT_COLUMNS); table.setCellSelectionEnabled(false); table.setShowHorizontalLines(true); table.setShowVerticalLines(true); scroll = new JScrollPane(table); scroll.setBounds(10,10,400,200); contentPane.add(scroll,null); } protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); } } void connectODBCButton_actionPerformed(ActionEvent e) { if(lastQuery) //若上次查询成功,则首先清除上次查询的表格 { scroll.setVisible(false); contentPane.remove(scroll); } initTable(); //初始化新的表格 try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //指定与数据库连接使用JDBC-ODBC桥驱动程序 String url = "jdbc:odbc:student"; //指定数据源名 connection = DriverManager.getConnection(url); //与数据源建立连接 statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); //创建Statement接口实例 String sql = "select * from studentbase"; //创建取出studentbase表中所有数据的SQL语句 rs = statement.executeQuery(sql); //将数据存入结果集中 vector.removeAllElements(); tm.fireTableStructureChanged(); //刷新表格显示结果集中的数据 while(rs.next()) { Vector rec_vector = new Vector(); rec_vector.addElement(String.valueOf(rs.getInt("学号"))); rec_vector.addElement(rs.getString("姓名")); rec_vector.addElement(String.valueOf(rs.getInt("年龄"))); rec_vector.addElement(String.valueOf(rs.getString("性别"))); rec_vector.addElement(String.valueOf(rs.getString("系名"))); vector.addElement(rec_vector); } tm.fireTableStructureChanged(); lastQuery = true; //数据库查询操作成功 } catch(SQLException ex){ //捕捉异常 System.out.println("\nERROR:----- SQLException -----\n"); while (ex != null) { System.out.println("Message: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("ErrorCode: " + ex.getErrorCode()); ex = ex.getNextException(); } } catch(Exception ex ) { ex.printStackTrace(); } finally { try { if(statement != null) { statement.close(); //关闭Statement接口实例 } if(connection != null) { connection.close(); //关闭Connection接口实例 } } catch (SQLException ex) { System.out.println("\nERROR:----- SQLException -----\n"); System.out.println("Message: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("ErrorCode: " + ex.getErrorCode()); } } } void connectMySQLButton_actionPerformed(ActionEvent e) { if(lastQuery) //若上次查询成功,则首先清除上次查询的表格 { scroll.setVisible(false); contentPane.remove(scroll); } initTable(); //初始化新的表格 try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); //指定与数据库连接使用MySQL驱动程序 String url ="jdbc:mysql://10.2.157.149:3306/student"; //指定数据库服务器的IP地址与端口号以及数据库名 String userName ="root"; //指定用户名 String password =""; //指定密码 connection = DriverManager.getConnection(url, userName, password); //与数据源建立连接 statement = connection.createStatement(); //创建Statement接口实例 String sql = "select * from studentbase"; //创建取出studentbase表中所有数据的SQL语句 rs = statement.executeQuery(sql); //将数据存入结果集中 vector.removeAllElements(); tm.fireTableStructureChanged(); //刷新表格显示结果集中的数据 while(rs.next()) { Vector rec_vector = new Vector(); rec_vector.addElement(String.valueOf(rs.getInt("student_number"))); rec_vector.addElement(rs.getString("name")); rec_vector.addElement(String.valueOf(rs.getInt("age"))); rec_vector.addElement(String.valueOf(rs.getString("sex"))); rec_vector.addElement(String.valueOf(rs.getString("department"))); vector.addElement(rec_vector); } tm.fireTableStructureChanged(); lastQuery = true; //数据库查询操作成功 } catch(SQLException ex){ //捕捉异常 System.out.println("\nERROR:----- SQLException -----\n"); while (ex != null) { System.out.println("Message: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("ErrorCode: " + ex.getErrorCode()); ex = ex.getNextException(); } } catch(Exception ex ) { ex.printStackTrace(); } finally { try { if(statement != null) { statement.close(); //关闭Statement接口实例 } if(connection != null) { connection.close(); //关闭Connection接口实例 } } catch (SQLException ex) { System.out.println("\nERROR:----- SQLException -----\n"); System.out.println("Message: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("ErrorCode: " + ex.getErrorCode()); } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -