JDBC之PreparedStatement

在这里插入图片描述
使用 PreparedStatement 对象完成对数据库的增删改查操作
(1) 查询 aa 数据库中 user 表中的的数据,并打印在控制台上。
(2) 插入一个 username 为 tony,password 为 123 的用户。
(3) 将 tony 用户的密码修改为 ‘123456’。
(4) 将 tony 用户从 user 表中删除。
以上练习自己独立完成!!!
使用 PreparedStatement 对象完成对数据库的增删改查操作
// (1) 插入一个 username 为 tony,password 为 123 的用户。
@Test
public void testAdd(){
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//注册驱动,并获取数据库连接
conn = JDBCUtils.getConnection();
//获取传输器,并传递SQL骨架
String sql = “insert into user values(null,?,?)”;
ps=conn.prepareStatement(sql);
//设置SQL参数
ps.setString(1,“tony”);
ps.setString(2, “123”);
//返回执行结果
int rows=ps.executeUpdate();
System.out.println(“影响的行数为:”+rows);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.close(rs, ps, conn);
}
}
//(2) 将 tony 用户的密码修改为 ‘123456’。
@Test
public void testUpdate(){
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
String sql = “update user set password=? where username=?”;
ps=conn.prepareStatement(sql);
ps.setString(1,“123456”);
ps.setString(2, “tony”);
int rows=ps.executeUpdate();
System.out.println(“影响的行数为:”+rows);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.close(rs, ps, conn);
}
}
//(3)将 tony 用户从 user 表中删除。
@Test
public void testDelete(){
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
String sql = “delete from user where username=?”;
ps=conn.prepareStatement(sql);
ps.setString(1,“tony”);
int rows=ps.executeUpdate();
System.out.println(“影响的行数为:”+rows);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.close(rs, ps, conn);
}
}
//(4) 查询 jt_db 数据库中 user 表中的的数据,并打印在控制台上。
@Test
public void testFindAll(){
Connection conn =null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
String sql = “select id,username,password from user”;
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
int id=rs.getInt(“id”);
String username = rs.getString(“username”);
String password=rs.getString(“password”);
System.out.println(id+":"+username+":"+password);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.close(rs, ps, conn);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值