Database database additions and deletions change
Add to
Insert into info (name,phone) VALUES (' Zhangsan ', ' 110 ')
Delete
Delete from info where name= ' Zhangsan '
Modify
Update info Set phone = ' 999 ' WHERE name = ' Zhangsan '
Inquire
SELECT * FROM info where name= ' Zhangsan '
Android under the database additions and deletions to search
- Void-db.execsql () Increased deletion
- Cursor-db.rawquery () query
注意:操作数据库 一定要记得把数据库**连接**给关闭掉。 cursor 用完后,也记得关闭
Getreadabledatabase () Getwriteabledatabase () returns an instance of the same database, the difference being whether the database is locked when it returns.
Use the Sqlite3 tool to view the contents of a database
Sqlite3 xxx.db
If there is a garbled language, you need to modify the CMD encoding set
65001 Utf-8
CHCP 65001 Change the encoding of the CMD window, default is gb2312
Create database steps under Android
- Class inheritance Sqliteopenhelper (Help class for data creation, Oncreate,onupgrade)
Build Construction method
/** * 创建一个数据库帮助类,去创建/打开/管理 数据库 * @param context 上下文 * @param name 设置数据库名称 * @param factory CursorFactory 定义一个结果集,游标工厂。 * Cursor 游标(结果集,保存了对数据库的引用,指针) * 设置为null,表示调用默认游标 * @param version 数据库的版本,从1开始 */ public MySqliteDB(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub }
Override the OnCreate (Sqlitedatabase db) method, which is called the first time the database is created. Fits the initialization of the database table structure.
CREATE table info (_id integer primary key autoincrement, name varchar, phone varchar (20))
Overrides Onupgrade (sqlitedatabase db, int oldversion, int newversion), the method that is called when the database is updated. The version number of the database is incremented when it is called.
- Add a constructor method for the helper class. Specifies the name of the database, the version number, and the cursor factory default NULL
Location of database file creation
/data/data/Package Name/databases/xxx.db
The database does not specify content when it is created, and the default is to create only one table metadata save the system locale.
Cursor cursor
- A pointer to a reference to the database is saved. is set to NULL, which means that the default cursor is called.
- Default starting position is-1
Common methods:
boolean move(int offset) Move the cursor by a relative amount, forward or backward, from the current position. boolean moveToFirst() Move the cursor to the first row. boolean moveToLast() Move the cursor to the last row. boolean moveToNext() Move the cursor to the next row. boolean moveToPosition(int position) Move the cursor to an absolute position. boolean moveToPrevious()
How to prevent SQL statement injection
Method: Binding Parameters
//示例xx.exeSQL("insert into person(name,age) values (?,?)",new Object[]{name,age})
Sqlite3The command
- Sqlite3 < database name > View database, enter SQLite mode
- . Tables View all Tables
- . Mode column | List | Insert | Line | Tabs | Tcl | CSV Change output format
- . Schema View DDL statements for all tables in the library
- . Headers on/Off display table header default off
- . Nullvaluenull empty Value data display problem
- . dump< table name > Generate SQL script to form table
- . Dump generates SQL scripts for the entire database
- . Exit exits
- . Help View assistance
(Focus) class Sqlitedatabase(API implementation database is being censored)
Inserting data
long insert(String table, String nullColumnHack, ContentValues values)
Delete data
int delete(String table, String whereClause, String[] whereArgs)
modifying data
int update(String table, ContentValues values, String whereClause, String[] whereArgs)
Querying data
Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) Query the given URL, returning a Cursor over the result set. Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) Query the given table, returning a Cursor over the result set. Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Advantages and disadvantages of two methods of adding and deleting
- Write your own SQL statement
- High degree of freedom and flexibility
- High efficiency and low resource consumption
- cascading queries for tables can be implemented
- Google's off-the-shelf API
- Convenient, easy to make mistakes
- Resource overhead is relatively high and the efficiency is slightly lower
(focus) Transactions of the database
Benefits: Safe, efficient
Ensure that the operation succeeds at the same time or fails at the same time. Bank transfer
A->b Remittance A-100 Block B + 100 block
Template code for a transaction
//开启事务 db.beginTransaction(); try { ... 处理业务逻辑A ... //设置成功(回滚)点,即要么全成功要么全失败 db.setTransactionSuccessful(); ... 处理业务逻辑B ... //设置成功(回滚)点。(同时操作若干个动作时可以设置多个成功点) db.setTransactionSuccessful(); ... } finally { //结束事务 db.endTransaction(); //千万不要忘记干掉这个 db.close(); }
(focus) The contents of the database are synchronized to the interface (ListView). How the ListView Works
MVC design pattern. * Model Data Models Person * View ListView * Controller controllers Adapter data adapters to organize data collections into interfaces in a specific way
Self-understanding: the ListView + adapter mechanism, when needed to create TextView objects to create objects based on the number of bars that the current screen can display, to display the past (previously appearing on the screen, And then disappearing entries) the entry object will be re-assigned to the new value (that is, the new entry shown)
Listview Use steps
- Write UI interface XML file ListView
- Find a ListView
- Implementing the data adapter for the ListView adapter
- Set the adapter to the ListView, and once the adapter is set, the view is requested from this method
The development of how to customize the data adapter to implement a complex UI interface.
- Defining the ListView Layout
- Find a ListView
- Customizing a complex Baseadapter
- GetCount (); Returns the number of entries list.size ()
- GetView (); Returns the View object for each entry
Define an XML file View view = View.inflate (mainactivity.this, r.layout.rl_item, NULL); Modify the View object display content View.findviewbyid ();
- Set adapter for the ListView
(key) Pump--layoutinflater
How do I convert an XML data (layout file) to a View object? Populates an XML layout file into a View object for addition to other view containers.
simpleadapter--Display Picture text information arrayadapter--can only display pictures
android dialog box
Builder
ProgressDialog * Progress dialog box
Finishing Supplement: Content providers
Database files are generally private. -rw-rw----Other applications are not able to access private databases.
Purpose: To ensure the security of application data. Each application is independent and can not manipulate data from another application database.
There are special requirements that need to expose their own private databases to other applications for access by other applications.
The content provider is the one who does it.
Steps created by the content provider (
Understanding Principle)
- Dayifuprovider Extend ContentProvider
- The content provider is configured inside the manifest file. Xml. Configure the full classpath, host name.
android:name="com.itheima.db.DaYifuProvider"
android:authorities="com.itheima.db.persondb"
- Dayifuprovider defines some data manipulation URIs using Urimatcher to specify some special paths Content://com.itheima.db.persondb/query queries content:// Com.itheima.db.persondb/insert Add Content://com.itheima.db.persondb/delete Delete content://com.itheima.db.persondb/ Update updates
- Realize the method of Dayifuprovider adding and deleting. According to the business requirements to achieve. Implement the Query method, 1. Check that the path URI is correct. 2. If the cursor is returned correctly 3. If the exception is thrown incorrectly.
How to query data by using content providers
- Gets the parser for the content provider
ContentResolver resolver = getContentResolver();
- Use resolver for the operation of the increase and deletion check.
Android Database SQLite