Java创建和更新mysql表语法错误

Java创建和更新mysql表语法错误,java,mysql,sql-update,Java,Mysql,Sql Update,我不知道如何解决这个问题。我在MySQLWorkbench中测试了SQL语句,它运行正常 公共void updateTable引发SQLException { String query=SET SQL\u SAFE\u UPDATES=0;删除表(如果存在);studentCopy;创建表studentCopy select*from student;\n+ 更新studentCopy加入选择ID,sumcredits new\u tot\u cred\n+ 使用课程id从左加入课程,其中成绩不

我不知道如何解决这个问题。我在MySQLWorkbench中测试了SQL语句,它运行正常

公共void updateTable引发SQLException { String query=SET SQL\u SAFE\u UPDATES=0;删除表(如果存在);studentCopy;创建表studentCopy select*from student;\n+ 更新studentCopy加入选择ID,sumcredits new\u tot\u cred\n+ 使用课程id从左加入课程,其中成绩不为空且成绩为“F”\n+ 使用ID set tot\u cred=cred.new\u tot\u cred;按ID cred分组\n+ 将SQL\u安全\u更新设置为1;\n+ 从studentCopy中选择*;; resultSet=statement.executeQueryquery; } sql.SQLSyntaxErrorException:您的sql语法有错误;检查与您的MySQL服务器版本对应的手册,了解使用near'drop table(如果存在studentCopy)的正确语法;创建表studentCopy从第1行的student中选择* 位于com.mysql.cj.jdbc.exceptions.SQLError.createSQLExceptionSQLError.java:120 位于com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateExceptionsqleexceptionsmapping.java:122 位于com.mysql.cj.jdbc.StatementImpl.executeQueryStatementImpl.java:1198 在MyQuery.updateablemyquery.java:157//resultSet=statement.executeQueryquery; 在TestMyQuery.mainTestMyQuery.java:38//main方法调用 这个查询在workbench中工作

设置SQL\u SAFE\u UPDATES=0; 下表学生复印件; 创建表studentCopy select*from student; 更新studentCopy加入选择ID,sumcredits new\u tot\u cred from使用课程id向左加入课程,其中成绩不为null且成绩为“F” 按ID cred分组,使用ID set tot_cred=cred.new_tot_cred; 设置SQL\u SAFE\u UPDATES=1; 从studentCopy中选择*;
不要像从workbench.insted复制一样在循环中逐个执行查询

公共void updateTable引发SQLException{ 字符串查询[]={ 将SQL\u安全\u更新设置为0;, 删除表(如果存在studentCopy;), 创建表studentCopy select*from student;, 更新studentCopy加入选择ID,sumcredits new_tot_cred;, 使用课程id从左加入课程,其中成绩不为空且成绩为“F”;, 使用ID set tot_cred=cred.new_tot_cred;,按ID cred分组;, 将SQL\u安全\u更新设置为1;, 从studentCopy中选择*; }; 对于int i=0;i 您可以为要执行的每个查询创建单独的查询字符串,并将这些查询添加到批处理中。例如,我在这里创建了4个查询

String sql0 = "SET SQL_SAFE_UPDATES = 0;";
String sql1 = "insert into employees(first,last,age) values('Foo','Bar',18);";
String sql2 ="create or replace table employeesCopy as select  id, first, last, age  from employees;";
String sql3 ="update employees set first='changed' where id = 1;";
可以将这些查询添加到语句对象中

 con.setAutoCommit(false); //to make sure data doesn't update if exception  occurs
 Statement stmt =  con.createStatement();
 stmt.addBatch(sql0);
 stmt.addBatch(sql1);
 stmt.addBatch(sql2);
 stmt.addBatch(sql3);
在批处理中添加每个查询后,可以执行批处理

 stmt.executeBatch();
 con.commit(); // commiting all the data
限制:无法在批处理中执行选择查询

 stmt.executeBatch();
 con.commit(); // commiting all the data

如果有我不知道的其他限制

一次执行一条sql语句。将它们放入一个数组中,然后循环执行。您认为SQL\u SAFE\u更新的作用是什么?为什么要抄桌子?您不是刚刚完成了更新查询的SELECT表单吗?这是一个作业。我想证明我知道如何在不影响现有表的情况下更新表。这很有帮助。我使用一个数组和一个for循环来添加批处理查询,并使用一个单独的executeQuery来返回select值。这是我实现您的解决方案时出现的错误。无法使用executeQuery发出数据操作语句。addBatch和executeBatch工作正常。