java之mysql数据库的链接及增删改查

Java中与数据库交互的步骤

1 新建一个工程
2 导包,在工程中导入连接MySQL数据库所使用的jar包
3 连接数据库
4 数据的增删改查
数据库的增删改查操作

步骤

1 获取刚刚创建的Connection对象

2 写sql语句

3 得到statement对象

4 执行sql语句,得到结果集

5 处理结果集

6 关闭资源

7 增加数据
DBUtil db = new DBUtil();
private Connection conn;

/*
插入数据
*/
@Override
public void insertUser(TeamWorker newUser) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm = null;
String sql_insert = "insert into teamworkerinfo(tb_pid,tb_pname,tb_ppsw) values(?,?,?)"; //sql语言
pstm = conn.prepareStatement(sql_insert);

//填充sql语句中的?
pstm.setString(1, newUser.getId());
pstm.setString(2, newUser.getName());
pstm.setString(3, newUser.getPwd());

//使用executeUpdate函数执行sql语句
int row = pstm.executeUpdate();
System.out.println("新增用户成功" + row + "行受到影响");
//释放对数据库的连接
db.closeConn(null, pstm, conn);

}
修改数据
DBUtil db = new DBUtil();
private Connection conn;
/*
从数据库中修改用户信息
*/
@Override
public void updateUser(String id, TeamWorker modUser) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm = null;
String sql_update = "update teamworkerinfo set tb_pname=?tb_ppsw=? where tb_pid=?";
pstm = conn.prepareStatement(sql_update);

pstm.setString(1,modUser.getName());
pstm.setString(2,modUser.getPwd());
pstm.setString(3,id);

int row = pstm.executeUpdate();
System.out.println("修改用户成功"+row+"行受到影响");
db.closeConn(null, pstm, conn);

}
删除数据
DBUtil db = new DBUtil();
private Connection conn;
/*
从数据表中删除用户信息
*/
@Override
public void deleteUser(String id) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm = null;
String sql_delete = "delete from teamworkerinfo where tb_pid=?";
pstm = conn.prepareStatement(sql_delete);

pstm.setString(1,id);

int row = pstm.executeUpdate();
System.out.println("删除用户成功"+row+"行受到影响");
db.closeConn(null, pstm, conn);

}
修改数据
DBUtil db = new DBUtil();
private Connection conn;
/*
从数据库中修改用户信息
*/
@Override
public void updateUser(String id, TeamWorker modUser) throws Exception {
Connection conn = db.getConn();
PreparedStatement pstm = null;
String sql_update = "update teamworkerinfo set tb_pname=?tb_ppsw=? where tb_pid=?";
pstm = conn.prepareStatement(sql_update);

pstm.setString(1,modUser.getName());
pstm.setString(2,modUser.getPwd());
pstm.setString(3,id);

int row = pstm.executeUpdate();
System.out.println("修改用户成功"+row+"行受到影响");
db.closeConn(null, pstm, conn);

}

posted on 2020-11-11 19:30  狂风飘飘  阅读(173)  评论(0编辑  收藏  举报