Skip to content

Instantly share code, notes, and snippets.

@sheharyarn
Created November 12, 2014 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheharyarn/37143305b6bddbf6c125 to your computer and use it in GitHub Desktop.
Save sheharyarn/37143305b6bddbf6c125 to your computer and use it in GitHub Desktop.
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