2017-02-24 123 views
1

我想創建一個名單在其中的表。這種輸出:無法與SQLite創建表

「無法創建表格名」

這是工作之前,我使用NetBeans IDE中使用SQLite 3.7.2。我也試過在數據庫上執行正常的語句。但它不會通過下面的Java代碼工作

class DatabaseHelper{  
    public void addToDb(String tbname, List<String> name){ 
     try { 
      String url = "jdbc:sqlite:D:/names.db"; 
      Class.forName("org.sqlite.JDBC"); 
      try(Connection conn = DriverManager.getConnection(url); 
        Statement stmt = conn.createStatement();){ 
       stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + "(id integer PRIMARY KEY AUTOINCREMENT," 
         + "name text NOT NULL)"); 

       name.forEach((s) -> { 
        try{ 
         stmt.execute("INSERT INTO " + tbname + "(name) VALUES('" + s + "')"); 
        }catch(SQLException e){ 
         e.printStackTrace(); 
        } 
       }); 
       System.out.println("Finished"); 
      }catch(SQLException e){ 
       e.printStackTrace(); 
      } 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

編輯:它確實有效,只需要刷新它。沒有實際的問題似乎

+0

未能創建數據庫或表,錯誤表示database_name,並在您的代碼中嘗試創建表? –

+0

這是一個錯字,我現在修復它 –

+0

打印所有的錯誤請 –

回答

0

嘗試與這樣的數據庫名創建表除外:

String query = "CREATE TABLE IF NOT EXISTS databasename." + tbname + 
       " (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)"; 

如果你的數據庫已經包含模式然後用這樣的模式名稱創建你的表格:

structure to create a table sqlite

CREATE TABLE [IF NOT EXISTS] [schema_name].table_name (

這樣:

String query = "CREATE TABLE IF NOT EXISTS sch_name." + tbname + 
       " (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)"; 

您可以在這裏瞭解更多:SQLite Create Table

哎呀,這是邏輯

此錯誤是邏輯它返回false所有的時間,如果你嘗試st.executeUpdate(q)和你查詢是成功的,它將返回0,因爲CREATE TABLE不會返回任何東西,因爲您始終得到否定結果,而不是像插入或更新它返回一個結果,當你執行你的語句,所以我建議你的代碼改成這樣:

boolean created; 
try { 
    q = "CREATE TABLE ..."; 
    Statement st = connection.createStatement(); 

    //you can use 
    System.out.println(st.executeUpdate(q)); 
    //or 
    System.out.println(st.execute(q)); 

    created = true; 
} catch (SQLException e) { 
    created = false; 
} 

//now you can check if your table is created or not 
if(created){ 
    System.out.println("Table created with sucess"); 
}else{ 
    System.out.println("Faild to create table"); 
} 

希望與你這項工作。

+0

感謝您的信息。 Java代碼返回創建表的失敗,並且在「表」下的服務選項卡中,我看不到該表。但是,當我刷新它,它在那裏 –

+0

所以,你的解決方案的工作?或者你是什麼意思@UnsolvedRubiks –

+0

它的工作,但它似乎需要通過服務選項卡 –

0
if(stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + ";"+"CREATE TABLE "+ tbname + "(id integer PRIMARY KEY AUTOINCREMENT," 
           + "name text NOT NULL)")) 

,或者你可以給升至

+0

你的代碼應該實現什麼功能? –

+0

stmt.execute返回布爾值 –