Java 一个简单的数据库操作示例

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);
    }
}

 

posted @ 2017-12-19 08:43  tiger_yj  阅读(2893)  评论(0编辑  收藏  举报