# #在Android中创建一个数据库 # #
# # #步骤 # #
1. Create a class to inherit Sqliteopenhelper and override the constructor method, OnCreate method, Ongrade method of the parent class in the class (the version of the database can only be upgraded and cannot be degraded)
# # #数据库增删改查方法 # #
public void Add (view view) {
Sqlitedatabase db = Sql.getwritabledatabase ();
Random random = new random ();
Add a single piece of data to the database
Db.execsql ("INSERT into info (name,phone) VALUES (?,?)", New object[]{"Zhang San", "123456"});
Db.execsql ("INSERT into info (name,phone) VALUES (?,?)", New object[]{"John Doe", "654321"});
Toast.maketext (This, "Add successfully!", Toast.length_short). Show ();
Db.close ();
}
public void Delete (view view) {
Sqlitedatabase db = Sql.getwritabledatabase ();
Delete the specified data in the database
Db.execsql ("delete from info where name=?", New object[]{"Zhang San"});
Toast.maketext (This, "Delete successfully!", Toast.length_short). Show ();
Db.close ();
}
public void Upgrade (view view) {
Sqlitedatabase db = Sql.getwritabledatabase ();
Modify the specified data in the database
Db.execsql ("Update info set phone=?") Where Name=? ", New object[]{" 111111 "," John Doe "});
Toast.maketext (This, "Upgrade successfully!", Toast.length_short). Show ();
Db.close ();
}
public void Checkall (view view) {
Sqlitedatabase db = Sql.getreadabledatabase ();
Querying the database and returning the cursor set cursors
cursor cursor = db.rawquery ("SELECT * from info", NULL);
Create a list collection
List<person>list = new arraylist<person> ();
Traversing database data through a while loop
while (Cursor.movetonext ()) {
person person = new person ();
Person.setid (Cursor.getint (Cursor.getcolumnindex ("_id"));
Person.setname (Cursor.getstring (Cursor.getcolumnindex ("name"));
Person.setphone (Cursor.getstring (Cursor.getcolumnindex ("Phone"));
List.add (person);
Person=null;
}
Cursor.close ();
Traversing the list collection
for (person P:list) {
System.out.println (P.tostring ());
}
Toast.maketext (This, "Checkall successfully!", Toast.length_short). Show ();
Db.close ();
}
Create DATABASE learning notes under Android