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

📄 chinacharconversionframe.java

📁 java数据库编程实例—————————很好很强大第
💻 JAVA
字号:
package chinacharconversion;import com.borland.jbcl.layout.*;import java.awt.*;import java.awt.event.*;import java.lang.*;import java.lang.Object.*;import java.sql.*;import java.util.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.table.*;/**   * Title:				中文字符转换程序   * Description:			教学示范   * Copyright:				Copyright (c) 2003   * Company:				北京师范大学计算机系   * @author				孙一林   * @version				1.0   */public class ChinaCharConversionFrame extends JFrame {  private JPanel contentPane;  private XYLayout xYLayout1 = new XYLayout(); // 构造XYLayout布局管理器  // 创建显示信息的组件  private Label label1 = new Label();  private Label label2 = new Label();  private Label label3 = new Label();  private Label label4 = new Label();  private Label label5 = new Label();  private TextField stunumField = new TextField();  private TextField nameField = new TextField();  private TextField ageField = new TextField();  private TextField sexField = new TextField();  private TextField departmentField = new TextField();  private Button addButton = new Button();  private Button displayButton = new Button();  Vector vector;                                         // 声明一个向量对象  String title[] = {"学号","姓名","年龄","性别","系名"};    // 二维表列名  Connection connection = null;                          // 声明Connection接口对象connection  ResultSet rs = null;                                   // 定义数据库查询的结果集  Statement statement = null;                            // 定义查询数据库的Statement对象  AbstractTableModel tm;                                 // 声明一个AbstractTableModel类对象tm  String name,sex,department;                     // 定义姓名、性别、系名文本框对应的字符串变量以进行转换  public ChinaCharConversionFrame() {    enableEvents(AWTEvent.WINDOW_EVENT_MASK);    try {      jbInit();    }    catch(Exception e) {      e.printStackTrace();    }  }  private void jbInit() throws Exception  {    contentPane = (JPanel) this.getContentPane();     // 初始化组件    label1.setText("学号");    contentPane.setLayout(xYLayout1);    this.setSize(new Dimension(432, 434));    this.setTitle("中文字符转换");    label2.setText("姓名");    label3.setText("年龄");    label4.setText("性别");    label5.setText("系名");    addButton.setLabel("添加记录");    addButton.addActionListener(new java.awt.event.ActionListener() {// 设置addButton按钮监听器      public void actionPerformed(ActionEvent e) {        addButton_actionPerformed(e);      }    });    displayButton.setLabel("显示所有记录");    displayButton.addActionListener(new java.awt.event.ActionListener() {// 设置displayButton按钮监听器      public void actionPerformed(ActionEvent e) {        displayButton_actionPerformed(e);      }    });    contentPane.add(displayButton,  new XYConstraints(226, 325, -1, 34));    contentPane.add(label1,  new XYConstraints(39, 256, 41, 26));    contentPane.add(label2,  new XYConstraints(113, 256, 41, 26));    contentPane.add(label3,  new XYConstraints(187, 256, 41, 26));    contentPane.add(label4,  new XYConstraints(260, 256, 41, 26));    contentPane.add(label5,  new XYConstraints(334, 256, 41, 26));    contentPane.add(stunumField,  new XYConstraints(29, 286, 59, 26));    contentPane.add(nameField,  new XYConstraints(104, 286, 59, 26));    contentPane.add(ageField,  new XYConstraints(180, 286, 59, 26));    contentPane.add(sexField,  new XYConstraints(255, 286, 59, 26));    contentPane.add(departmentField,  new XYConstraints(330, 286, 59, 26));    contentPane.add(addButton,  new XYConstraints(86, 325, 107, 34));    createtable();                                 // 在初始化函数中调用createtable()函数显示表格  }  void createtable() {                             // 定义createtable()函数    JTable table;                                  // 声明一个JTable类对象table    JScrollPane scroll;                            // 声明一个滚动杠对象scroll    vector = new Vector();                         // 创建向量对象    tm = new AbstractTableModel() {                // 创建AbstractTableModel类对象tm      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_OFF);      // 设置表格调整尺寸模式    table.setCellSelectionEnabled(false);                // 设置单元格选择方式    table.setShowHorizontalLines(true);                  // 设置是否显示单元格之间的分割线    table.setShowVerticalLines(true);    scroll = new JScrollPane(table);                     // 给表格加上滚动杠    scroll.setBounds(6,20,540,250);    contentPane.add(scroll,new XYConstraints(16, 20, 395, 200));  }  protected void processWindowEvent(WindowEvent e) {    super.processWindowEvent(e);    if (e.getID() == WindowEvent.WINDOW_CLOSING) {      System.exit(0);    }  }  public static String toTureAsciiStr(String str){  // 定义将中英文字串转换成纯英文字串共用静态方法    StringBuffer sb=new StringBuffer();    byte[] bt=str.getBytes();                       // 把要转换的字符串转换为字节形式    for(int i=0;i<bt.length;i++){      if(bt[i]<0){                                  // 判断是否为汉字,如是则去高位1        sb.append((char)(bt[i]&(0x7f)));      }      else{                                         // 是英文字符补0作记录        sb.append((char)0);        sb.append((char)bt[i]);      }    }    return  sb.toString();                          // 返回转换后的英文字符串  }  public static String unToTrueAsciiStr(String str){// 定义将经转换的字串还原方法    byte[] bt=str.getBytes() ;    int i;    int l=0;    int length=bt.length;    int j=0;    for(i=0;i<length;i++){                          // 判断有几个英文字符以去除Byte 0      if(bt[i]==0){        l++;        }    }    byte[] bt2=new byte[length-l];                  // 定义返回的字节数组    for(i=0;i<length;i++){      if(bt[i]==0){                                 // 是英文字符去掉0        i++;        bt2[j]=bt[i];      }      else{                                         // 是汉字补上高位1        bt2[j]=(byte)(bt[i]|0x80);      }      j++;    }    String tt=new String(bt2);    return tt;                                     // 返回还原后的字符串  }  void addButton_actionPerformed(ActionEvent e) {    try {      // 调用toTureAsciiStr()函数将中英文信息转换为英文信息      name=toTureAsciiStr(nameField.getText());      sex=toTureAsciiStr(sexField.getText());      department=toTureAsciiStr(departmentField.getText());      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  // 实例化JDBC-ODBC桥的驱动      String url = "jdbc:odbc:TestDbStu";             // 设置连接字符串      connection = DriverManager.getConnection(url); // 连接数据库      statement = connection.createStatement();      String sql = "insert into studentbase (学号,姓名,年龄,性别,系名) values (" +Integer.parseInt(stunumField.getText()) +", '" +name+"',"+Integer.parseInt(ageField.getText())+",'"+sex+"',"+"'"+department+ "')";      statement.executeUpdate(sql);             // 执行增加新的数据记录语句      // 清空文本框信息      stunumField.setText("");      nameField.setText("");      ageField.setText("");      sexField.setText("");      departmentField.setText("");    }    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 displayButton_actionPerformed(ActionEvent e) {    try {      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");   // 实例化JDBC-ODBC桥的驱动      String url = "jdbc:odbc:TestDbStu";              // 设置连接字符串      connection = DriverManager.getConnection(url);   // 连接数据库      // 创建Statement接口对象      statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);      String sql = "select * from studentbase";      // 执行statement对象的executeQuery方法,查询studentbase表,将查询结果放入rs中      ResultSet rs = statement.executeQuery(sql);      vector.removeAllElements();                      // 初始化向量对象      tm.fireTableStructureChanged();                  // 更新表格内容      while(rs.next()) {        Vector rec_vector = new Vector();        // 从结果集中取数据放入向量rec_vector中        rec_vector.addElement(String.valueOf(rs.getInt("学号")));        rec_vector.addElement(unToTrueAsciiStr(rs.getString("姓名"))); // 调用unToTrueAsciiStr函数还原为中文信息再添加        rec_vector.addElement(String.valueOf(rs.getInt("年龄")));        rec_vector.addElement(unToTrueAsciiStr(rs.getString("性别"))); // 调用unToTrueAsciiStr函数还原为中文信息再添加        rec_vector.addElement(unToTrueAsciiStr(rs.getString("系名"))); // 调用unToTrueAsciiStr函数还原为中文信息再添加        vector.addElement(rec_vector);                 // 向量rec_vector加入向量vector中      }      tm.fireTableStructureChanged();                  // 更新表格,显示向量vector的内容      rs.close() ;                                         // 关闭结果集    }    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 + -