我想在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)的表。是否可以使用更可重用的方法并在不知道列数的情况下创建表? 我希望一切都很清楚
答案 0 :(得分:2)
您可以使用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);
答案 1 :(得分:1)
您可以使用varargs,它只是一个数组。考虑每个奇数项都是属性名称,每个偶数项都是属性类型:
public static void createNewTable(String databaseName, String tableName, String ...attributes) {
if (attributes.length % 2 != 0) throw new IllegalArgumentException(...);
// attributes[0] - 1st attribute name
// attributes[1] - 1st attribute type
for (int i = 0; i < attributes.length-1; i+=2) {
// attributes[i] - i-st attribute name
// attributes[i+1] - 1st attribute type
// ...
}
// ...
}
我希望你能通过自己完成这种方法的休息逻辑。