sqlite模糊查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlite模糊查询相关的知识,希望对你有一定的参考价值。
参考技术A 主要是glob、like两种方法.like可以设置是否区分大小写-默认不区分,_代表一个字符,%代表不确定数量个字符
glob区分大小写,?代表一个字符,*代表不确定数量个字符
示例代码
Class.forName("org.sqlite.JDBC");
String dbPath1 = "C:sqlitetestq.db";
new File(dbPath1).delete();
Connection conn = DriverManager.getConnection("jdbc:sqlite:"+dbPath1);
Statement stat = conn.createStatement();
stat.executeUpdate("create table if not exists stu1(name varchar(20), age int, score int) ;");
stat.executeUpdate("insert into stu1 values('A1',12,72);");
stat.executeUpdate("insert into stu1 values('A2',13,73);");
stat.executeUpdate("insert into stu1 values('A3',14,74);");
stat.executeUpdate("insert into stu1 values('D33',14,74);");
//stat.executeUpdate("PRAGMA case_sensitive_like =1;");
stat.executeUpdate("PRAGMA case_sensitive_like =0;");
ResultSet rs = stat.executeQuery("select s1.name,s1.age,s1.score from stu1 s1 where s1.name like '%3' ;");
while (rs.next())
System.out.println("name = " + rs.getString("name")+" age:"+rs.getInt("age")+" score:"+rs.getInt("score"));
rs.close();
rs = stat.executeQuery("select s1.name,s1.age,s1.score from stu1 s1 where s1.name like 'A_' ;");
while (rs.next())
System.out.println("name = " + rs.getString("name")+" age:"+rs.getInt("age")+" score:"+rs.getInt("score"));
rs.close();
rs = stat.executeQuery("select s1.name,s1.age,s1.score from stu1 s1 where s1.name like 'a_' ;");
while (rs.next())
System.out.println("name = " + rs.getString("name")+" age:"+rs.getInt("age")+" score:"+rs.getInt("score"));
rs.close();
rs = stat.executeQuery("select s1.name,s1.age,s1.score from stu1 s1 where s1.name GLOB 'd3*' ;");
while (rs.next())
System.out.println("name = " + rs.getString("name")+" age:"+rs.getInt("age")+" score:"+rs.getInt("score"));
rs.close();
System.out.println("----");
rs = stat.executeQuery("select s1.name,s1.age,s1.score from stu1 s1 where s1.name glob 'D3?' ;");
while (rs.next())
System.out.println("name = " + rs.getString("name")+" age:"+rs.getInt("age")+" score:"+rs.getInt("score"));
rs.close();
stat.close();
conn.close();
输出
name = A3 age:14 score:74
name = D33 age:14 score:74
name = A1 age:12 score:72
name = A2 age:13 score:73
name = A3 age:14 score:74
name = A1 age:12 score:72
name = A2 age:13 score:73
name = A3 age:14 score:74
----
name = D33 age:14 score:74
Sqlite模糊查询通配符%和下划线无法匹配问题
问题描述:
使用以下like语句查询,
select * from table where columnName like \'%_%\';
结果是返回全部的记录,不是想要的结果!
网上搜索一下,原因如下:
在like语句中的“下划线”代表匹配“任意一个字符”,“%”代表匹配“任意多个字符”。
解决方案:
方案一:使用escape转义
escape的内容可以任意,只要保证前后一致即可
select * from table where columnName like \'%\\_%\' escape \'\\\';
select * from table where columnName like \'%|_%\' escape \'|\';
se
以上是关于sqlite模糊查询的主要内容,如果未能解决你的问题,请参考以下文章
怎样对android开发中的sqlite数据库进行模糊查询,并返回一个Cursor