⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqltimestampframe.java

📁 JAVA数据库编程实例随书源码
💻 JAVA
字号:
package sqltimestamp;import java.awt.*;import java.awt.event.*;import java.sql.*;import java.util.*;import javax.swing.*;import javax.swing.table.*;/** * Title:			使用Timestamp类进行数据库操作 * Description:			教学示范 * Copyright:			Copyright (c) 2003 * Company:			北京师范大学计算机系 * @author			孙一林 * @version			1.0 */public class sqlTimeStampFrame extends JFrame {  private JPanel contentPane;  private Label label1 = new Label();  private TextField nameField = new TextField();  private Button insertButton = new Button();  private Button refreshButton = new Button();  Connection connection = null;                //定义与数据库进行连接的Connection对象  ResultSet rs = null;                         //定义数据库查询的结果集  Statement statement = null;                  //定义查询数据库的Statement对象  boolean lastQuery = false;                   //上次查询是否成功  Vector vector;                               //定义存储结果集数据的数组  String[] title = {"姓名","访问时间"};          //定义显示数据表格的标题  AbstractTableModel tm;                       //定义显示数据表格的抽象类  JScrollPane scroll;                          //定义装载数据表格的容器  public sqlTimeStampFrame() {    enableEvents(AWTEvent.WINDOW_EVENT_MASK);    try {      jbInit();    }    catch(Exception e) {      e.printStackTrace();    }  }  private void jbInit() throws Exception  {          //初始化用户界面    contentPane = (JPanel) this.getContentPane();    refreshButton.setLabel("刷新访问记录");    refreshButton.setBounds(new Rectangle(206, 308, 111, 28));    refreshButton.addActionListener(new java.awt.event.ActionListener() {      public void actionPerformed(ActionEvent e) {        refreshButton_actionPerformed(e);      }    });    insertButton.setLabel("添加访问记录");    insertButton.setBounds(new Rectangle(89, 308, 107, 28));    insertButton.addActionListener(new java.awt.event.ActionListener() {      public void actionPerformed(ActionEvent e) {        insertButton_actionPerformed(e);      }    });    label1.setText("姓名:");    label1.setBounds(new Rectangle(105, 19, 39, 25));    contentPane.setLayout(null);    this.setSize(new Dimension(400, 385));    this.setTitle("使用时间戳存取数据库");    nameField.setBounds(new Rectangle(151, 19, 143, 25));    contentPane.add(nameField, null);    contentPane.add(label1, null);    contentPane.add(refreshButton, null);    contentPane.add(insertButton, 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(50,50,300,200);    contentPane.add(scroll,null);  }  protected void processWindowEvent(WindowEvent e) {    super.processWindowEvent(e);    if (e.getID() == WindowEvent.WINDOW_CLOSING) {      try      {        connection.close();      }      catch(Exception ex)      {        ex.printStackTrace();      }      System.exit(0);    }  }  void insertButton_actionPerformed(ActionEvent e) { //将用户名以及访问时间插入数据库    String name = nameField.getText();    java.sql.Timestamp timestamp = new java.sql.Timestamp(new java.util.Date().getTime()); //创建Timestamp类实例并将当前时间值赋给给此实例    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_UPDATABLE);  //创建Statement接口实例      String now_Timestamp = timestamp.toString();     //将Timestamp类实例所代表的时间值转换为字符串表示      String sql = "insert into studentvisiting(姓名,访问时间) values('" + name + "', '" + now_Timestamp + "')";      //创建插入studentvisiting表数据的SQL语句      statement.executeUpdate(sql);                    //将新的数据插入到数据库      JOptionPane msg = new JOptionPane();      JOptionPane.showMessageDialog(this, "添加记录成功", "添加记录成功!", 1);    }    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 refreshButton_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 studentvisiting";    //创建取出studentvisiting表中所有数据的SQL语句      rs = statement.executeQuery(sql);                //将数据存入结果集中      vector.removeAllElements();      tm.fireTableStructureChanged();                  //刷新表格显示结果集中的数据      while(rs.next())      {        Vector rec_vector = new Vector();        rec_vector.addElement(rs.getString("姓名"));        rec_vector.addElement(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());      }    }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -