如何使用Java线程从MySQL检索数据?

时间:2016-05-04 15:25:38

标签: java mysql multithreading

我有一个场景,多个客户端连接到一个从MySQL表中检索数据的服务器。在这种情况下,它是具有id,username和password列的users表。 在服务器端是以下代码:

Server.java(代码的一部分)

public void run() {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
        writer.println("[type 'bye' to disconnect]");
        String commandType = null, username = null, password = null;
        while (true) {

            String line = reader.readLine();
            String[] parts = line.split(" ");

            for (int i = 0; i < parts.length; i++) {
                commandType = parts[0];
                username = parts[1];
                password = parts[2];
            }

            if (commandType.equals("!login")) {
                if (db.login(username, password)) {
                    writer.println("Welcome");

                } else {
                    writer.println("Wrong credentials");
                }
            }

            if (line.trim().equals("bye")) {
                writer.println("bye!");
                break;
            }

        }
    } catch (Exception e) {
        System.err.println("Exception caught: client disconnected.");
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            ;
        }
    }
}

在DBManager类中我有登录方法:

public synchronized boolean login(String username, String password) throws SQLException {
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", "root");

    Statement st = con.createStatement();

    String sql = "SELECT username, password FROM users WHERE username = " + username + " AND password = "
            + password;

    ResultSet rs = st.executeQuery(sql);

    while (rs.next()) {

        String uname, pass;
        uname = rs.getString("username");
        pass = rs.getString("password");

        if (username.equals(uname) && password.equals(pass)) {
            return true;
        }

    }
    rs.close();
    st.close();
    con.close();
    return false;
}

所以,当客户发送:

!login admin admin

我可以用

打印命令类型,用户名和密码
writer.println("Client sends commandType: " + commandType + " , username: " + username + " password: " + password);

,但如果我想检查用户表中是否有admin admin,则客户端会自动断开与服务器的连接,并在服务器端抛出异常:客户端已断开连接。

1 个答案:

答案 0 :(得分:1)

客户端虽然听起来像是系统错误消息而被盗用,但事实并非如此! 这是你产生的东西。而不是:

} catch (Exception e) {
    System.err.println("Exception caught: client disconnected.");
} finally {

DO

} catch (Exception e) {
    e.printStackTrace();
} finally {

将显示真正的错误。