Another method for adding, deleting, modifying, and querying android databases is to add, delete, and modify android databases.

Source: Internet
Author: User

Another method for adding, deleting, modifying, and querying android databases is to add, delete, and modify android databases.

Instructor notes

#3 add, delete, modify, and query methods in Android

1. Create a help class object, call the getReadableDatabase method, and return a SqliteDatebase object

2. Use the SqliteDatebase object to call the insert, update, delete, and query methods for addition, deletion, modification, and query.

* ***** Features: added, deleted, modified, and returned values can be used to determine whether the SQL statement is successfully executed. However, the query is not flexible enough and you cannot perform multi-table queries. Therefore, the second method is preferred for adding, deleting, and modifying common users in the company, and the first method is used for query.

Private MySqliteOpenHelper mySqliteOpenHelper;
Public InfoDao (Context context ){
// Create a help Class Object
MySqliteOpenHelper = new MySqliteOpenHelper (context );
}

Public boolean add (InfoBean bean ){

// SqliteDatabase object is required for SQL statement execution
// Call the getReadableDatabase method to initialize database creation
SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase ();


ContentValues values = new ContentValues (); // It is an object encapsulated by map and used to store values.
Values. put ("name", bean. name );
Values. put ("phone", bean. phone );

// Table: table name. nullColumnHack: It can be empty. It indicates adding an empty row. values: the value of a Data row. Return Value: indicates the Id of the new row to be added.-1 indicates adding failed.
Long result = db. insert ("info", null, values); // The underlying layer is the assembled SQL statement.

// Closes the database object
Db. close ();

If (result! =-1) {//-1 indicates that the addition failed.
Return true;
} Else {
Return false;
}
}

