JDBC之插入、删除、修改操作

一、插入操作

	public static void insert(String username,String password)
	{
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try {
			con=JDBCUtils.getConnection();//JDBCUtils是我们之前说过的我们自己写的工具包,详细见代码重构那个博客
			String sql="insert into student(xuehao,xingming) values(?,?)";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, username);//设置第一个参数(即第一个?)
			pstmt.setString(2, password);//设置第二个参数(即第二个?)
			int result=pstmt.executeUpdate();//result返回的是有几行受影响
			if(result>0)
				System.out.println("插入成功");
			else
				System.out.println("插入失败");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCUtils.close(con, pstmt, rs);
		}
	}

二、删除操作

	public static void delete(int id)
	{
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try {
			con=JDBCUtils.getConnection();
			String sql="delete from student where id=?";//参数都用?表示
			pstmt=con.prepareStatement(sql);
			pstmt.setInt(1, id);
			int result=pstmt.executeUpdate();
			if(result>0)
				System.out.println("删除成功");
			else
				System.out.println("删除失败");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCUtils.close(con, pstmt, rs);
		}
	}

三、修改操作

	public static void update(int id,String newxuehao)
	{
		Connection con=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try {
			con=JDBCUtils.getConnection();
			String sql="update student set xuehao=? where id=?";
			pstmt=con.prepareStatement(sql);
			pstmt.setString(1, newxuehao);
			pstmt.setInt(2, id);
			int result=pstmt.executeUpdate();
			if(result>0)
			System.out.println("更新成功");
			else {
				System.out.println("更新失败");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCUtils.close(con, pstmt, rs);
		}
	}

猜你喜欢

转载自blog.csdn.net/henulmh/article/details/105050577