java链接mysql添加中文和模糊查询

时间:2023-03-09 04:28:56
java链接mysql添加中文和模糊查询
如下内容为转载
http://sunshinechen2008.blog.163.com/blog/static/107585374201162442643967/  
mysql如果不对乱码处理,对中文的插入修改以及where条件查询都会有影响,处理乱码:把连接url中写成
"jdbc:mysql://localhost/book?seUnicode=true&characterEncoding=UTF-8"。如下所示:
Class.forName("org.gjt.mm.mysql.Driver") ;
String url="jdbc:mysql://localhost/book?seUnicode=true&characterEncoding=UTF-8";
String userName="root";
String passWord="yang";
 conn= DriverManager.getConnection(url,userName,passWord);
 stmt = conn.createStatement();
模糊查询
String key = "软件";
String sql = "select * from book where b_name like '%"+key+"%'";
DB db=new DB();
PreparedStatement ps = db.conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
判断结果集ResultSet是否为空可以 用 if(rs!=null) 处理,如果用if(rs.next),然后再if中写
while (rs.next()),如果返回的结果集只有一条,那么,不会查询出结果。因为rs.next已经是游标跳到了下一条结果上面。