On the Android XUTILS3 framework using the method (a) article, mainly introduced the XUTIL3 annotation module, network module, picture loading module, today to bring you a database module explanation, now the mainstream ORM framework, such as Ormlite,greendao, Active Android,realm and so on, each of these frameworks has its own advantages and disadvantages, you can completely according to the actual needs of their projects to choose, the following start into today's database module introduction.
Today mainly brings you the following several modules:
How to create a delete table
How to check and delete the table and modify the operation
How to create a database and delete a database
How to establish a table on a table, multiple tables on a table, multiple tables on the foreign key operation of multiple tables.
People who believe that you know the ORM framework probably know that you can generate a table by simply creating a JavaBean object, adding a comment tag above and above the class. Let's take a look at the XUTILS3 entity Bean:
@Table (name= ' person ') public class Persontable {@Column (name= "id", isid=true,autogen=
true) private int id;
Name @Column (name= "name") private String name;
Ages @Column (name= "age") private int;
Gender @Column (name= "sex") Private String sex;
Wage @Column (name= "salary") private String salary; public int getId () {return id;} public void setId (int id) {this.id = ID;} public String GetName () {return name; pub LIC void SetName (string name) {this.name = name;} public string Getsex () {return sex;} public void Setsex (String sex)
{this.sex = sex;} public int getage () {return age;} public void Setage (int age) {this.age = age;} public String getsalary () {return Sal
ary public void Setsalary (String salary) {this.salary = salary} @Override public String toString () {return "persontable
[id= "+ ID +", name= "+ name +", age= "+ Age +", sex= "+ Sex +", salary= "+ salary +"] "; }
}
With the above entity bean, we need to be aware of the following points for the entity bean that corresponds to a table:
1. Add the @table tag above the class name, the value of the attribute name inside the tag is the name of the table of the database that is generated later
2. The attributes in the entity bean need to be tagged with the @column so that the value of the Name property of the label corresponds to the field of the table in the database.
3. The normal properties within the entity bean, without adding a @column tag, will not add fields to the table when the table is generated.
4. Entity beans must have a primary key, if there is no primary key, the table will not create success, @Column (name= "id", isid=true,autogen=true) the value of this property name represents the identity of the primary key of the table. Isid This property represents whether the property is a primary key of the table, Autogen is the primary key is self growing, and if you do not write Autogen This property, the default is the properties of the growth.
Now that you know how to write an entity bean, let's see how to create a database and how to generate a table in your program.
public class Xutil {
static dbmanager.daoconfig daoconfig;
public static Daoconfig Getdaoconfig () {
file File=new file (Environment.getexternalstoragedirectory (). GetPath ()) ;
if (daoconfig==null) {
daoconfig=new dbmanager.daoconfig ()
. Setdbname ("Shiyan.db")
. Setdbdir (file)
. Setdbversion (1)
. Setallowtransaction (True)
. Setdbupgradelistener (New Dbupgradelistener () {
@ Override public
void Onupgrade (Dbmanager db, int oldversion, int newversion) {
}
});
Return Daoconfig
}
}
Through the Xuti.getdaoconfig () method, we can get a Daoconfig object. Through the Getdaoconfig () method, we can know that this method can mainly do the following things:
1.setDbName setting the name of the database
2.setDbDir set the path for the database to be stored
3.setDbVersion set the version of the database
4.setAllowTransaction (true) setting allows transactions to be opened
5.setDbUpgradeListener setting up a version of the Monitor method of upgrade
So when exactly did we create the table? How do we create a table if we simply call the Xuti.getdaoconfig () method to create a table that persontable the person that corresponds to this entity?
It only takes a few steps:
1.DaoConfig Daoconfig=xutil.getdaoconfig ();
2.DbManager db = X.getdb (daoconfig);
What I'm going to tell you here is that database inside the creation of the table, only in your database operations involved in this table operation, will first determine whether the current table exists, if it does not exist, will create a table, if it exists, will be the corresponding CRUD operations, But as long as we want to make a table of CRUD operations, we have to do the above 2 steps, the popular point is that we must get a dbmanger this object, why do I say so? So let's take a look at Dbmanger's flesh first.
Dbmanager part of the source code is as follows:
Public interface Dbmanager extends closeable {daoconfig getdaoconfig ();
Sqlitedatabase getdatabase ();
/** * Save the list to database for an entity class or entity class, * If the ID of the type is generated automatically, the ID is assigned when the save is finished.
* * @param entity * @return * @throws dbexception/Boolean savebindingid (Object entity) throws dbexception;
/** * Save or update the list to database for an entity class or entity class, depending on the ID's data.
* * @param entity * @throws dbexception/void Saveorupdate (Object entity) throws dbexception;
/** * Save the entity class or entity class list to the database * * @param entity * @throws dbexception/Void Save (Object entity) throws dbexception;
/** * Save or update the list to database of entity classes or entity classes to determine whether the data exists based on ID and other unique indexes.
* * @param entity * @throws dbexception/void replace (Object entity) throws dbexception;
Delete void Deletebyid (class<?> EntityType, Object idvalue) throws dbexception;
void Delete (Object entity) throws dbexception;
void Delete (Class<?> EntityType) throws dbexception;
void Delete (Class<?> EntityType, Wherebuilder wherebuilder) throws dbexception; update void update (Object entity, String ... updatecolumnnames) throws dbexception;
void update (Object entity, Wherebuilder Wherebuilder, String ... updatecolumnnames) throws dbexception;
Find <T> T FindByID (class<t> EntityType, Object idvalue) throws dbexception;
<T> T FindFirst (class<t> EntityType) throws dbexception;
<T> list<t> findall (class<t> EntityType) throws dbexception;
<T> selector<t> Selector (class<t> EntityType) throws dbexception;
Dbmodel Finddbmodelfirst (Sqlinfo sqlinfo) throws dbexception;
List<dbmodel> Finddbmodelall (Sqlinfo sqlinfo) throws dbexception; Table/** * Delete Tables * * @param entitytype * @throws dbexception/void droptable (class<?> EntityType) thr
oWS dbexception;
/** * Add a column, * the properties of this column must be defined in the new EntityType. * * @param entitytype * @param column * @throws dbexception/void AddColumn (class<?> EntityType, String column) th
Rows dbexception; DB/** * Delete Library * * @throws dbexception/VOID dropdb () throws dbexception;
/** * Shut down the database, * xutils the link to the same library is a single-instance, generally do not need to close it.
* * @throws IOException */void Close () throws IOException;
custom void Execnonquery (Sqlinfo sqlinfo) throws dbexception;
void Execnonquery (String sql) throws dbexception;
Cursor ExecQuery (Sqlinfo sqlinfo) throws dbexception;
Cursor ExecQuery (String sql) throws dbexception; }
By dbmanager This class we know that mainly it does the following few things:
1.getDaoConfig Obtaining configuration information for the database
2.getDatabase Get Database instance
3.saveBindingId Saveorupdate Save 3 methods for inserting data (saving data)
4.replace only use caution if there is a unique index
4 Methods for 5.delete operations (delete data)
2 Methods of 6.update operation (modify data)
7.find Operation 6 ways (query data)
8.dropTable Delete Table
9.addColumn Add a column
10.dropDb Delete Database
Insert operation
private void Insert () {
try {
persontable person=new persontable ();
Person.setname ("Xiaoli");
Person.setage (a);
Person.setsex ("woman");
Person.setsalary (4000);
Db.save (person);
Db.saveorupdate (person);
Db.savebindingid (person);
} catch (Dbexception e) {
e.printstacktrace ();
}
}
The results are as follows:
The parameters required for the 3 insert operations are an entity bean. The difference between save and Saveorupdate is that when the primary key in an entity is the same, if you use Saveorupdate to replace the data that corresponds to the current primary key, the error will be made if you use save.
Savebindingid is mainly stored in data if the current table has a primary key round primary key for binding association.
When you're done with this method, you'll see that there is one more piece of data inside the person table in the database.
Query operations
The effects of the tables in the current database are as follows:
Use of 1.findById
This method mainly uses the value of the primary key to find the data in the table.
Requirements: Find data with ID 3 above the person table above
private void Query () {
try {
persontable person = Db.findbyid (Persontable.class, "2");
LOG.E ("Person", person.tostring ());
} catch (Dbexception e) {
e.printstacktrace ();
}
}
The results are as follows:
Use of 2.findFirst
The main method is to return the first data in the current table.
Requirements: Find the first piece of data in the person table above
private void Query () {
try {
persontable person = Db.findfirst (persontable.class);
LOG.E ("Person", person.tostring ());
} catch (Dbexception e) {
e.printstacktrace ();
}
}
Use of 3.findAll
The main method is to return all the data in the current table.
Requirements: Find all the data in the person table
private void Query () {
try {
list<persontable> persons = Db.findall (Persontable.class);
LOG.E ("Persons", persons.tostring ());
} catch (Dbexception e) {
e.printstacktrace ();
}
}
Use of 4.selector
This method is mainly used to search for certain conditions.
Requirements: Find data with age greater than 30 and gender as man in the person table
private void Query () {
try {
list<persontable> persons = Db.selector (Persontable.class). WHERE ("Age", " > "," ("sex", "=", "man"). FindAll ();
for (persontable person:persons) {
log.e (' person ', person.tostring ());
}
catch (Dbexception e) {
E.printstacktrace ();
}
Use of 5.findDbModelFirst
Speaking of this method, the method returns a Dbmodel object, what is the object?
Dbmobel source code is as follows:
Public final class Dbmodel {/** * key:columnname * value:valuestr/private hashmap<string, string> Datamap = n
EW hashmap<string, string> (); public string getString (string columnName) {return datamap.get (columnName);} public int getInt (string columnName) {Retu
RN integer.valueof (Datamap.get (columnName)); public boolean Getboolean (string columnName) {String value = Datamap.get (columnName); if (value!= null) {return value . Length () = 1?
"1". Equals (value): boolean.valueof (value);
return false; Public double getdouble (String columnName) {return double.valueof (Datamap.get (ColumnName));} public float getfloat (St Ring columnName) {return float.valueof (Datamap.get (columnName)), Public long Getlong (String columnName) {return LONG.V
Alueof (Datamap.get (columnName)); Public Date getDate (String columnName) {Long date = long.valueof (Datamap.get (ColumnName)), return new date (date); pub Lic java.sql.Date getsqldate (String columnName) {Long Date = long.valueof (datAmap.get (ColumnName));
return new Java.sql.Date (Date);
public void Add (string columnName, String valuestr) {datamap.put (columnName, VALUESTR);/** * @return Key:columnname * * Public hashmap<string, string> Getdatamap () {return datamap;}/** * @param columnName * @return/public bool Ean IsEmpty (String columnName) {return Textutils.isempty (Datamap.get (ColumnName));}
Through the source code, we found that Dbmodel essence is a key for the current table of the field, value is the current record of the value of a hashmap.
Requirements: How old is the age of the person who finds the first data in the People table.
private void Query () {
try {
Dbmodel model = Db.finddbmodelfirst (New Sqlinfo ("SELECT * from person"));
LOG.E (' Age ', model.getstring ("Age '));
} catch (Dbexception e) {
e.printstacktrace ();
}
}
Note that the Sqlinfo object is created with a constructor parameter that requires only one SQL statement to be passed in.
The use of 6.findDbModelAll
The purpose of this method is to return a collection of fields that satisfy all the data for sqlinfo information.
Requirements: Find names of everyone in the person table with age older than 25
private void Query () {
try {
list<dbmodel> persons = Db.finddbmodelall (new Sqlinfo ("SELECT * from person W") here >));
for (Dbmodel person:persons) {
log.e ("name", Person.getstring ("name"));
}
catch (Dbexception e) {
e.printstacktrace ();
}
Basically put the query 6 ways to say it again, of course, the above 6 kinds of requirements may not be completely using the above query method can find out the results, I am so the purpose of the query is to lead everyone familiar with the XUTILS3 of the 6 query method is how to use, will be the above 6 methods, I believe your query will not have too much problem, As for the complex query is nothing more than the basic skills of SQL statements, we hurriedly practice it.
Modify Operation
The effects of the tables in the current database are as follows:
There are 2 different ways to modify:
First type:
Requirement: We change the age of the record with ID 1 above to 25 years old
private void Update () {
try{
persontable person = Db.findbyid (Persontable.class, 1);
Person.setage (a);
Db.update (person, ' age ');
} catch (Exception e) {
e.printstacktrace ();
}
}
By way of this, we know that we first have to find the entity bean with ID 1 by Dbmanager, and if you need to modify which field in it, you just need to reset the value of this property. The Dbmanager.update method is then called, the first parameter is the entity that needs to be modified, and the second parameter is the corresponding property.
The second type:
Requirements: The salary salary for man in the person table becomes 6000.
private void Update () {
try {
list<persontable> persons = Db.findall (Persontable.class);
for (persontable person:persons) {
person.setsalary (6000);
Db.update (person, wherebuilder.b ("sex", "=", "Mans"), "salary");
}
catch (Exception e) {
e.printstacktrace ();
}
}
There are 2 ways to modify the data, basically need an entity bean object to operate, the second method above is to modify the data, a more restrictive conditions, so that the modification of the data appears flexible.
The parameters of the second Update method above are briefly described:
First argument: Entity Bean object
Second parameter: A Wherebuilder object that constructs a where condition statement mainly by static B method
Third parameter: Need to modify the field name, if your requirement is to modify 2 or more fields, just add the corresponding parameters, such as the second method I more than modify salary also need to modify the age of 40 years, refer to the following;
private void Update () {
try {
list<persontable> persons = Db.findall (Persontable.class);
for (persontable person:persons) {
person.setsalary (6000);
Person.setage ();
Db.update (person, wherebuilder.b ("sex", "=", "Mans"), "salary", "age");
}
catch (Exception e) {
e.printstacktrace ();
}
}
Delete operation
The effect of the person table in the current database is as follows:
The use of 1.deleteById
This method is mainly based on the primary key of the table to delete a single record
Requirements: Delete the record with ID 5 in the above person table
private void Delete () {
try {
Db.deletebyid (Persontable.class, 5);
} catch (Dbexception e) {
E.printstacktrace ();
}
The results are as follows:
Use of 2.delete (Object entity)
This method is mainly based on the entity bean to delete one or more of the data in the table
Requirements: Delete name for camel This record of information
private void Delete () {
try {
persontable person = db.selector (Persontable.class). WHERE ("name", "=", "Camel"). FindFirst ();
Db.delete (person);
} catch (Dbexception e) {
e.printstacktrace ();
}
}
3.delete (class<?> EntityType)
This method is mainly used to delete all the data in the table, but note: The table will still exist, but the data in the table is not
private void Delete () {
try {
db.delete (persontable.class);
} catch (Dbexception e) {
E.printstacktrace ();
}
4.delete (class<?> EntityType, Wherebuilder wherebuilder)
This method is mainly based on the conditions of the WHERE statement to delete operations
Requirements: Delete the person table total sex as woman and salary to 5000
private void Delete () {
try {
db.delete (Persontable.class, wherebuilder.b ("sex", "=", "Woman"). and ("Salary", " = "," 5000 "));
} catch (Dbexception e) {
e.printstacktrace ();
}
}
5.dropTable (class<?> EntityType)
This method is used to delete the table
private void Delete () {
try {
db.droptable (persontable.class);
} catch (Dbexception e) {
E.printstacktrace ();
}
6.dropDb ()
This method is used to delete the database
Db.dropdb ();
Other methods
1.addColumn (class<> EntityType, String column)
Requirements: Add a Country field to the table above
The Persontable entity code is as follows:
@Table (name= "Person") public class Persontable {@Column (name= "id", isid=true,autogen=true) private int id;//Name @Column (
Name= "name") private String name;
Ages @Column (name= "age") private int;
Gender @Column (name= "sex") Private String sex;
Wage @Column (name= "salary") private int salary;
National @Column (name= "Country", property= "China") private String country; public int getId () {return id;} public void setId (int id) {this.id = ID;} public String GetName () {return name; pub LIC void SetName (string name) {this.name = name;} public string Getsex () {return sex;} public void Setsex (String sex)
{this.sex = sex;} public int getage () {return age;} public void Setage (int age) {this.age = age;} public int getsalary () {return salary
; The public void setsalary (int salary) {this.salary = salary} is public String getcountry () {return country;} public void S Etcountry (String country) {this.country = country} @Override public String toString () {return "persontable [id=" + ID + ", name=" + name + ", age=" + Age + ", sex=" + Sex + ", salary=" + salary + ", country=" + Country + "]; } The private void AddColumn () {try {db.addcolumn (Persontable.class, "Country");} catch (Dbexception e) {e.printstacktr
Ace (); }
}
After executing the AddColumn method, we see a country field in the person table.
The results are as follows:
Summarize
The above mainly introduces the XUTILS3 database module, including how to create a database, how to create a table, how to add a column to the table, how to modify the table to check the operation. Said so much, I believe you must have a basic understanding of the XUTILS3 database module, as for a table on a table, multiple tables on a table, more than table for multiple tables and so on such requirements, is to add a field in a table, or create a third-party table to maintain the relationship between table and table, This type of example I do not say that the reason is that those needs are inseparable from the above changes in the method, I believe you as long as the above method will be used completely, your XUTILS3 database module Basic use will not have a problem.