java mysql数据库增_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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值