如何检查表中是否有字符串?

时间:2015-10-11 14:12:10

标签: java mysql sql string

Here's the table (tblemployees) 如何将使用文本文件的代码转换为将使用数据库(表)的代码。

int intcurrentLine = -1;
String[] strLineSplit = (sb.toString()).split("\\r?\\n"); // converts sb to string then splits it by line
int intNumElements = strLineSplit.length; // number of elements
while (intcurrentLine != (intNumElements - 1)) {
    intcurrentLine++;
    String[] strWords = (strLineSplit[intcurrentLine]).split(" ", 2); // splits the current line by the first instance(space)
    if (strEmpID.equals(strWords[0])) { // checks if the employee ID is available
        JOptionPane.showMessageDialog(null, "Welcome " + strWords[1] + ", you have successfully logged in.");
        strCheck = 1; // to confirm and go to time in and out process
        break;
    }
    if ((intcurrentLine + 1) == intNumElements) { // condition to state that ID cant be found from the employee list
        JOptionPane.showMessageDialog(null, "No such employee, please check the ID No. that you entered.");
    }
}

现在我想搜索列中是否包含员工编号。我怎么把它放到一个条件,我一直在寻找,但无法找到一个明确的答案。他们只是像这样搜索

String queryCheck = "SELECT * from messages WHERE EmpIDNo = 'COMSCI0001'";
ResultSet res = st.executeQuery(queryCheck);
然后我迷路了,如果员工没有,如何制定条件。不存在会发生什么事情会发生。我只是混淆了如何制定条件。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

String queryCheck = "SELECT * FROM messages WHERE EmpIDNo = 'COMSCI0001' LIMIT 1";
ResultSet res = st.executeQuery(queryCheck);
boolean exists = res.next();

boolean变量exists将指示是否存在匹配记录。

请注意,我在SQL的末尾添加了LIMIT 1作为优化,以避免获取超出实际需要的数据。