When we usually use SQLite, if we have 10 tables, we have to write 10 statements, and only some of the names of the table statements need to be changed, it is time-consuming and laborious, but also error-prone, we know that when writing SQL statements are often written incorrectly, if the wrong program will be collapsed, And check 10 build statements can also, if there are 100 I'm going crazy. This article tells you how to quickly build a table by reflection.
1. We write a dbhelper inherited from Sqliteopenhelper
Public classDBHelperextendssqliteopenhelper{//version of the database Private Final Static intDb_version = 1; //Database name Private Final StaticString db_name = "Ladeng.db"; PrivateContext Mcontext; //we call the constructor of the parent class directly with super, so that we only need to pass in a context parameter when we instantiate the DBHelper. PublicDBHelper (Context context) {Super(Context, Db_name,NULL, db_version); This. Mcontext =context; } //This method is called when the database does not exist.@Override Public voidonCreate (Sqlitedatabase db) {createtables (db,0,0); } //call this method when the version number is changed@Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { //1. Delete the original table//2. Call OnCreate to re-create the database } /*** Build a table statement, you can build a table in just one row*/ Private voidCreatetables (Sqlitedatabase db,intOldversion,intnewversion) { //createtable (movie.class) returns the SQL Build table statement//db.execsql (SQL) executes this build statementDb.execsql (CreateTable (Movie.class)); } /*** If not, the default is to use class masterpieces to indicate *@paramClazz entity class *@return */ Private<T> String createtable (class<t>clazz) { returncreatetable (Clazz, Clazz.getsimplename ()); } /*** The real way to build a table *@paramClazz entity class *@paramTableName indicates *@returnSQL Build Table statement*/ Private<T> String createtable (class<t>Clazz, String tableName) { //instantiate a container that is used to stitch SQL statementsStringBuffer Sbuffer =NewStringBuffer (); //SQL statement, the first field is _id primary key auto-increment, this is universal, so write directly to the deadSbuffer.append ("CREATE table if not exists" + TableName + "+" (_id INTEGER PRIMARY KEY AutoIncrement not NULL, "); //get all the public properties in the entity classfield[] Fields =Clazz.getfields (); //Traverse all of the public properties for(Field field:fields) {//if the property is not _id, the description is a new field if(!field.getname (). Equals ("_id")) { //get the basic data type of the propertyString type =Field.gettype (). Getsimplename (); //if the property is of type string, set the field type to text if(Type.equals ("String") {sbuffer.append (Field.getname () )+ "TEXT,"); //If the attribute is of type int, set the field type to integer}Else if(Type.equals ("int") {sbuffer.append (Field.getname () )+ "INTEGER,"); } } } //remove the last commaSbuffer.deletecharat (Sbuffer.length ()-1); //replacement); Indicates the end of the SQL statementSbuffer.append (");"); //return this SQL statement returnsbuffer.tostring (); } }
2.Movie entity class, the attribute in the entity class is the field in the table
Public class Movie { public String title; Public int rating; Public String year; Public String genre; Public String country; Public int Price ;}
3. Add the following code to the Mainactivity.java
public class mainactivity extends Activity {@Override protected< /span> void OnCreate (Bundle savedinstancestate { super .oncreate (Savedinstancestate) ; Setcontentview (R.layout.activity_main); // instantiate our dbhelper dbhelper DBHelper = new dbhelper (this ); // DBHelper in OnCreate does not execute until this method is called Dbhelper.getreadabledatabase (); }}
4. We check whether the table has been built in the data/data/package name/databases/ladeng.db
Android makes it easy for SQLite to create a table with reflection