How do i return all the rows of a result set to a client?

Giuseppe P. :

I am writing a java application where the client sends a query and the server gets the result and sends it back to the client

The code is the following:


    private ServerSocket serverSocket;
    private Socket socket;
    private BufferedReader bufferedReader;
    private PrintWriter printWriter;
    private String message;
    private Connection connection; //rappresenta la connessione col database
    private ResultSet resultSet; //rappresenta i risultati della query
    private Statement stmt; //rappresenta la query

    public ServerSql() throws IOException, ClassNotFoundException, SQLException {
        serverSocket = new ServerSocket(5000);
        Class.forName("com.mysql.cj.jdbc.Driver");
        //connessione al database
        connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
    }

    @Override
    public void run() {
        try {
            while(true){
                socket = serverSocket.accept();
                printWriter = new PrintWriter(socket.getOutputStream(),true);
                bufferedReader =  new BufferedReader(new InputStreamReader(socket.getInputStream()));
                message = bufferedReader.readLine();
                stmt = (Statement) connection.createStatement();
                resultSet = stmt.executeQuery(message);
                while (resultSet.next()) {
                    String id = resultSet.getString(1);
                    String nome = resultSet.getString(2);
                    String cognome = resultSet.getString(3);
                    String result = id + nome + cognome;
                    printWriter.println(result);
                }

            }
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
        new Thread(new ServerSql()).start();
    }
}


public class SqlClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1",5000);
        BufferedReader bufferedReader =  new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);;
        String message;
        Connection connection;
        ResultSet resultSet;
        Statement stmt;
        Scanner scanner = new Scanner(System.in);
        message = scanner.nextLine();
        printWriter.println(message);
        System.out.println(bufferedReader.readLine());
        printWriter.flush();
        printWriter.close();
        bufferedReader.close();
    }
}

As you can see in the code for the server I saved all 3 columns of each row in 3 variables,then made a string and sent it to the client and it works but the client receives only one string,if I put the readline in a loop how do I know when to stop it? Should I make a Thread so it's always listening? I was wondering what was the best way to do this, at first I wanted to serialize the resultset but it doesn't implement serializable; So should I use a bidimensional array ? If yes what is the code to put every record in it's place?

I searched everywhere but I can't understand what is the correct way to do this,please help.

bob tang :

How about you iterate the result set from server, and save it into a List, and then jsonify the List as String and send it to client. The client can convert the json string to List again. there are some libraries can be utilized for json conversions.

if you does not like the idea of json, you can also try other existing data types. or just create your own data type implementing the serializable as your client and server are both in java.

if your data volume is large, you can control at the server side on how many records to send in one go, for example 10000 per batch. each 10000, you send the data as a json string. And your client has to keep listening, until it reads something from the server as end of the whole session, for example, you receive a string from server: "end", and then you stop the read.

in your case, if you want to read line by line from server, you can have a loop keeps reading, until server sends "bye". And your server can send "bye" at then end of sending your resultset

       while(true){
            String receiveMessage = bufferedReader.readLine();//receive from server

            if(receiveMessage.equals("bye")) 
                break;

            System.out.println(receiveMessage); 
        }       

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=218457&siteId=1