时间:2021-07-01 10:21:17 帮助过:4人阅读
2、进行增删改查操作
public class test { Connection connection=null; PreparedStatement pstm=null; ResultSet rs=null; //增加数据 public void insert(){ connection=JDBCUtil.getConnection(); String sql="insert into student values(?,?,?,?)"; try { pstm=connection.prepareStatement(sql); pstm.setObject(1,4); pstm.setObject(2,"薛勇"); pstm.setObject(3,"男"); pstm.setObject(4,201); pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.closeResoirce(pstm,connection); } } public void update(){ connection=JDBCUtil.getConnection(); String sql="update student set sex=? where sid=?"; try { pstm=connection.prepareStatement(sql); pstm.setObject(1,"男"); pstm.setObject(2,"1"); pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.closeResoirce(pstm,connection); } } public void delete(){ connection=JDBCUtil.getConnection(); String sql="delete from student where sid=?"; try { pstm=connection.prepareStatement(sql); pstm.setObject(1,3); pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.closeResoirce(pstm,connection); } } public void search(){ connection=JDBCUtil.getConnection(); String sql="select * from student where sid=?"; try { pstm=connection.prepareStatement(sql); pstm.setObject(1,"2"); rs=pstm.executeQuery(); if(rs.next()){ int sid = rs.getInt("sid"); String sname = rs.getString("sname"); String sex = rs.getString("sex"); int tid = rs.getInt("tid"); System.out.println("sid:"+sid+",sname:"+sname+",sex"+sex+",tid"+tid); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.closeResoirce2(rs,pstm,connection); } } public void searchNo(){ connection=JDBCUtil.getConnection(); String sql="select * from student"; try { pstm=connection.prepareStatement(sql); rs=pstm.executeQuery(); while(rs.next()){ int sid = rs.getInt("sid"); String sname = rs.getString("sname"); String sex = rs.getString("sex"); int tid = rs.getInt("tid"); System.out.println("sid:"+sid+",sname:"+sname+",sex"+sex+",tid"+tid); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.closeResoirce2(rs,pstm,connection); } } public static void main(String[] args) { test t=new test(); // t.insert(); t.searchNo(); } }
JDBC操作数据库--增删改查
标签:连接 col -- class get try ati return upd