我正在尝试执行hibernate插入sql查询
String sqlQuery = "insert into examschedule (class_id,examtype_id,subject_id,examdate,start_time,end_time,messagetype_id,createddate) values";
String sql1 =sql1+ "("+ classes.getId()+","+
exType.getId()+","+
subjectName.getId()+","+
"'"+sqlDate+"'"+","+"'"+startTime+"'"+","+"'"+endTime+"'"+","+msgType.getId()+","+"'"+sqlTimestamp+"'"+");";
System.out.println(sqlQuery+sql1);
query = session.createSQLQuery(sqlQuery);
int result = query.executeUpdate();
但是,当我尝试在 mysql 控制台中执行相同的查询时,我遇到了异常,没有语法错误,它执行完美
为什么当我在查询对象上调用 createSQLQuery()) 时,值参数就会被删除。
18:20:16,855 INFO [stdout] (http-localhost-127.0.0.1-8080-2) insert into examschedule (class_id,examtype_id,subject_id,examdate,start_time,end_time,messagetype_id,createddate) values(13,1,5,'2015-09-07','11AM','12PM',2,'2015-09-12 18:20:16.855');
18:20:16,868 INFO [stdout] (http-localhost-127.0.0.1-8080-2) Hibernate: insert into examschedule (class_id,examtype_id,subject_id,examdate,start_time,end_time,messagetype_id,createddate) values
18:20:16,871 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-2) SQL Error: 1064, SQLState: 42000
18:20:16,871 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-2) 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
18:20:16,876 ERROR [stderr] (http-localhost-127.0.0.1-8080-2) org.hibernate.exception.SQLGrammarException: could not execute statement
最佳答案
我在评论中提到的代码中有一些错误:
String sqlQuery = "insert into examschedule (class_id,examtype_id,subject_id,examdate,start_time,end_time,messagetype_id,createddate) values";
String sql1 =sql1+ "("+ classes.getId()+","+
//^^ here you are adding undefined value remove it
exType.getId()+","+
subjectName.getId()+","+
"'"+sqlDate+"'"+","+"'"+startTime+"'"+","+"'"+endTime+"'"+","+msgType.getId()+","+"'"+sqlTimestamp+"'"+");";
System.out.println(sqlQuery+sql1); //complete query is in sqlQuery+sql1
query = session.createSQLQuery(sqlQuery); //here you are passing half query use sqlQuery+sql1
int result = query.executeUpdate();
考虑并尝试以下代码片段:
String sqlQuery = "insert into examschedule (class_id,examtype_id,subject_id,examdate,start_time,end_time,messagetype_id,createddate) values";
sqlQuery = sqlQuery + "("+ classes.getId()+","+
exType.getId()+","+
subjectName.getId()+","+
"'"+sqlDate+"'"+","+"'"+startTime+"'"+","+"'"+endTime+"'"+","+msgType.getId()+","+"'"+sqlTimestamp+"'"+");";
System.out.println(sqlQuery);
query = session.createSQLQuery(sqlQuery);
int result = query.executeUpdate();
Please don't to
SO
for debuging your snippet. Read What types of questions should I avoid asking?
关于java - Hibernate插入SQL语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32539227/