原代码是:
String sql = "select id,name,password,age,sex,birthday" +
"from user where name like ? or password like ? or sex like ?";
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
ps = conn.prepareStatement(sql); //实例化对象
ps.setString(1, "%" + keyWord + "%");
ps.setString(2, "%" + keyWord + "%");
ps.setString(3, "%" + keyWord + "%");
报的错误是:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'where name like '%�%' or password like '%�%' or sex like '%�%'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1912)
at com.heima.services.PreparedStatementDemo2.main(PreparedStatementDemo2.java:45)
刚开始看网上的资料 有的说是编码不对,,我就查看了我的MySQL数据库和myeclipse的编码都是utf-8,首先排除这个问题.
最后又在网上看资料说是sql语句写的不对,空格的问题,我也看了好多就是找不出了
折腾了一会发觉是少了一个空格
String sql = "select id,name,password,age,sex,birthday" +
"from user where name like ? or password like ? or sex like ?";
应该写成 " from user where name like ? or password like ? or sex like ?"; 这个from前面少了一个空格, 这是最容易犯得一个错误,因为代码太长,换到第二行后会自动出现双引号,,,而容易导致少了空格,弄成birthday和from变成了一个词birthdayfrom