无法使用SQLite

时间:2017-02-24 16:37:20

标签: java sqlite jdbc

我试图创建一个包含名称列表的表。这输出:

  

"无法创建table_name"

以前工作过,我使用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();
        }
    }
}

编辑:它确实有效,只需刷新它。似乎没有实际问题

2 个答案:

答案 0 :(得分:0)

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

或者你能否提出引发的例外

答案 1 :(得分: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

Ooops这是逻辑

此错误是逻辑,它始终返回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");
}

希望这项工作与您合作。