2014-09-05 72 views
0

我一直在试图在数据库中创建一个表。该代码显示没有错误,运行良好,但最终没有在数据库中创建表。请帮助。Java:在数据库中创建表

public void createTable(){ 

    try { 

    String host = "jdbc:derby://localhost:1537/fypDB"; 
    String uname = "test"; 
    String pword = "test"; 
    Connection con = DriverManager.getConnection(host, uname, pword); 
    Statement stmt = con.createStatement(); 

    //username is valid variable from main class 
    String SQL = "CREATE TABLE "+username+" (classId VARCHAR(255), "+"PRIMARY KEY (classId))"; 
    stmt.executeUpdate(SQL); 
    System.out.println(SQL); 

    } catch (SQLException err){ 
     System.out.println(err.getMessage()); 
    } 
} 
+3

是自动提交启用连接? – 2014-09-05 14:36:50

+0

你不应该为每个用户创建一个表。有一个表,并在该表中使用户名成为一个字段。 – 2014-09-05 14:40:46

+0

根据这个http://stackoverflow.com/questions/11962028/create-table-in-by-sql-statement-using-executeupdate-in-mysql你缺少一个分号:'String SQL =“CREATE TABLE“+ username +”(classId VARCHAR(255),“+”PRIMARY KEY(classId));“;' – StephaneM 2014-09-05 14:44:39

回答

0

这应该这样做

Class.forName("org.apache.derby.jdbc.ClientDriver"); 
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1537/fypDB", 
                "yourUsername", "ypurPassword"); 
Statement stmt = con.createStatement(); 
stmt.execute(SQL); 

不要忘记把derbyclient.jar在你的classpath和关闭