[英]servlet init method fails to create mysql tables - why?
我的Java Servlet初始化方法無法創建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.
//與dbase的est連接-設置表后,效果很好
//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);
}
}
您不能使用stmt.executeQuery( query );
正如醫生所說-
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.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.