如何从mysql数据库读取数据

如何从mysql数据库读取数据,第1张

读取数据,首先要将数据库的驱动包导入:如果是mysql数据库,需要导入mysql-connector-java-5.1.27.jar,如果是oracle就需要导入oracle.jar包;

然后就是建立数据库连接,使用Connection 新建连接,然后执行你的sql语句查询出需要的数据,下面是两个方法: public PageModel findAllUser(int pageNo,int pageSize){String sql = "select * from user where user_name <>'root' order by user_name" +"limit" + (pageNo - 1) * pageSize + "," + pageSizePageModel pageModel =nullConnection conn =nullStatement stmt =nullResultSet rs = nulltry{conn = DB.getConn()stmt = conn.createStatement()rs = stmt.executeQuery(sql)List user_List = new ArrayList()while(rs.next()){User user = new User()user.setUser_name(rs.getString("user_name"))user.setUser_password(rs.getString("user_password"))user.setUser_tel(rs.getString("user_tel"))user.setUser_email(rs.getString("user_email"))user.setUser_createDate(rs.getTimestamp("user_createdate"))user_List.add(user)}//取得所有记录int totalRecords = getTotalRecords(conn)pageModel = new PageModel()pageModel.setPageSize(pageSize)pageModel.setList(user_List)pageModel.setTotalRecord(totalRecords)}catch(SQLException e){e.printStackTrace()}finally{DB.close(rs)DB.close(stmt)DB.close(conn)}return pageModel} /** * 取得所有记录 * @param conn * @return 所有记录totalRecords */public int getTotalRecords(Connection conn){String sql = "select count(*) from user where user_name <>'root' "int totalRecords = 0Statement stmt = nullResultSet rs = nulltry{conn = DB.getConn()stmt = conn.createStatement()rs = stmt.executeQuery(sql)if(rs.next()){totalRecords = rs.getInt(1)}}catch(SQLException e){e.printStackTrace()}finally{DB.close(rs)DB.close(stmt)DB.close(conn)}return totalRecords}

查询数据库的时候,语句这样写:AsText(point类型的列),如下:

sql = "select AsText(point), x(point), y(point), type, name, status from tb_point"//SQL语句

      db1 = new DBHelper(sql)//创建DBHelper对象

      try {

          ret = db1.pst.executeQuery()//执行语句,得到结果集

          while (ret.next()) {

         final String point = ret.getString(1)

            final String xpoint = ret.getString(2)

            final String ypoint = ret.getString(3)

              final String type = ret.getString(4)

              final String name = ret.getString(5)

              final int status = ret.getInt(6)

              System.out.println(String.format("%s\t%s\t%s\t%s\t%s\t%d", point, xpoint,ypoint, type,name,status))

          }//显示数据

          ret.close()

          db1.close()//关闭连接

      } catch (final SQLException e) {

          e.printStackTrace()

      }

输出结果:

POINT(123.462202 41.804471)   123.462202    41.804471 ViewPoint Yellow Stone Park 1

POINT(123.462202 41.804471)   123.462202    41.804471 Clinic TangZhen 1


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/8652132.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-19
下一篇 2023-04-19

发表评论

登录后才能评论

评论列表(0条)

保存