Java实现对数据库的查操作

查询数据库得到的结果有很大的可能会得到若干条,因此executeQuery()方法的返回值是一个集合,返回类型由ResultSet接收。 在JDBCUtils工具类中对close方法进行方法重载

public static void close(PreparedStatement ps, Connection connection) {
          
   
        if (ps != null){
          
   
            try {
          
   
                ps.close();
            } catch (SQLException e) {
          
   
                e.printStackTrace();
            }
        }
        if (connection != null){
          
   
            try {
          
   
                connection.close();
            } catch (SQLException e) {
          
   
                e.printStackTrace();
            }
        }
    }
//close方法重载
public static void close(PreparedStatement ps, Connection connection,ResultSet rs) {
          
   
        close(ps,connection);
        if(rs != null){
          
   
        	try{
          
   
        		rs.close();
        	} catch (SQLException e) {
          
   
                e.printStackTrace();
            }
        }
    }
ResultSet rs = ps.executeQuery();

//获取数据
while(rs.next()){
          
   
	rs.getXXX(String columnLabel); // 根据字段名获取相应的内容
}

//举例:有一个student表,表中有 id int,name varchar(20)两个字段,
sql = "select * from student";
Connection connection = JDBCUtils.getConnection();
PreparedStatement ps = connection.PrepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
          
   
	int id = rs.getInt("id");
	String name = rs.getString("name");
	System.out.println(id + " " + name);
}
JDBCUtils.close(ps,connection,rs);
经验分享 程序员 微信小程序 职场和发展