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\‘的这种形式插入。

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

时间: 2024-08-07 12:27:58

jdbc中如何实现模糊查询的相关文章

在tp框架中实现数据模糊查询

首先数据库中有一个word表 //实例化一个数据对象$wcidobj = M('word');$p = I('get.p', 1);//得到查询关键字$keyword = I('get.keyword','');if($keyword <> ''){    //设置查询地图(模糊查询)    $map['name'] = array('like',"%$keyword%");    $this->assign('keyword',$keyword);}$pagesiz

WINFORM中的COMBOX模糊查询

有的时候下拉框中的元素过多不好查询,可以考虑进行模糊过滤查询. 在类文件的designer.cs中找到定义combox的模块,加入以下两行代码即可: this.combox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.combox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;

Mysql中的like模糊查询

MySql的like语句中的通配符:百分号.下划线和escape %代表任意多个字符 _代表一个字符 escape,转义字符后面的%或_,使其不作为通配符,而是普通字符匹配 数据库数据如下: 1.查找名字中以Lucy的字段 查询语句: select * from `user` where name like 'Lucy%' 结果: 2.查询名字是“Lucy”开头且后面只有一个字符的字段 查询语句: select * from `user` where name like 'Lucy_' 查询结果

ibatis中使用like模糊查询

无效的方法: select * from table1 where name like '%#name#%' 两种有效的方法: 1) 使用$代替#.此种方法就是去掉了类型检查,使用字符串连接,不过可能会有sql注入风险. select * from table1 where name like '%$name$%' 2) 使用连接符.不过不同的数据库中方式不同. mysql: select * from table1 where name like concat('%', #name#, '%'

Mybatis中的like模糊查询

1.  参数中直接加入%% param.setUsername("%CD%");      param.setPassword("%11%"); <select id="selectPersons" resultType="person" parameterType="person"> select id,sex,age,username,password from person where t

关于jdbc预编译下模糊查询的写法

PreparedStatement预编译的SQL可以有效的防止SQL注入,但是有些写法需要值得注意. Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ssm","root","root"); StringBuffer sql =new StringBuffer(&quo

Node.js和mybatis分别实现mysql中like变量模糊查询

<!-- mybatis --> <where> <if test="varName != '' and varName != null" > var_name like '%${varName}%' </if> </where> //node 变量 if (data.varName && data.varName != '') { sql += " where var_name like '%&qu

MyBatis Plus之like模糊查询中包含有特殊字符(_、\、%)

传统的解决思路:自定义一个拦截器,当有模糊查询时,模糊查询的关键字中包含有上述特殊字符时,在该特殊字符前添加\进行转义处理. 新的解决思路:将like 替换为 MySQL内置函数locate函数 一.问题提出 使用MyBatis中的模糊查询时,当查询关键字中包括有_.\.%时,查询关键字失效. 二.问题分析 1.当like中包含_时,查询仍为全部,即 like '%_%'查询出来的结果与like '%%'一致,并不能查询出实际字段中包含有_特殊字符的结果条目2.like中包括%时,与1中相同3.

Mybatis中模糊查询使用中文无法查询

解决Mybatis中模糊查询使用中文关键字无法查询 解决方法: 在mybatis中,采用模糊查询时,如果使用中文查询则无法查询出结果:采用英文则可以 解决方法:在sqlconfig.xml中:url的value值的后面加上?useUnicode=true&characterEncoding=UTF-8 原文地址:https://www.cnblogs.com/bestjdg/p/12043867.html