package com.sys;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class My {
private final static String jdbcdriver = "com.mysql.jdbc.Driver";
private final static String url = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8";
private Connection con =null;
   public ResultSet findall(String filter){
    PreparedStatement ps=null;
    ResultSet rs=null;
       try{
           Class.forName(jdbcdriver);
           con=DriverManager.getConnection(url);
     
           String fil="";
           if(filter!=null)fil="where"+" "+filter;
           //打印SQL语句
           System.out.println("select * from users "+fil);
          ps=con.prepareStatement("select * from users "+fil);
          rs=ps.executeQuery();         
      } 
      catch(SQLException e){
       System.out.println(e.toString());
      }
      catch (ClassNotFoundException e) {
e.printStackTrace();
}
      return rs;
   }
public static void main(String[] args) {
My p = new My();
String username="mary";
p.findall("username="+"'"+username+"'");
}
}
此程序抛出异常
select * from users where username='mary'
java.sql.SQLException: Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='此程序的SQL语句试过在MYSQL可以查出结果.....
如果输入的是select * from users where userid=1这样就可以运行..但是换成string就会抛出异常..

解决方案 »

  1.   

    你用的是mysql的那个版本??可能和你的连接字符串有关系。
    你设成jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gbk
      

  2.   

    哦,好像我记得有篇文章说过mysql默认字符集的写法和java不一样,UTF-8好像该写成utf8。
    你都试试吧,可能就是和连接字符串有关系。
      

  3.   

    肯定是与你的编码格式有关,因为错误提示中:utf8_general_ci 指的是与utf8( unicode )相关的东西,而latin1_swedish_ci也是指拉丁swedish(瑞士或者瑞典)语相关.而且当你把userid='1'换成userid=1的时候不出错误(因为1不是字符串了,而'1'才是).所以,与你其中的不同代码部分用不同码表不同或者数据库码表与代码中码表冲突而产生。你的这段代码制定的编码格式是characterEncoding=UTF-8,检查其余相关代码和数据库,另外还有jdbc驱动的版本的语言特征等。问题就在这些个地方。