-
Statement执行方法:
即sql语句中不需要用占位符传值的情况,直接用Statement.executeQuery(“sql语句”)即可
下面以查询所有信息指令为例(未含释放资源代码):
public List<AirInfo> Qurey() throws SQLException { Connection con = BaseDao.getConnection(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from airmessa"); List<AirInfo> airmList = new ArrayList<AirInfo>(); AirInfo airm = null; while (rs.next()){ airm = new AirInfo(); airm.setID(rs.getInt("编号")); airm.setAirNumber(rs.getString("航班号")); airm.setDestination(rs.getString("目的地")); airm.setAirTime(rs.getString("起飞日期")); airmList.add(airm); } return airmList; }
-
PreparedStatement执行方法:
即需要用占位符传值的情况,
(1)查询语句用PreparedStatement.excuteQuery()执行,注意括号中不写sql语句!
public List<AirInfo> QureyByTime(String airdate){ List<AirInfo> airTimeList = new ArrayList<AirInfo>(); ResultSet rs = null; PreparedStatement psmt = null; Connection con = BaseDao.getConnection(); try { con = BaseDao.getConnection(); Statement stmt = con.createStatement(); String sql = "select * from airmessa where 起飞日期 = ?"; // 预编译sql语句 psmt = con.prepareStatement(sql); // 先对应SQL语句,给SQL语句传递参数 psmt.setDate(1, java.sql.Date.valueOf(airdate)); //执行语句 rs = psmt.executeQuery(); //将结果取出,赋值给数组 AirInfo airm; while (rs.next()){ airm = new AirInfo(); airm.setID(rs.getInt("编号")); airm.setAirNumber(rs.getString("航班号")); airm.setDestination(rs.getString("目的地")); airm.setAirTime(rs.getDate("起飞日期").toString()); airTimeList.add(airm); } } catch (SQLException throwables) { throwables.printStackTrace(); } return airTimeList;
(2)更新、删除语句,用PreparedStatement.excute()执行
public static void Update(AirInfo airInfo){ Date airdate = null; PreparedStatement psmt = null; Connection con=null; try { con=BaseDao.getConnection(); String sql="update airmessa " + "set 航班号 = ?, 目的地 = ?, 起飞日期 = ?" + "where 编号 = ?"; // 预编译sql语句 psmt = con.prepareStatement(sql); // 先对应SQL语句,给SQL语句传递参数 psmt.setString(1, airInfo.getAirNumber()); psmt.setString(2, airInfo.getDestination()); //时间类型待转换: // 先String类型转util.Date类型 DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); airdate = format.parse(airInfo.getAirTime()); //再util.Date转sql.Date java.sql.Date airdate2 = new java.sql.Date(airdate.getTime()); psmt.setDate(3, airdate2); psmt.setInt(4, airInfo.getID()); // 执行SQL语句 psmt.execute(); } catch (SQLException | ParseException throwables) { throwables.printStackTrace(); }