完成对数据库的CRUD操作

时间:2023-03-09 17:05:28
完成对数据库的CRUD操作

PS:查询相对复杂,要处理结果集,增删改则不用。

 package it.cast.jdbc;

 import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class CRUD { /**
* @param args
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
delete(); } //删除
static void delete() throws SQLException, ClassNotFoundException { Connection conn = null;
Statement st = null;
ResultSet rs = null;
// 2.建立连接
conn = jdbcUtils.getConnection(); // 3.创建语句
st = conn.createStatement(); String sql = "delete from user where name='name1'"; // 4.执行语句
int i = st.executeUpdate(sql); System.out.println("I="+i); // 6.释放资源
jdbcUtils.free(rs, st, conn);
} //修改
static void update() throws SQLException, ClassNotFoundException { Connection conn = null;
Statement st = null;
ResultSet rs = null;
// 2.建立连接
conn = jdbcUtils.getConnection(); // 3.创建语句
st = conn.createStatement(); String sql = "update user set money=money+10"; // 4.执行语句
int i = st.executeUpdate(sql); System.out.println("I="+i); // 6.释放资源
jdbcUtils.free(rs, st, conn);
} //新增
static void create() throws SQLException, ClassNotFoundException { Connection conn = null;
Statement st = null;
ResultSet rs = null;
// 2.建立连接
conn = jdbcUtils.getConnection(); // 3.创建语句
st = conn.createStatement(); String sql = "insert into user(name,birthday,money) values('name1','1997-01-01',4000)"; // 4.执行语句
int i = st.executeUpdate(sql); System.out.println("I="+i); // 6.释放资源
jdbcUtils.free(rs, st, conn);
} }

CRUD