我已经创建了一个在MySQL工作台中正常工作的查询,但是当我在eclipse中运行它时却不工作。与数据库的连接正常工作,因为对于更简单的查询,我得到了正确的结果。java代码: String queryAlter = "SELECT count(*) "; queryAlter += "INTO @exist "; queryAlter += "FROM information_schema.columns "; queryAlter += "WHERE table_schema = database() "; queryAlter += "and COLUMN_NAME = 'question" + (100 + number + 1)+"' "; queryAlter += "AND table_name = '"+ tableName+"'; "; queryAlter += "set @query = IF(@exist <= 0, 'alter table "+ tableName+" add column question" + (100 + number + 1)+" varchar(2048) NULL', "; queryAlter += "'select \\'Column Exists\\' status'); "; queryAlter += "use joomla30; "; queryAlter += "prepare stmt from @query; "; queryAlter += "EXECUTE stmt;";我收到一条信息:发生错误。可能用户/密码无效CopyMySQL.jdcC.Exv.jdc4.mySQLSythAcLogReExerExc:在SQL语法中有一个错误,请检查对应于MySQL服务器版本的手册,以便使用正确的语法,使用“SET@查询”=“(@存在查询字符串也是: SELECT count(*) INTO @exist FROM information_schema.columns WHERE table_schema = database() and COLUMN_NAME = 'question101' AND table_name = 'n0x3c_twoquestions_table'; set @query = IF(@exist <= 0, 'alter table n0x3c_twoquestions_table add column question101 varchar(2048) NULL', 'select \'Column Exists\' status'); use joomla30; prepare stmt from @query; EXECUTE stmt;我也在java中尝试过这个,我从MySQL Query works in PhpMyAdmin but not in JAVA Eclipse中读到: String s1 = "SELECT count(*) INTO @exist FROM information_schema.columns WHERE table_schema = database() and COLUMN_NAME = 'question" + (100 + number + 1)+"' AND table_name = '"+ tableName+"'; "; String s2 = "set @query = IF(@exist <= 0, 'alter table "+ tableName+" add column question" + (100 + number + 1)+" varchar(2048) NULL', 'select \\'Column Exists\\' status'); "; String s3 = "use joomla30; "; String s4 = "prepare stmt from @query; "; stmt.addBatch(s1); stmt.addBatch(s2); stmt.addBatch(s3); stmt.addBatch(s4); stmt.executeBatch(); conn1.commit();但我有个错误:java.sql.BatchUpdateException:无法通过executeUpdate()发出SELECT。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您可以使用两个不同的查询。首先是检查列的存在性:String countQuery = "select count(*) from information_schema.columns WHERE table_schema = database() and COLUMN_NAME = 'question106' and table_name='n0x3c_twoquestions_table'";如果countQuery返回0,则可以执行alterQuery:String alterQuery = "alter table n0x3c_twoquestions_table add column question106 varchar(2048) NULL";如果不想使用两个不同的查询,可以通过异常捕获来处理:String alterQuery = "alter table n0x3c_twoquestions_table add column question106 varchar(2048) NULL";try (Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement(alterQuery)) { ps.execute();} catch (SQLException e) { if (e.getErrorCode() == 1060) { columnExists = true; } else { // TODO handle exception }}我发现了错误代码MySQL Server error codes。 (adsbygoogle = window.adsbygoogle || []).push({});
09-05 09:11