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
【查询数据库结果】:
时间: 2024-10-30 01:03:30