week_three_jdbc

来源:互联网 发布:mac在windows截图 编辑:程序博客网 时间:2024/05/10 13:08

说明:
写一个JDBC的java程序,使用作业2中的数据表结构,完成以下操作:
1、向数据表写入十条不同的数据,并将数据库中所有的数据输出
2、查询年龄大于15岁的男生,并将数据输出
3、删除所有男生的数据,并将删除之后,数据库中的所有数据输出
注意:提交作业时要提交:
1、程序的源代码
2、建表语句

public class TestDemo {    private static String insertSQL = "INSERT INTO t_students (stu_id,stu_name,stu_age,stu_gender,stu_address) values\n" +            "  ('20170061','某某1','23','女','杭州'),\n" +            "  ('20170062','某某2','24','男','富阳'),\n" +            "  ('20170063','某某3','25','女','桐庐'),\n" +            "  ('20170064','某某4','26','男','新登'),\n" +            "  ('20170065','某某5','27','女','上官'),\n" +            "  ('20170066','某某6','28','男','湖源'),\n" +            "  ('20170067','某某8','29','女','场口'),\n" +            "  ('20170068','某某8','30','男','余杭'),\n" +            "  ('20170069','某某9','31','女','下沙'),\n" +            "  ('20170070','某某10','32','男','滨江');";    private static String selectSQL = "select * from t_students where stu_gender='男' and stu_age >15 ORDER BY id DESC;";    private static String deleteSQL = "DELETE from t_students where stu_gender='男';";    private static String selectAll = "select * from t_students order by id desc;";    public static void main(String[] args){        Connection conn = null;        try{            conn = JdbcUtil.getConnection();            conn.setAutoCommit(false);            SqlUtil.insertBySql(conn,insertSQL);            ResultSet rs =  SqlUtil.selectBySql(conn,selectSQL);            SqlUtil.deleteBySql(conn,deleteSQL);            ResultSet rsAll = SqlUtil.selectBySql(conn,selectAll);            conn.commit();            showData(rs);            System.out.println("=======================");            showData(rsAll);        }catch(Exception e){            System.out.println("捕获到SQL异常");            try {                conn.rollback();                System.out.println("回滚成功");            } catch (SQLException e1) {                e1.printStackTrace();                System.out.println("回滚失败");            }            e.printStackTrace();        }finally {            try {                if (conn != null) {                    conn.close();                }            } catch (SQLException e) {                e.printStackTrace();            }        }    }    public static void showData(ResultSet rs) throws SQLException {        while (rs.next()){            System.out.print(rs.getString("stu_id") + "\t");            System.out.print(rs.getString("stu_name") + "\t");            System.out.print(rs.getString("stu_age") + "\t");            System.out.print(rs.getString("stu_gender") + "\t");            System.out.print(rs.getString("stu_address") + "\t");            System.out.println();        }    }}
原创粉丝点击