jdbc中如何实现模糊查询

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jdbc中如何实现模糊查询相关的知识,希望对你有一定的参考价值。

情况如何

再利用jdbc执行sql语句的时候,对于其他的句子的执行没什么太大的问题:加上占位符,然后设置占位符的值。

但是在模糊查询的时候,一直都写不对,这里提供了两种可选的解决办法,以供参考。

解决方法

第一种:

String sql = "select studentname, age, phone, address, other from customer"
                + " where studentname like ? ";
pstmt = conn.prepareStatement(sql);
// 设定参数
pstmt.setString(1, "%" + customername + "%" );       
// 获取查询的结果集           
rs = pstmt.executeQuery();

第二种:

百分号直接写在sql语句中

String sql = "select customercode, customername, phone, address, relationman, other from customer"
                + " where customername like \"%\"?\"%\" ";
pstmt = conn.prepareStatement(sql);           
// 设定参数
pstmt.setString(1, customername);       
// 获取查询的结果集           
rs = pstmt.executeQuery();

为什么会这样?

得研究一下PreparedStatement是如何来处理占位符的。

在PresparedStatement中的setString()方法中有如下的一段代码:

public void setString(int parameterIndex, String x) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        // 如果x是空的话,就直接调用另外的方法
        if (x == null) {
            setNull(parameterIndex, Types.CHAR);
        } else {
            checkClosed();

            // 获得待插入的字符串的长度
            int stringLength = x.length();

            if (this.connection.isNoBackslashEscapesSet()) {
                // Scan for any nasty chars

                // 判断字符串中是否需要进行转义的字符
                boolean needsHexEscape = isEscapeNeededForString(x, stringLength);

                // 如果x里面没有需要转义的字符串
                if (!needsHexEscape) {
                    byte[] parameterAsBytes = null;

                    StringBuilder quotedString = new StringBuilder(x.length() + 2);

                    // 直接就以字符串的形式加入到串中
                    quotedString.append(‘\‘‘);
                    quotedString.append(x);
                    quotedString.append(‘\‘‘);

                    if (!this.isLoadDataQuery) {
                        parameterAsBytes = StringUtils.getBytes(quotedString.toString(), this.charConverter, this.charEncoding,
                                this.connection.getServerCharset(), this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                    } else {
                        // Send with platform character encoding
                        parameterAsBytes = StringUtils.getBytes(quotedString.toString());
                    }

                    setInternal(parameterIndex, parameterAsBytes);
                } else {
                    byte[] parameterAsBytes = null;

                    if (!this.isLoadDataQuery) {
                        parameterAsBytes = StringUtils.getBytes(x, this.charConverter, this.charEncoding, this.connection.getServerCharset(),
                                this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                    } else {
                        // Send with platform character encoding
                        parameterAsBytes = StringUtils.getBytes(x);
                    }

                    setBytes(parameterIndex, parameterAsBytes);
                }

                return;
            }

            String parameterAsString = x;
            boolean needsQuoted = true;

            if (this.isLoadDataQuery || isEscapeNeededForString(x, stringLength)) {
                needsQuoted = false; // saves an allocation later

                StringBuilder buf = new StringBuilder((int) (x.length() * 1.1));

                buf.append(‘\‘‘);

                //
                // Note: buf.append(char) is _faster_ than appending in blocks, because the block append requires a System.arraycopy().... go figure...
                //
                // 如果需要转义则遍历需要转义的字符
                for (int i = 0; i < stringLength; ++i) {
                    char c = x.charAt(i);

                    switch (c) {
                        case 0: /* Must be escaped for ‘mysql‘ */
                            buf.append(‘\\‘);
                            buf.append(‘0‘);

                            break;

                        case ‘\n‘: /* Must be escaped for logs */
                            buf.append(‘\\‘);
                            buf.append(‘n‘);

                            break;

                        case ‘\r‘:
                            buf.append(‘\\‘);
                            buf.append(‘r‘);

                            break;

                        case ‘\\‘:
                            buf.append(‘\\‘);
                            buf.append(‘\\‘);

                            break;

                        case ‘\‘‘:
                            buf.append(‘\\‘);
                            buf.append(‘\‘‘);

                            break;

                        case ‘"‘: /* Better safe than sorry */
                            if (this.usingAnsiMode) {
                                buf.append(‘\\‘);
                            }

                            buf.append(‘"‘);

                            break;

                        case ‘\032‘: /* This gives problems on Win32 */
                            buf.append(‘\\‘);
                            buf.append(‘Z‘);

                            break;

                        case ‘\u00a5‘:
                        case ‘\u20a9‘:
                            // escape characters interpreted as backslash by mysql
                            if (this.charsetEncoder != null) {
                                CharBuffer cbuf = CharBuffer.allocate(1);
                                ByteBuffer bbuf = ByteBuffer.allocate(1);
                                cbuf.put(c);
                                cbuf.position(0);
                                this.charsetEncoder.encode(cbuf, bbuf, true);
                                if (bbuf.get(0) == ‘\\‘) {
                                    buf.append(‘\\‘);
                                }
                            }
                            // fall through

                        default:
                            buf.append(c);
                    }
                }

                buf.append(‘\‘‘);

                parameterAsString = buf.toString();
            }

            byte[] parameterAsBytes = null;

            if (!this.isLoadDataQuery) {
                if (needsQuoted) {
                    parameterAsBytes = StringUtils.getBytesWrapped(parameterAsString, ‘\‘‘, ‘\‘‘, this.charConverter, this.charEncoding,
                            this.connection.getServerCharset(), this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                } else {
                    parameterAsBytes = StringUtils.getBytes(parameterAsString, this.charConverter, this.charEncoding, this.connection.getServerCharset(),
                            this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                }
            } else {
                // Send with platform character encoding
                parameterAsBytes = StringUtils.getBytes(parameterAsString);
            }

            setInternal(parameterIndex, parameterAsBytes);

            this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.VARCHAR;
        }
    }
}

protected final void setInternal(int paramIndex, byte[] val) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {

        int parameterIndexOffset = getParameterIndexOffset();

        checkBounds(paramIndex, parameterIndexOffset);

        this.isStream[paramIndex - 1 + parameterIndexOffset] = false;
        this.isNull[paramIndex - 1 + parameterIndexOffset] = false;
        this.parameterStreams[paramIndex - 1 + parameterIndexOffset] = null;
        this.parameterValues[paramIndex - 1 + parameterIndexOffset] = val;
    }
}

在setString()方法中,字符串会变为\‘string\‘的这种形式插入。

第一种方法可以成功比较好理解一些,但是第二种就有点想不通了。这里从源代码看出一点端倪就是会判断字符串中有没有转义字符,而且还会判断字符串需不需要被括起来。现就了解了这些,有空再深钻。




































































































以上是关于jdbc中如何实现模糊查询的主要内容,如果未能解决你的问题,请参考以下文章

ComboBox如何实现对数据库模糊查询!!!

搜索框实现模糊查询方法 - js

如何使用AS3,实现百度模糊查询提示那样。

js如何实现模糊查询

怎样基于Redis实现模糊查询

spring jdbc模糊查询代码怎么写