1. 主窗體界面,代碼如下:
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class BoxLayoutFrame extends JFrame { private JTextField textField; private JTextArea textArea; public static void main(String[] args) { // TODO Auto-generated method stub BoxLayoutFrame frame=new BoxLayoutFrame(); frame.setVisible(true); } public BoxLayoutFrame() { super(); setTitle("箱式布局管理界面"); setBounds(360,260,360,320); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container cp=getContentPane(); Box topicBox=Box.createHorizontalBox(); //創建一個水平箱容器 cp.add(topicBox, BorderLayout.NORTH); //添加到窗體中的最北部 topicBox.add(Box.createHorizontalStrut(5)); //添加一個5像素的水平支柱 JLabel topicLabel=new JLabel("主題:"); //創建標簽topicLabel topicBox.add(topicLabel); //添加到水平箱容器中 topicBox.add(Box.createHorizontalStrut(5)); //添加一個5像素的水平支柱 textField=new JTextField(80); //創建文本框 topicBox.add(textField); //添加到水平容器中 Box box=Box.createVerticalBox(); //創建一個垂直箱容器 cp.add(box, BorderLayout.CENTER); //添加到窗體中 box.add(Box.createVerticalStrut(5)); //添加一個5像素的垂直支柱 Box contentBox=Box.createHorizontalBox(); //創建一個水平箱容器 contentBox.setAlignmentX(1); //設置組件的水平調整值,靠右對齊 box.add(contentBox); //添加到垂直容器中 contentBox.add(Box.createHorizontalStrut(5)); //添加一個5像素的水平支柱 JLabel contentLabel=new JLabel("內容:"); //定義標簽contentLabel contentLabel.setAlignmentY(0); //設置組件的垂直調整值,靠上方對齊 contentBox.add(contentLabel); //添加到水平箱容器中 contentBox.add(Box.createHorizontalStrut(5)); //添加一個5像素 JScrollPane scrollPane=new JScrollPane(); //創建滾動面板 scrollPane.setAlignmentY(0); //設置組件的垂直調整值,向上對齊 contentBox.add(scrollPane); //將滾動面板添加到contentBox中 textArea=new JTextArea(); //創建文本框textArea textArea.setLineWrap(true); //允許自動換行 scrollPane.setViewportView(textArea); //文本框添加到滾動面板scrollPane box.add(Box.createVerticalStrut(5)); //添加一個5像素高的垂直支柱 Box bottomBox=Box.createHorizontalBox(); bottomBox.setAlignmentX(1); box.add(bottomBox,BorderLayout.SOUTH); JButton viewButton=new JButton("瀏覽記錄"); bottomBox.add(viewButton); viewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SelectFrame sframe=new SelectFrame(BoxLayoutFrame.this); sframe.setVisible(true); } }); JButton button=new JButton("確定"); //創建一個按鈕button button.setAlignmentX(1); //設置組件的水平調整值,靠右對齊 //box.add(button); //按鈕添加到垂直箱容器 bottomBox.add(button); button.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent arg1) { //System.exit(0); if(textField.getText().length()==0) {//如果文本框無輸入信息則不作任何處理 } if(!textField.getText().equals("")) { TbNews tbs=new TbNews(); tbs.setTopicId(textField.getText()); tbs.setContentTxt(textArea.getText()); boolean res =DbOperation.getInstance().addTbNews(tbs); if (res==true) { textField.setText(null); textArea.setText(null); } } } }); } }
2. 數據庫連接類,本示例數據庫是SQL Server2008 R2。代碼如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DbTool { private static Connection conn=null; //創建Connection對象 public static Connection getConn() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //加載SQL Server數據庫驅動 } catch(ClassNotFoundException e) { e.printStackTrace(); } //指定連接數據庫的URL String url="jdbc:sqlserver://localhost:1433;databaseName=SRM"; String user="sa"; //指定連接數據庫的用戶名 String passWord="1111"; //指定連接數據庫的密碼 try { conn=DriverManager.getConnection(url,user,passWord); if(conn!=null) { //如果Connection實例不為空 //System.out.println("數據庫連接成功"); //提示信息 } /* //加載MySQL數據庫的連接 Class.forName("com.mysql.jdbc.Driver"); //加載MySQL數據庫驅動 String url="jdbc:mysql://localhost:3306/SRM"; String user="sa"; String passWord="1111"; conn=DriverManager.getConnection(url,user,passWord); if(conn!=null){ } //加載Oracle數據庫的連接 Class.forName("oracle.jdbc.driver.OracleDriver");// 加載Oracle驅動程序 String url = "jdbc:oracle:" + "thin:@127.0.0.1:1521:SRM";// 127.0.0.1是本機地址,SRM是精簡版Oracle的默認數據庫名 String user = "sa";// 用戶名 String password = "1111";// 你安裝時選設置的密碼 conn = DriverManager.getConnection(url, user, password);// 獲取連接 */ } catch(SQLException e) { e.printStackTrace(); } return conn; } }
3. 數據庫操作類,示例代碼如下:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Vector; public class DbOperation { private static DbOperation instance = null; public static DbOperation getInstance() { //返回DbOperation類實例的靜態方法,單例模式!!!! if (instance == null) { instance = new DbOperation(); } return instance; } public boolean addTbNews(TbNews tns) { //添加數據方法 Connection conn=null; boolean result=false; try { conn=DbTool.getConn(); //建立與數據庫的連接 String sqlInsert="INSERT INTO tbNews(topicId,contentTxt)VALUES(?,?)"; PreparedStatement stm=conn.prepareStatement(sqlInsert); stm.setString(1, tns.getTopicId()); stm.setString(2, tns.getContentTxt()); int i=stm.executeUpdate(); if (i==1) { result=true; } }catch(SQLException e) { e.printStackTrace(); }finally { try { conn.close(); }catch (SQLException e) { e.printStackTrace(); } } return result; } public Vector<TbNews> queryTbNews(){ //返回Vector類型方式查詢數據 Vector<TbNews> list =new Vector<TbNews>(); Connection conn=null; try { conn=DbTool.getConn(); Statement stmt=conn.createStatement(); String querySql="select * from TbNews"; ResultSet rs=stmt.executeQuery(querySql); while(rs.next()) { TbNews tbs=new TbNews(); tbs.setTopicId(rs.getString(1)); tbs.setContentTxt(rs.getString(2)); list.add(tbs); } } catch(Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch(SQLException e) { e.printStackTrace(); } } return list; } public List<String> selectTbNews(){ //查詢數據方法 List<String> tbsList=new ArrayList<String>(); Connection conn=null; try { conn=DbTool.getConn(); Statement stmt=conn.createStatement(); String selectSql="select * from TbNews"; ResultSet rs=stmt.executeQuery(selectSql); //執行SQL並返回結果集 while(rs.next()) { String tbs=rs.getString("topicId")+","+rs.getString("contentTxt"); tbsList.add(tbs); } } catch(Exception e) { e.printStackTrace(); } finally { try { conn.close(); //關閉連接 }catch(SQLException e) { e.printStackTrace(); } } return tbsList; } } /* package 數據庫_向數據庫插入數據; import java.sql.Connection; import java.sql.DriverManager; public class DatabaseConnection { private static Connection conn = null; public static Connection getCon() { try { Class.forName("com.mysql.jdbc.Driver"); //加載數據庫連接驅動 String user = "root"; String psw = "XXX"; //XXX為自己的數據庫的密碼 String url = "jdbc:mysql://localhost:3306/ZZZ"; //ZZZ為連接的名字 conn = DriverManager.getConnection(url, user, psw); //獲取連接 } catch (Exception e) { System.out.println("連接數據庫失敗"); e.printStackTrace(); } return conn; } } package 數據庫_向數據庫插入數據; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; //EmployeeOperation類用於操作數據庫,以下的編寫方法是JAVA軟件編程的一種設計模式,稱為!!!!! 單例模式,!!!!!!! //方法中先判斷該類的對象是否為空,只有為空才創建(new) ,因此保證該對象在程序中永遠是唯一的,可以避免重復創建對象造成的系統內存被過多占用 public class EmployeeOperation { private static EmployeeOperation instance = null; public static EmployeeOperation getInstance() { //返回EmployeeOperation類實例的靜態方法,單例模式!!!! if (instance == null) { instance = new EmployeeOperation(); } return instance; } public boolean saveEmployee(Employee emp) { //向數據庫中加入數據 boolean result = false; Connection conn = null; try { conn = DatabaseConnection.getCon(); //建立數據庫連接 String sqlInset = "insert into company.tb_employee(empId, empName, empAge, empSex) values(?, ?, ?, ?)"; PreparedStatement stmt = conn.prepareStatement(sqlInset); //會拋出異常 stmt.setInt(1, emp.getEmpId()); //設置SQL語句第一個“?”的值 stmt.setString(2, emp.getEmpName()); //設置SQL語句第二個“?”的值 stmt.setInt(3, emp.getEmpAge()); //設置SQL語句第三個“?”的值 stmt.setString(4, emp.getEmpSex()); //設置SQL語句第四個“?”的值 int i = stmt.executeUpdate(); //執行插入數據操作,返回影響的行數 if (i == 1) { result = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { //finally的用處是不管程序是否出現異常,都要執行finally語句,所以在此處關閉連接 try { conn.close(); //打開一個Connection連接后,最后一定要調用它的close()方法關閉連接,以釋放系統資源及數據庫資源 } catch(SQLException e) { e.printStackTrace(); } } return result; } public List<Employee> selectEmployee() { //從數據庫中查詢所需數據 List<Employee> empList = new ArrayList<Employee>(); Connection conn = null; try { conn = DatabaseConnection.getCon(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from company.tb_employee");//執行SQL並返回結果集 while (rs.next()) { Employee emp = new Employee(); emp.setEmpId(rs.getInt("empId")); //從結果集rs中獲取內容時,若為字符串類型的,用rs.getString("string")方法 emp.setEmpName(rs.getString("empName")); //其中str為想要從 數據庫的 表 中獲取的信息 emp.setEmpAge(rs.getInt("empAge")); //若為int類型,用rs.getInt(number); emp.setEmpSex(rs.getString("empSex")); empList.add(emp); } } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); //關閉連接 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return empList; //返回結果 } public boolean updateEmployee(Employee emp) { //根據員工的編號更改員工的年齡信息 boolean result = false; Connection conn = null; try { conn = DatabaseConnection.getCon(); String sql = "update company.tb_employee set empAge=? where empId=?"; //update語句 PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, emp.getEmpAge()); //設置SQL語句第一個"?"的參數值 stmt.setInt(2, emp.getEmpId()); //設置SQL語句第二個"?"的參數值 int flag = stmt.executeUpdate(); //執行修改操作,返回影響的行數 if (flag == 1) { //修改成功返回true result = true; } } catch(Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } public boolean deleteEmployeeById(Employee emp) { boolean result = false; Connection conn = null; try { conn = DatabaseConnection.getCon(); String sql = "delete from company.tb_employee where empId = ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, emp.getEmpId()); int i = stmt.executeUpdate(); if (i == 1) { result = true; } } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } } package 數據庫_向數據庫插入數據; public class MainTest { public static void main(String[] args) { //測試向數據庫的表中插入元素的方法 Employee emp = new Employee(); emp.setEmpId(2); emp.setEmpName("LILEI"); emp.setEmpAge(33); emp.setEmpSex("male"); boolean res = EmployeeOperation.getInstance().saveEmployee(emp); if (res == true) { System.out.println("向company.tb_employee表中插入數據成功"); } else { System.out.println("向company.tb_employee表中插入數據失敗"); } } } package 數據庫_向數據庫插入數據; import java.util.List; public class SelectMainTest { //測試從數據庫中獲取數據的方法 public static void main(String[] args) { List<Employee> empList = EmployeeOperation.getInstance().selectEmployee(); System.out.println("員工ID\t員工姓名\t員工年齡\t員工性別"); for (Employee emp : empList) { System.out.print(emp.getEmpId() + "\t" + emp.getEmpName() + "\t" + emp.getEmpAge() + "\t" + emp.getEmpSex()); System.out.println(); } } } package 數據庫_向數據庫插入數據; import java.util.List; public class UpdateMainTest { //根據員工的id修改員工年齡的方法 public static void main(String[] args) { List<Employee> empList = EmployeeOperation.getInstance().selectEmployee(); System.out.println("員工ID"); for (Employee emp : empList) { System.out.println(emp.getEmpId()); } Employee emp = new Employee(); emp.setEmpId(2); emp.setEmpAge(50); boolean res = EmployeeOperation.getInstance().updateEmployee(emp); if (res == true) { System.out.println("編號為2的員工的年齡修改成功"); } else { System.out.println("編號為2的員工的年齡修改失敗"); } } } package 數據庫_向數據庫插入數據; public class DeleteMainTest { public static void main(String[] args) { //測試刪除對應id的員工的方法 Employee emp = new Employee(); emp.setEmpId(1); boolean res = EmployeeOperation.getInstance().deleteEmployeeById(emp); if (res == true) { System.out.println("成功刪除id為1的員工"); } else { System.out.println("未能成功刪除id為1的員工"); } } } ////// 對於ResultSet取得結果后,我們可以使用Vector二維數據存儲,然后再利用new DefaultTableModel(vector,vector)來構造表格模型 Vector<Vector<Object>> list = new Vector<Vector<Object>>(); while(result.next()) { Vector<Object> vTemp = new Vector<Object>(); vTemp.add(result.getInt(1));//ID vTemp.add(result.getString(2));//姓名 vTemp.add(result.getInt(3));//隊 vTemp.add(result.getString(4));//手機 if(result.getInt(5) == 0){ vTemp.add("否");//是否已經繳費 } else{ vTemp.add("是");//是否已經繳費 } vTemp.add(result.getInt(6));//欠費 list.add(vTemp); } Vector<String> columns = new Vector<String>(); columns.add("ID"); columns.add("姓名"); columns.add("隊"); columns.add("手機"); columns.add("已繳費"); columns.add("欠費"); tableModel = new DefaultTableModel(list,columns); table.setModel(tableModel); import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class Utilities { // 功能:實現結果集的表格顯示 public static void displayResultSet(JTable table, ResultSet rs) throws SQLException { // rs.beforeFirst();// 指針移到第一條記錄前面 boolean hasRecords = rs.next(); if (!hasRecords) { // 記錄集為空,提示一條消息 JOptionPane.showMessageDialog(table, "無相關記錄", "Check your input!", JOptionPane.ERROR_MESSAGE); return; } Vector<String> columnHeads = new Vector<String>();// 用於存儲表頭字段(列名) Vector<Vector> rows = new Vector<Vector>();// 用於存儲記錄行 try { // 獲取字段的名稱 ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); ++i) columnHeads.addElement(rsmd.getColumnName(i)); do {// 獲取記錄集 rows.addElement(getNextRow(rs, rsmd)); } while (rs.next()); // 建立相應的TableModel,並將TableModel應用到Table中顯示出來 DefaultTableModel model = new DefaultTableModel(rows, columnHeads); table.setModel(model); return; } catch (SQLException exc) { JOptionPane.showMessageDialog(table, exc.toString(), "Check your input!", JOptionPane.ERROR_MESSAGE); return; } } // // 被displayResultSet(JTable table, ResultSet rs)調用, 以Vector形式返回一個記錄行 private static Vector getNextRow(ResultSet rs, ResultSetMetaData rsmd) throws SQLException { Vector<String> currentRow = new Vector<String>(); for (int i = 1; i <= rsmd.getColumnCount(); ++i) currentRow.addElement(rs.getString(i)); return currentRow; // 返回一條記錄 } } */
4. 實體類,示例代碼如下:
public class TbNews { private String topicId; private String contentTxt; public TbNews() { } public TbNews(String topicId,String contentTxt) { this.topicId=topicId; this.contentTxt=contentTxt; } public String getTopicId() { return topicId; } public void setTopicId(String topicId) { this.topicId=topicId; } public String getContentTxt() { return contentTxt; } public void setContentTxt(String contentTxt) { this.contentTxt=contentTxt; } }
5. 瀏覽記錄,代碼如下:
import java.awt.BorderLayout; import java.awt.Container; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.Vector; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SelectFrame extends JDialog { Thread t; private JTable table; private DefaultTableModel tableModel; public SelectFrame(BoxLayoutFrame frame) { super(frame,"瀏覽記錄",true); setBounds(380,300,300,260); Container cp=getContentPane(); /* Vector<String> columns=new Vector<String>(); columns.add("topicId"); columns.add("contentTxt"); Vector<Vector<TbNews>> list = new Vector<Vector<TbNews>>(); list.add(DbOperation.getInstance().queryTbNews()); tableModel=new DefaultTableModel(list,columns); //table=new JTable(tableModel); table=new JTable(); table.setModel(tableModel); */ String[] columns= {"topicId","contentTxt"}; tableModel=new DefaultTableModel(columns,0); List<String> tbs=DbOperation.getInstance().selectTbNews(); for(String info:tbs) { String[] args=info.split(","); tableModel.addRow(args); } table=new JTable(); table.setModel(tableModel); final JScrollPane scrollPane=new JScrollPane(); cp.add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(table); } }