java连接数据库的模糊查询
发布日期:2021-11-02 05:00:19 浏览次数:2 分类:技术文章

本文共 1828 字,大约阅读时间需要 6 分钟。

1:模糊查询是比较常见的一种查询方式,例如在订单表中,包含有订单的具体日期。如果要查询某年某月的订单信息,最好的方式就是使用模糊查询。进行模糊查询需要使用关键字LIKE。在使用LIKE关键字进行模糊查询时,可以使用通配符"%",来代替0个或者多个字符,使用下划线_来代表一个字符。

注释:需要注意的是在使用LIKE的时候,后面的查询条件需要加 ’ ',英文状态下的单引号引起来,不然报错如下

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘%别%’ at line 1

package com.ningmeng;

import java.sql.*;

public class Test07 {

public static void main(String[] args) {    // TODO Auto-generated method stub    try {        Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动        System.out.println("加载数据库驱动成功");        String url="jdbc:mysql://localhost:3306/test";//声明自己的数据库test的url        String user="root";//自己的数据库用户名        String pass="123456";//自己的数据库密码        //建立数据库连接,获得连接的对象conn        Connection conn=DriverManager.getConnection(url,user,pass);        System.out.println("连接数据库驱动成功");        Statement stmt=conn.createStatement();//创建一个Statement对象        String sql="select * from users where username like '%别%' ";//生成sql语句        ResultSet rs=stmt.executeQuery(sql);//执行sql语句        int id,age,sex;        String username,password;        System.out.println("id\t 用户名\t 密码\t 性别\t 年龄");        while(rs.next()){            id=rs.getInt("id");            username=rs.getString(2);            password=rs.getString("password");            age=rs.getInt(4);            sex=rs.getInt("age");            System.out.println(id+"\t"+username+"\t"+password+"\t"                    +sex+"\t"+age);//输出查询结果        }        System.out.println("模糊查询成功");        conn.close();//关闭数据库连接        System.out.println("关闭数据库连接成功");    } catch (ClassNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (SQLException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    }

}

在这里插入图片描述

转载地址:https://blog.csdn.net/weixin_43488355/article/details/84279565 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java中构造方法的特征及其作用
下一篇:eclipse不能自动弹出提示的解决办法

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月17日 14时39分36秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章