我的java servlet init方法无法创建mysql表 - 我想知道原因。当我直接登录到mysql并创建表时,生活是美好的,当我删除表并运行servlet时 - 没有表,servlet抛出一个异常(还没有把它挖出来)。代码看起来像这样:
package ...;
import ... // quite a bit
@WebServlet("/MyClass")
public class MyClass extends HttpServlet {
public void init() throws ServletException {
try { Foo foo = Foo.getInstance();
foo.createTables();
} catch (Exception e) {
throw new ServletException("Error creating tables", e);
}
}
... //更多MyClass的东西 } // Foo是一个看起来像这样的单身人士:
package ...;
import ... // quite a bit
public class Foo {
public static final Foo INSTANCE = new Foo();
public static Foo getInstance() {
return INSTANCE;
}
... //更多Foo的东西,然后
public void createTables(){
try {
// first establish a connection
Connection connection = Foo.getInstance().getConnection(); // get connection est.
// est。连接到dbase - 一旦表格设置好了
//Create a query.
Statement stmt = connection.createStatement();
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL, "+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
ResultSet rs = stmt.executeQuery( query );
query = "CREATE TABLE IF NOT EXISTS result (" +
"uuid_Survey VARCHAR(36) NOT NULL, "+
"remoteAddress VARCHAR(15) NOT NULL, " +
"currentTime BIGINT NOT NULL, "+
" likert VARCHAR(40),"+
" numerical DOUBLE, " +
" open VARCHAR(40), "+
" PRIMARY KEY (uuid_Survey, remoteAddress, currentTime),"+
"FOREIGN KEY ix_survey_uuid (uuid_Survey) REFERENCES survey (uuid_Survey))" ;
rs = stmt.executeQuery( query );
connection.close();
} catch (Exception e) {
System.err.println("Error creating tables: " + e);
}
}
答案 0 :(得分:1)
您无法使用stmt.executeQuery( query );
正如Doc所说 -
ResultSet#executeQuery(String sql)
- 此方法执行给定的SQL语句,该语句返回单个ResultSet对象。其中 sql - 要发送到数据库的SQL语句,通常是静态 SQL SELECT语句
您可能希望使用execute()代替
赞stmt.execute(query);
或
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL,"+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
PreparedStatement statement = conn.prepareStatement(query);
int count = statement.executeUpdate();
if(count>=0){
System.out.println("Successfully created.");
}