使用java怎么连接数据库并实现模糊查询?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
注释:需要注意的是在使用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();
}
}
}
看完上述内容,你们掌握使用java怎么连接数据库并实现模糊查询的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。