日期:2014-05-16  浏览次数:20532 次

对数据库的CRUD(增删改查)
package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *对数据库的增删改查
 * @author HaoWang
 */
public class CRUD {
    public static void main(String[] args) {
        create();
        read();
        update();
        read();
        delete();
        read();
    }
    public static void create() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        String sql = null;
        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            sql = "insert into Students(sid,name,sex,birthday) value (4,'wanghao',1,'1987-11-01')";
            int i = st.executeUpdate(sql);
            System.out.println("i="+i);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        } finally {
            JdbcUtils.free(conn, st, rs);
        }
    }
    public static void read() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            rs = st.executeQuery("Select * from Students;");
            while (rs.next()) {
                System.out.println(rs.getObject(1) + "\t" + rs.getObject(2) + "\t" + rs.getObject(3) + "\t" + rs.getObject(4));
            }
        } catch (SQLException ex) {
            System.out.println(ex.toString());
        } finally {
            JdbcUtils.free(conn, st, rs);
        }
    }
    public static void update() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        String sql = null;
        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            sql = "update students set birthday='1987-11-03' where sid=4;";
            int i = st.executeUpdate(sql);
            System.out.println("i="+i);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        } finally {
            JdbcUtils.free(conn, st, rs);
        }
    }
    public static void delete() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        String sql = null;
        try {
            conn = JdbcUtils.getConnection();
            st = conn.createStatement();
            sql = "delete from students where sid>3";
            int i = st.executeUpdate(sql);
            System.out.println("i="+i);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        } finally {
            JdbcUtils.free(conn, st, rs);
        }
    }
}

?