【发布时间】:2021-03-20 05:53:21
【问题描述】:
我不确定如何解决这个问题。我在 MySQLWorkbench 中测试了 SQL 语句,它可以工作。
public void updateTable() throws SQLException
{
String query = "SET SQL_SAFE_UPDATES = 0; drop table if exists studentCopy; create table studentCopy select * from student;\n" +
"update studentCopy join (select ID, sum(credits) new_tot_cred\n" +
"from takes left join course using(course_id) where grade is not null and grade<>'F'\n" +
"group by ID) cred using(ID) set tot_cred=cred.new_tot_cred;\n" +
"SET SQL_SAFE_UPDATES = 1;\n" +
"select * from studentCopy;";
resultSet = statement.executeQuery(query);
}
java.sql.SQLSyntaxErrorException: 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 'drop table if exists studentCopy; create table studentCopy select * from student' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1198)
at MyQuery.updateTable(MyQuery.java:157) // resultSet = statement.executeQuery(query);
at TestMyQuery.main(TestMyQuery.java:38) // main method call
此查询在工作台中有效。
SET SQL_SAFE_UPDATES = 0;
drop table studentCopy;
create table studentCopy select * from student;
update studentCopy join (select ID, sum(credits) new_tot_cred
from takes left join course using(course_id) where grade is not null and grade<>'F'
group by ID) cred using(ID) set tot_cred=cred.new_tot_cred;
SET SQL_SAFE_UPDATES = 1;
select * from studentCopy;
【问题讨论】:
-
一次执行 1 条 sql 语句。将它们放入一个数组中,然后循环执行。
-
您认为
SQL_SAFE_UPDATES会做什么?为什么要复制表格?你不是在 SELECT 形式的 UPDATE 查询之后吗? -
这是一个作业。我想证明我知道如何在不影响现有表的情况下更新表。
标签: java mysql sql-update