java sql指定关键词的模糊查询
指定关键词的模糊查询:
package com.mldn;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Prepared
{ // 连接驱动路径
public static final String DRIVER = “com.mysql.jdbc.Driver”; // “org.gjt.mm.mysql.driver”
// 定义数据源URL:数据库地址
public static final String DBURL = “jdbc:mysql://localhost:3306/school?characterEncoding=utf8”;
// 定义数据库登录的用户名:
public static final String USERNAME = “root”;
// 定义数据库登录的密码:
public static final String PASSWORD = “123456”;
public static void main(String[] args) throws Exception // 抛出所有异常
{
Connection conn = null; // 数据库连接
PreparedStatement pstmt = null; // 预处理语句
ResultSet rs = null; // 接收查询结果
Class.forName(DRIVER); // 加载驱动
conn = DriverManager.getConnection(DBURL, USERNAME, PASSWORD); // 获取连接
// 查询操作:模糊查询
String keyword = “k”; // 查询关键字
int keyword1 = 20;
String sql = “SELECT id, name, age, sex, birthday FROM student WHERE name LIKE ? OR age LIKE ? OR sex LIKE ?”;
// 获取预编译对象
pstmt = conn.prepareStatement(sql);
// 设置字段:定义通配符?
pstmt.setString(1, “%” + keyword + “%”);
pstmt.setInt(2, keyword1);
pstmt.setString(3, “%” + keyword + “%”);
// 执行查询操作
rs = pstmt.executeQuery();
// 输出查询结果
while(rs.next())
{
int id = rs.getInt(“id”); // 获取id
String name = rs.getString(“name”); // 获取name
int age = rs.getInt(“age”); // 获取年龄
String sex = rs.getString(“sex”); // 获取性别
java.util.Date date = rs.getDate(“birthday”); // 获取生日
System.out.print(“id: ” + id + ” ” + “姓名:” + name + ” ” + “年龄:” + age + ” ”
+ “性别:” + sex + ” ” + “生日:” + date + “\n”);
}
// 关闭所有操作和连接!
rs.close();
pstmt.close();
conn.close();
}
}
/*
ubuntu@xu-desktop:~$ javac -d . work/Prepared.java
ubuntu@xu-desktop:~$ java com.mldn.Prepared
id: 1 姓名:王敏 年龄:20 性别:女 生日:2009-01-05
id: 21 姓名:ll 年龄:20 性别:男 生日:null
id: 25 姓名:k187 年龄:29 性别:男 生日:1982-02-25
// PreparedStatement的模糊查询很有用!
// 开发中很少用Statement,而是用PreparedStatement!
*/
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《java sql指定关键词的模糊查询》
本文地址:http://www.xiupu.net/archives-154.html
关注公众号:
微信赞赏
支付宝赞赏