Java 如何从jsp文件中检索数据库中的数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24369261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:49:35  来源:igfitidea点击:

How to retrieve data from a database from a jsp file?

javajspjdbc

提问by Nikunj Banka

I have a .jsp file which basically displays data from a database. The database class is defined separately in a .java file. To get the contents of the database I am calling the getData method of the database. But the function calls made never execute and nothing is returned.

我有一个 .jsp 文件,它基本上显示来自数据库的数据。数据库类在 .java 文件中单独定义。为了获取数据库的内容,我调用了数据库的 getData 方法。但是函数调用永远不会执行并且没有返回任何内容。

However if I return any pre-computed values from the getData function, then it executes fine.

但是,如果我从 getData 函数返回任何预先计算的值,那么它执行得很好。

I want to know how can I access the database from the .jsp file.

我想知道如何从 .jsp 文件访问数据库。

I don't want to add the java code directly to the .jsp file. So I want to do it via a method call.

我不想将 java 代码直接添加到 .jsp 文件中。所以我想通过方法调用来做到这一点。



.jsp 文件中的函数:


<%
    ArrayList<String> al = com.Database.getData();
%>



Java函数:

getData(){
    al = new ArrayList<String>();
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs   = null;
    al.add("first");
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL,USER,PASS);
        stmt = conn.createStatement();

        String sql = "SELECT rs FROM DATABASE";
        rs = stmt.executeQuery(sql);
        while(rs.next()){
            String str  = rs.getString("str");
            al.add(str);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    al.add("nikunj ");
    al.add("banka ");
    return al;
}


The contents of the arraylist after the call are {"first", "nikunj", "banka"} and no data from the database.

调用后arraylist的内容为{"first", "nikunj", "banka"},没有来自数据库的数据。

How can I get the data from the database. I have tried creating a static block that will populate the ArrayList at the start of the program but even this is not working.

如何从数据库中获取数据。我曾尝试创建一个静态块,它将在程序开始时填充 ArrayList,但即使这样也不起作用。

采纳答案by Paul Vargas

There are several ways to do this. You can also use JSTLif you want to avoid Java code in your JSP. e.g.:

有几种方法可以做到这一点。如果您想避免在 JSP 中使用Java 代码,也可以使用JSTL。例如:

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %>

<sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver"
                   url="jdbc:mysql://localhost/test"
                   user="root"  password="pass123"/>

<html>
<head>
<title>JSTL SQL</title>
</head>
<body>

<sql:query var = "result" dataSource="${dataSource}">
SELECT str FROM table
</sql:query>

<table border=1>
<c:forEach var="row" query="${result.rows}">
<tr>
<td><c:out value="${row.str}"/></td>
</tr>
</c:forEach>
</table>

</body>
</html>


Maybe you want to read:

也许你想阅读:

回答by SparkOn

create a jsp have this code:

创建一个jsp有这个代码:

<%
  List list = main.myPack.Test.getData();
  System.out.println(list);

%>

create a static method of a class like this :

创建一个类的静态方法,如下所示:

public static List getData()
    {
        List<String> list = new ArrayList<String>();
        try{

            System.out.println("invoked");
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("making connection");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "welcome");
            System.out.println("Connection established");
            Statement stmt=con.createStatement();
            ResultSet rset=stmt.executeQuery("select * from student");
            System.out.println("fetching data");
            while(rset.next())
            {
                String name = rset.getString("student_name");
                String id = rset.getString("student_id");
                list.add(name);
                list.add(id);
                System.out.println(name+" "+id);
            }
            System.out.println(list);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;

then call the jsp thats it what you want }

然后调用jsp就是你想要的}

回答by Harsha

Check your SQL query column with ResultSet.getString() methods dear. If you used SELECT str FROM database_table it's fine.

亲爱的,使用 ResultSet.getString() 方法检查您的 SQL 查询列。如果您使用 SELECT str FROM database_table 就可以了。

回答by BruceRudd

I think @Harsha has pointed you in the right direction. ResultSet.getString()has two overloads.

我认为@Harsha 为您指明了正确的方向。ResultSet.getString()有两个重载。

  • One takes an Intthat represent which column, ordinally, you want to retrieve.
  • The other, which you used, take a Stringwhich would be the column name in the result set.
  • 一个取一个Int代表您想要检索的列。
  • 另一个,您使用的,取 aString这将是结果集中的列名。

Since your SELECT statement only selected the column "rs" you have no column "str" in your result set to retrieve.

由于您的 SELECT 语句仅选择了列“rs”,因此您的结果集中没有要检索的列“str”。

回答by wrecklez

i think you should check your sql statement you have database error i think!

我认为你应该检查你的 sql 语句你有数据库错误我认为!

//String sql = "SELECT rs FROM DATABASE";
String sql = "SELECT str FROM DATABASE";
rs = stmt.executeQuery(sql);
while(rs.next()){
   String str  = rs.getString("str"); //you get "str" field here not "rs"
   al.add(str);
}