Public int del (String name ){

// SqliteDatabase object is required for SQL statement execution
// Call the getReadableDatabase method to initialize database creation
SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase ();

// Table: table Name, whereClause: delete condition, whereArgs: parameter of the placeholder condition; Return Value: number of rows deleted successfully
Int result = db. delete ("info", "name =? ", New String [] {name });
// Closes the database object
Db. close ();

Return result;

}
Public int update (InfoBean bean ){

// SqliteDatabase object is required for SQL statement execution
// Call the getReadableDatabase method to initialize database creation
SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase ();
ContentValues values = new ContentValues (); // It is an object encapsulated by map and used to store values.
Values. put ("phone", bean. phone );
// Table: table Name, values: updated value, whereClause: Updated condition, whereArgs: The placeholder value of the updated condition, return value: How many rows are modified successfully
Int result = db. update ("info", values, "name =? ", New String [] {bean. name });
// Closes the database object
Db. close ();
Return result;

}
Public void query (String name ){

// SqliteDatabase object is required for SQL statement execution
// Call the getReadableDatabase method to initialize database creation
SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase ();

// Table: table Name, columns: name of the queried column. If the value is null, all columns are queried. selection: Query condition, selectionArgs: parameter value of the condition placeholder,
// GroupBy: by what field grouping, having: grouping condition, orderBy: by what field sorting
Cursor cursor = db. query ("info", new String [] {"_ id", "name", "phone"}, "name =? ", New String [] {name}, null, null," _ id desc ");
// Parse data in Cursor
If (cursor! = Null & cursor. getCount ()> 0) {// checks whether data exists in the cursor.

// Cyclically traverse the result set to obtain the content of each row
While (cursor. moveToNext () {// condition, can the cursor locate to the next row?
// Obtain data
Int id = cursor. getInt (0 );
String name_str = cursor. getString (1 );
String phone = cursor. getString (2 );
System. out. println ("_ id:" + id + "; name:" + name_str + "; phone:" + phone );


}
Cursor. close (); // close the result set.

}
// Closes the database object
Db. close ();

}

Master

Package com. itheima. crud; import android. app. activity; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. toast; import com. itheima. crud2.R; import com. itheima. crud. bean. infoBean; import com. itheima. crud. dao. infoDao; public class MainActivity extends Activity implements OnClickListener {private Context mContext; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); mContext = this; // create a help Class Object MySqliteOpenHelper mySqliteOpenHelper = new helper (mContext); // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = MySqliteOpenHelper. getReadableDatabase (); // find the findViewById (R. id. bt_add ). setOnClickListener (this); findViewById (R. id. bt_del ). setOnClickListener (this); findViewById (R. id. bt_update ). setOnClickListener (this); findViewById (R. id. bt_query ). setOnClickListener (this) ;}@ Override public void onClick (View v) {InfoDao infoDao = new InfoDao (mContext); // create a dao object for addition, deletion, modification, and query switch (v. getId () {case R. id. bt_add: InfoBean bean = new InfoBean (); bean. name = "Zhang San"; bean. phone = "110"; boolean result = infoDao. add (bean); if (result) {Toast. makeText (mContext, "added successfully", 0 ). show ();} else {Toast. makeText (mContext, "failed to add", 0 ). show ();} break; case R. id. bt_del: int del = infoDao. del ("James"); Toast. makeText (mContext, "successfully deleted" + del + "row", 0 ). show (); break; case R. id. bt_update: InfoBean bean2 = new InfoBean (); bean2.name = "zhangsan"; bean2.phone = "119"; int update = infoDao. update (bean2); Toast. makeText (mContext, "modified successfully" + update + "row", 0 ). show (); break; case R. id. bt_query: infoDao. query ("Zhang San"); break; default: break ;}}}

 

Create a database for the class under the same package

Package com. itheima. crud; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteDatabase. cursorFactory; import android. database. sqlite. SQLiteOpenHelper; public class MySqliteOpenHelper extends SQLiteOpenHelper {public MySqliteOpenHelper (Context context) {// context: Context, name: database file name factory: used to create a cursor object, the default value is null // version: the database version number. The onUpgrade method will be called if it changes from 1. After 4.0, the super (context, "info. db ", null, 1);} // The oncreate method is called when the database is created for the first time. It is especially suitable for table structure initialization and SQL statements need to be executed; SQLiteDatabase db can be used to execute SQL statements @ Override public void onCreate (SQLiteDatabase db) {// execute the SQL statement db.exe cSQL ("create table info (_ id integer primary key autoincrement, name varchar (20), phone varchar (11) for creating a table through SQLiteDatabase )) ");} // The onUpgrade database will be executed only when the version number of the database changes. It is particularly suitable for modifying the table structure @ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// add a phone field // db.exe cSQL ("alter table info add phone varchar (11 )");}}

 

Add, delete, modify, and query package name Encapsulation

Package com. itheima. crud. dao; import android. content. contentValues; import android. content. context; import android. database. cursor; import android. database. sqlite. SQLiteDatabase; import com. itheima. crud. mySqliteOpenHelper; import com. itheima. crud. bean. infoBean; public class InfoDao {private MySqliteOpenHelper mySqliteOpenHelper; public InfoDao (Context context) {// create a help class Object mySqliteOpenHelper = new MySqli TeOpenHelper (context);} public boolean add (InfoBean bean) {// The sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); ContentValues values = new ContentValues (); // It is an object encapsulated by map and used to store value values. put ("name", bean. name); values. put ("phone", bean. phone); // table: table Name, nullColumnHack: Can be empty, indicating that an empty row is added. values: the value of a Data row. Return Value: indicates the Id of the new row to be added, -1 indicates that the addition fails. Ong result = db. insert ("info", null, values); // The underlying layer is the assembled SQL statement // close the database object db. close (); if (result! =-1) {//-1 indicates failed return true;} else {return false;} public int del (String name) {// sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); // table: table Name, whereClause: delete condition, whereArgs: parameter of the placeholder condition; Return Value: number of rows deleted successfully int result = db. delete ("info", "name =? ", New String [] {name}); // closes the database object db. close (); return result;} public int update (InfoBean bean) {// The sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); ContentValues values = new ContentValues (); // It is an object encapsulated by map and used to store value values. put ("phone", bean. phone); // table: table Name, values: updated value, whereClause: Updated condition, whereArgs: The placeholder value of the updated condition, return value: successfully modified number of rows int r Esult = db. update ("info", values, "name =? ", New String [] {bean. name}); // closes the database object db. close (); return result;} public void query (String name) {// sqliteDatabase object is required to execute the SQL statement // call the getReadableDatabase method to initialize the database creation SQLiteDatabase db = mySqliteOpenHelper. getReadableDatabase (); // table: table Name, columns: column name to be queried. If null represents all columns to be queried. selection: Query condition, selectionArgs: parameter value of the condition placeholder, // groupBy: group by field, having: group condition, orderBy: sort by field Cursor cursor = db. query ("info", new String [] {"_ Id", "name", "phone"}, "name =? ", New String [] {name}, null, null," _ id desc "); // parse the data in Cursor if (cursor! = Null & cursor. getCount ()> 0) {// checks whether data exists in the cursor. // traverses the result set cyclically and obtains the content of each row while (cursor. moveToNext () {// condition. Can the cursor locate the next row? // get the data int id = cursor. getInt (0); String name_str = cursor. getString (1); String phone = cursor. getString (2); System. out. println ("_ id:" + id + "; name:" + name_str + "; phone:" + phone) ;}cursor. close (); // close the result set} // close the database object db. close ();}}

 

Data encapsulation also uses a package

package com.itheima.crud.bean;public class InfoBean {    public  String name;    public String phone;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.