如何使用套接字发送PreparedStatement并使用ResultSet检索结果?

时间:2018-09-27 19:29:00

标签: java sql

我正在尝试利用套接字以及objectInputStream和ObjectOutputStream在服务器端查询数据库。我的问题是每次运行代码时,都会收到“ java.io.com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement42”异常。

我不知道这是一个愚蠢的错误还是什么?

客户:

public class ClientTest{
    static PreparedStatement ps;
    static ResultSet rs;
    public static void main(String[] args)throws SQLException, ClassNotFoundException, IOException{
        Socket client = new Socket("127.0.0.1",33000);
        ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(client.getInputStream());

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=movie_max_database;integratedSecurity=true");
        String sql = "SELECT * FROM users";
        PreparedStatement ps = con.prepareStatement(sql);
        out.writeObject(ps);
        ResultSet rs = (ResultSet)in.readObject();

        while(rs.next()){
            System.out.print("user ID: " + rs.getString(1) + " userName: " + rs.getString(2) + " userPassword: " 
                    + rs.getString(3));
        }
    }
}

服务器:

public class ServerTest{    
    public static void main(String[] args)throws SQLException,IOException,ClassNotFoundException{
        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=movie_max_database;integratedSecurity=true");
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        ServerSocket server = new ServerSocket(33000);
        Socket client = server.accept();

        ObjectInputStream in = new ObjectInputStream(client.getInputStream());
        ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());

        PreparedStatement ps =(PreparedStatement)in.readObject();
        ResultSet rs = ps.executeQuery();
        out.writeObject(rs);
    }
}

0 个答案:

没有答案