INSERT INTO 插入语句报错

来源:5-2 项目作业

jia_蛙

2020-03-11 11:04:01

我在编写循环插入图书的时候出现了错误,好像说我插入语句有问题,我找了好久都没发现
java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.zhou.book.global.KernelController.service(KernelController.java:57)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at com.zhou.book.global.EncodingFilter.doFilter(EncodingFilter.java:27)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: 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 '' at line 1
### The error may exist in com/zhou/book/dao/BookDao.java (best guess)
### The error may involve com.zhou.book.dao.BookDao.add-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO book(category_id,name,level,price,img_path,create_time,update_time) VALUES
### Cause: 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 '' at line 1
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:199)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:184)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:62)
	at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:144)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:85)
	at com.sun.proxy.$Proxy23.add(Unknown Source)
	at com.zhou.book.biz.impl.BookBizImpl.add(BookBizImpl.java:31)
	at com.zhou.book.controller.BookController.add(BookController.java:63)
	... 30 more
Caused by: 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 '' at line 1
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
	at com.mysql.jdbc.Util.getInstance(Util.java:408)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3933)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3869)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2675)
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1912)
	at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1251)
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:47)
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74)
	at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50)
	at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
	at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63)
	at com.sun.proxy.$Proxy20.update(Unknown Source)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:197)
	... 37 more
@Insert("<script>" +
        "INSERT INTO book(category_id,name,level,price,img_path,create_time,update_time) VALUES" +
        "<foreach collection ='list' item='book' separator=','>" +
        "(#{book.categoryId},#{book.name},#{book.level},#{book.price},#{book.imgPath},#{book.createTime},#{updateTime})"+
        "</foreach>" +
        "</script>")
@Options(useGeneratedKeys = true,keyProperty = "id")
void add(List<Book> list);
//图书实体
public class Book {
    private int id;//图书id
    private int categoryId;//图书分类id
    private String name;//图书名称
    private int level;//图书等级
    private int price;//图书价格
    private String imgPath;//图书地址
    private Timestamp createTime;//创建图书时的时间
    private Timestamp updateTime;//最后编辑图书的时间
    private Category category  = new Category();//图书分类
    getter settter .....
  }
// /admin/Book/add.do          添加图书
public void add(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, FileUploadException {
    List<Book> bookList = builderBook(request);
    bookBiz.add(bookList);
    request.getRequestDispatcher("/admin/Book/bookList.do").forward(request,response);
}

public List<Book> builderBook(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException {
    List<Book> bookList = new ArrayList<Book>();
    //使用FileUpload文件上传固定步骤:
    //1.创建工厂类
    FileItemFactory factory = new DiskFileItemFactory();
    //2.创建解析器
    ServletFileUpload upload = new ServletFileUpload(factory);
    //3.使用解析器解析request对象
    List<FileItem> list = upload.parseRequest(request);

    //4.对二进制数据和普通表单控件数据进行判断
    //因为可以同时添加多个图书,这里我们准备好属性数组,将获取到的值存入,到最后再循环添加
    List<Integer> cid =new ArrayList<Integer>();
    List<String> name =new ArrayList<String>();
    List<Integer> level =new ArrayList<Integer>();
    List<Integer> price =new ArrayList<Integer>();
    List<String> image =new ArrayList<String>();

    for(FileItem item : list){
        if(item.isFormField()){
            //普通表单控件
            if(item.getFieldName().equals("cid")){//图书分类id
                cid.add(Integer.parseInt(item.getString("UTF-8")));
            }else if(item.getFieldName().equals("name")){//图书名称
                name.add(item.getString("UTF-8"));
            }else if(item.getFieldName().equals("level")){//图书等级
                level.add(Integer.parseInt(item.getString("UTF-8")));
            }else if(item.getFieldName().equals("price")){//图书价格
                price.add(Integer.parseInt(item.getString("UTF-8")));
            }
        }else {
            //设置二进格式数据
            if(item.getFieldName().equals("image")){
                //设置图片大小最低限制
                if(item.getSize()<=100) continue;
                //获取项目物理的根路径
                String rootPath = request.getServletContext().getRealPath("/");
                System.out.println(rootPath);
                String path = item.getName();//获取图片的名字
                String type = ".jpg";//设置图片默认类型
                if(path.indexOf(".")!= -1){
                    //获取后缀ming  名字带.表示有后缀名
                    type = path.substring(path.lastIndexOf("."));
                    System.out.println("图片类型: " + type);
                }
                path = "/download/images/"+System.currentTimeMillis()+type;//获得图片在项目中的地址
                try {
                    //将二进制数据写入到准备好的图片中
                    item.write(new File(rootPath+path));
                    image.add(path);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *   List<String> category =new ArrayList<String>();
     *         List<String> name =new ArrayList<String>();
     *         List<Integer> level =new ArrayList<Integer>();
     *         List<Integer> price =new ArrayList<Integer>();
     *         List<String> image =new ArrayList<String>();
     */
    //5.处理数据
    for(int i=0;i<cid.size();i++){
        Book book = new Book();
        book.setName(name.get(i));//图书名
        book.setLevel(level.get(i));//图书等级
        book.setPrice(price.get(i));//图书价格
        book.setImgPath(image.get(i));//图书封面地址
        book.setCategoryId(cid.get(i));//图书分类id
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        book.setCreateTime((new Timestamp(System.currentTimeMillis())));//图片创建时间
        book.setUpdateTime((new Timestamp(System.currentTimeMillis())));//图片最后一次的修改时间
        bookList.add(book);
    }
    return bookList;
}


写回答

1回答

好帮手慕柯南

2020-03-11

同学你好!

老师看你的sql是没有问题的。可能是你传入的数据不正确导致的。

注意:要上传文件,否则会导致数据不正确

如果文件上传了,仍然报错,你在booList这里打一个断点,看一下里面的数据是否正确

http://img.mukewang.com/climg/5e68a0470977d4d608530497.jpg

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~


0
hia_蛙
h 之前我在这里打过断点,但是程序根本没运行到这里就报错了,我看到错误写了一对SQL有关的,我就一直以为是SQL问题,我刚才按老师说可能传入的数据不正确,然后找了一下,发现是jsp页面传过来的数据,后端接收出错了,现在已经修改好了,谢谢老师!
h020-03-11
共1条回复

0 学习 · 8016 问题

查看课程