Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java: Create Tables in SQLite beautifully
public class SQLiteHelper extends SQLiteOpenHelper {
private static final String BOOK_TABLE = "books";
private static final HashMap<String, String> BOOK_FIELDS = new HashMap<String, String>() {{
put("title", "TEXT");
put("author", "TEXT");
put("sales", "INTEGER"); // Neatly write fields and their types
}};
// ...
@Override
public void onCreate(SQLiteDatabase db) {
createTable(db, BOOK_TABLE, BOOK_FIELDS); // Create the table in a single, beautiful line.
}
// This function does all the dirty work
static public void createTable(SQLiteDatabase db, String tableName, HashMap<String, String> fields) {
String command = "CREATE TABLE " + tableName + " ( id INTEGER PRIMARY KEY AUTOINCREMENT";
for (Map.Entry<String, String> entry : fields.entrySet())
command = command + ", " + entry.getKey() + " " + entry.getValue();
command = command + " )";
db.execSQL(command);
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment