java - 我如何创建一个动态且可重用的方法来使用 java 和 sqlite 创建表

标签 java sql sqlite

我想在不知道列数的情况下在 java 中创建一个 sqlite 表

public static void createNewTable(String databaseName, String tableName, String typeOfAttribute1, String attribute1) {
        // SQLite connection string
        String url = "jdbc:sqlite:" + databaseName;

        // static SQL statement for creating a new table
        String sql = "CREATE TABLE IF NOT EXISTS "+ tableName + " (" + attribute1 + " " + typeOfAttribute1 + ");";


        try (Connection conn = DriverManager.getConnection(url);
                Statement stmt = conn.createStatement()) {
            // create a new table
            stmt.execute(sql);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

在这种特定情况下,我不得不创建一个只有一列(attribute1)的表。是否可以采用更可重用的方法并在不知道列数的情况下创建表? 我希望一切都清楚

最佳答案

您可以使用 StringBuilder 而不是传递列列表,我建议使用采用 Array[column_name, column_type] 的列表,如下所示:

public static void createNewTable(String databaseName, String tableName, List<String[]> columns) {
    // SQLite connection string
    String url = "jdbc:sqlite:" + databaseName;
    String query = "CREATE TABLE IF NOT EXISTS " + tableName + " (";
    StringBuilder sql = new StringBuilder(query);

    String prefix = "";

    for (String[] s : columns) {
        sql.append(prefix);
        prefix = ", ";
        sql.append(s[0]);
        sql.append(" ");
        sql.append(s[1]);
    }

    sql.append(");");
    System.out.println(sql);

    try (Connection conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement()) {
        // create a new table
        stmt.execute(sql.toString());
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
}

public static void main(String[] args) {
    List<String[]> list = new ArrayList<>();
    list.add(new String[]{"col1", "type1"});
    list.add(new String[]{"col2", "type2"});
    list.add(new String[]{"col3", "type3"});
    list.add(new String[]{"col4", "type4"});
    list.add(new String[]{"col5", "type5"});
    createNewTable("database_name", "table_name", list);
}

这会告诉你:

CREATE TABLE IF NOT EXISTS table_name (col1 type1, col2 type2, col3 type3, col4 type4, col5 type5);

关于java - 我如何创建一个动态且可重用的方法来使用 java 和 sqlite 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42390475/

相关文章:

java - 如何访问jar中的可执行文件

java - hibernate -JPA : foreign key not set in ManyToOne relationship

sql - MS SQL 2008 - 如何将 xml 值转换为 ms sql 表中的行集合?

python - SQLite 中的多个唯一列

java - 我如何在Android中停止线程

sql - 根据条件和相同的主键将金额从一个表转移到另一个表中

php - SQL SUM() All with check 来自其他表

.net - 将 Entity Framework 4.1 与 SQLITE 结合使用

python - 使用 fetchone()[0] 时,"TypeError: ' NoneType ' object is unsubscriptable"

eclipse - java.io.FileNotFoundException : null\conf\wrapper. conf(系统找不到指定的路径)