读
package zucc.edu.cn.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CRUD {
public static void main(String[] args) throws SQLException {
read();
}
public static void read() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = jdbcUtils.getinstance().getConnection();
// 3.创建执行SQL的语句
st = conn.createStatement();
// 4.执行语句
rs = st.executeQuery("select id, name, birthday, money from user");
// 5.处理结果
while (rs.next()) { // 推荐写列名,不建议写列索引号
System.out.println("id:" + rs.getObject("id") + '\t' + rs.getObject("name") + '\t'
+ rs.getObject("birthday") + '\t' + rs.getObject("money"));
}
} finally {
// 6.释放资源
jdbcUtils.free(rs, st, conn);
}
}
}
1 JiangLR 1998-01-02 100
2 HunagWB 1998-01-01 200
3 FanJH 1997-12-12 300
4 JiangJY 1997-01-02 400
插入
public static void create() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = jdbcUtils.getinstance().getConnection();
// 3.创建执行SQL的语句
st = conn.createStatement();
// 4.执行语句
String sql = "insert into user(name, birthday, money) value ('MaYL', '1997-10-10', 500)";
st.executeUpdate(sql); // executeUpdate()返回的是个数字
//不需要rs对象来遍历数据库操作
} finally {
// 6.释放资源
jdbcUtils.free(rs, st, conn);
}
}
1 JiangLR 1998-01-02 100
2 HunagWB 1998-01-01 200
3 FanJH 1997-12-12 300
4 JiangJY 1997-01-02 400
5 MaYL 1997-10-10 500
更新
public static void update() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = jdbcUtils.getinstance().getConnection();
// 3.创建执行SQL的语句
st = conn.createStatement();
// 4.执行语句
String sql = "update user set money = money + 233";
st.executeUpdate(sql); // executeUpdate()返回的是个数字(受影响的行数)
} finally {
// 6.释放资源
jdbcUtils.free(rs, st, conn);
}
}
1 JiangLR 1998-01-02 333
2 HunagWB 1998-01-01 433
3 FanJH 1997-12-12 533
4 JiangJY 1997-01-02 633
5 MaYL 1997-10-10 733
删除
public static void delete() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = jdbcUtils.getinstance().getConnection();
// 3.创建执行SQL的语句
st = conn.createStatement();
// 4.执行语句
String sql = "delete from user where id > 4";
st.executeUpdate(sql); // executeUpdate()返回的是个数字(删除的行数)
} finally {
// 6.释放资源
jdbcUtils.free(rs, st, conn);
}
}
1 JiangLR 1998-01-02 333
2 HunagWB 1998-01-01 433
3 FanJH 1997-12-12 533
4 JiangJY 1997-01-02 633