1

如何从 servlet 连接到数据库。我尝试了以下代码,但每次都控制异常。

   try
            {
            int num_rows = 0;
            Connection con = null;
            Statement st = null;
            Statement search = null;
            ResultSet rs = null;
            ResultSet searchRS = null;

            // Connecting to the database
            PrintWriter out = response.getWriter();
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employees","root","");
            st = con.createStatement(); 
            rs = st.executeQuery("select employees.first_name,employees.last_name,employees.gender,employees.hire_date,departments.dept_name,salaries.salary from employees,departments,salaries,dept_emp where employees.emp_no=salaries.emp_no AND dept_emp.emp_no=employees.emp_no AND dept_emp.dept_no=departments.dept_no AND salaries.to_date='9999-01-01' AND (employees.first_name='"+Sname+"' OR employees.last_name='"+Sname+"')");
            //Retrieval of data from result set retrieved from database

            String[][] str = new String[10][6];

                while( rs.next())
                {
                    str[num_rows][0] = rs.getString("first_name");
                    str[num_rows][1] = rs.getString("last_name");
                    str[num_rows][2] = rs.getString("gender");
                    str[num_rows][3] = rs.getString("hire_date");
                    str[num_rows][4] = rs.getString("dept_name");
                    str[num_rows][5] = rs.getString("salary");
                    num_rows++;
                }

                if(num_rows <10)
                {
                    isLast = true;
                    var = 0;
                }   

            request.setAttribute("listvalue",str);
            request.setAttribute("rows",num_rows);
            RequestDispatcher RequestDispatcherObj =request.getRequestDispatcher("SearchName.jsp");

            RequestDispatcherObj.forward(request, response);

            out.flush();
            con.close();
            var = var +10;
            }
    catch(Exception e)
    {
        e.printStackTrace();
    }
4

2 回答 2

1

您的字符串数组可以容纳 10 条记录;可能您从数据库中获得的不仅仅是这些。

你可以试试这个-

while( rs.next() && num_rows < 10 )

如果您需要收集所有记录,最好使用 List 之类的集合。

于 2013-04-22T05:47:14.890 回答
1

对我来说看起来像这条线

RequestDispatcherObj.forward(request, response);

正在制造问题。它正在将请求转发到其他地方。requestdispatcheobj可能已关闭对象out。所以在那之后使用flush() and write() 将导致一个IllegalStateException.

out.flush();
con.close();
var = var +10;

因此,请确保不是这种情况。

于 2013-04-22T06:13:11.530 回答