JDBC通过writer返回结果到客户端程序?

时间:2011-11-22 01:19:19

标签: java jdbc

我正在尝试将mySQL结果返回给我的客户端程序。我认为它没有连接,因为我可以返回连接错误,但我相信所有设置都是正确的,并且之前在PHP连接上使用过它们?

如果您只想返回一个字符串,那么完整的代码就完整了:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;

public class TestDatabase extends HttpServlet {

    private static String message = "Error during Servlet processing";
    private static String inputStream;
    ResultSet rs;

    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            int len = req.getContentLength();
            byte[] input = new byte[len];

            ServletInputStream sin = req.getInputStream();
            int c, count = 0;
            while ((c = sin.read(input, count, input.length - count)) != -1) {
                count += c;
            }

            sin.close();
            String inString = new String(input);
            int index = inString.indexOf("=");
            String value = inString.substring(index + 1);
            inputStream = URLDecoder.decode(value, "UTF-8");

        } catch (IOException e) {

        }

        try {
            responseWriter(resp);
        } catch (SQLException e) {

            e.printStackTrace();
        }
    }// end of requestReader

    public void responseWriter(HttpServletResponse resp) throws SQLException {



        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://server.co.uk:port/dbName?user=UserName&password=PassWord");

            Statement st = (Statement) con.createStatement();
            rs = st.executeQuery("SELECT * FROM MyTable;");

        } catch (Exception e){
            System.out.println("fail");
        }

        while (rs.next()){
            String output = rs.getString("column_name");
        }

        try {
            resp.setStatus(HttpServletResponse.SC_OK);
            OutputStreamWriter writer = new OutputStreamWriter(
            resp.getOutputStream());
            writer.write(output);
            writer.flush();
            writer.close();

        } catch (IOException e) {

        }

    }// end of responseWriter

}// end of class

编辑:我相信它抛出一个ClassNotFoundException。

1 个答案:

答案 0 :(得分:0)

在public void doPost()方法中,你不会抛出 抛出SQLException,IOException