JDBC学习笔记(5):数据库的基本操作CRUD

1.查询

public static void read() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from user");
            
            while(rs.next()) {
                System.out.println(rs.getInt("id") + "\t" 
                        + rs.getString("name") + "\t"
                        + rs.getDate("birthday") + "\t"
                        + rs.getFloat("money"));
            }
        } finally {
            JdbcUtils.close(rs, stmt, conn);
        }
    }
【运行结果】:
1    zhangs    1985-01-01    100.0
2    lisi    1986-01-01    200.0
3    wangwu    1987-01-01    300.0
 
2.增减一条记录,由于id是自增的,所以不需要重复插入数据:
public static void create() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.createStatement();
            String sql = "insert into user(name,birthday,money) values(‘zhaoliu‘,‘1990-01-01‘,400)";
            int i = stmt.executeUpdate(sql);
            System.out.println("i="+i);
        } finally {
            JdbcUtils.close(rs, stmt, conn);
        }
    }
【运行结果】:
 i=1  //表示成功插入一条记录
【查询数据库结果】:多了一条记录
技术分享
 
 3.将id=1的money修改为400
public static void update() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.createStatement();
            
            String sql = "update user set money=400 where id=1";
            int i = stmt.executeUpdate(sql);
            System.out.println("i = " + i);
        } finally {
            JdbcUtils.close(rs, stmt, conn);
        }
        
    }
【运行结果】:
 i = 1 
【查询数据库结果】:
技术分享
 
4.删除id=4的记录
public static void delete() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.createStatement();
            String sql = "delete from user where id=4";
            int i = stmt.executeUpdate(sql);
            System.out.println("i=====" + i);
        } finally{
            JdbcUtils.close(rs, stmt, conn);
        }
    }
【运行结果】:
 i=====1 
【查询数据库结果】:
技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。