我想在不知道列数的情况下在 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/